Skip to content

Serialization

dumps and loads encode a stable Quivers Indexed Effect Core (QIEC) graph as JSON text and decode it again, so that a module can be stored and rebuilt. A decoded module is checked again, and running it needs the runtime providers that its entry computations require. The QIEC developer note states the format.

serialization

Canonical wire codec for stable QIEC graphs.

The codec is an explicit allowlist, not a generic Python object serializer. Only frozen kernel records, concrete identifier classes, kernel enums, tuples, bytes, and JSON scalars cross the boundary. Runtime attachments, handler callbacks, modules, mappings, and unknown future node tags are rejected.

QIEC_WIRE_FORMAT module-attribute

QIEC_WIRE_FORMAT = 'qiec-json/v3'

The format tag every encoded document carries, checked on decoding.

JsonValue

JsonValue = None | bool | int | float | str | list[JsonValue] | dict[str, JsonValue]

A JSON document as json.loads returns it and json.dumps accepts it.

SerializationError

Bases: ValueError

A value is not in the stable QIEC wire language.

to_data

to_data(value: object) -> dict[str, JsonValue]

Encode a stable QIEC graph in its versioned wire envelope.

PARAMETER DESCRIPTION
value

The graph to encode.

TYPE: object

RETURNS DESCRIPTION
dict[str, JsonValue]

The envelope, carrying the wire format and the ABI alongside the graph. Both are recorded because neither can be guessed from the payload, and a reader that guessed wrong would misread it.

RAISES DESCRIPTION
SerializationError

If the graph contains a value that may not cross the boundary, or a typed hole: a module with holes has no stable form, and the message lists every hole.

Source code in src/quivers/qiec/serialization.py
def to_data(value: object) -> dict[str, JsonValue]:
    """Encode a stable QIEC graph in its versioned wire envelope.

    Parameters
    ----------
    value : object
        The graph to encode.

    Returns
    -------
    dict[str, JsonValue]
        The envelope, carrying the wire format and the ABI alongside the
        graph. Both are recorded because neither can be guessed from the
        payload, and a reader that guessed wrong would misread it.

    Raises
    ------
    SerializationError
        If the graph contains a value that may not cross the boundary, or a
        typed hole: a module with holes has no stable form, and the message
        lists every hole.
    """
    try:
        refuse_holes(value, action="serialization to stable QIEC")
    except HoleError as error:
        raise SerializationError(str(error)) from error
    return {
        "$schema": QIEC_WIRE_FORMAT,
        "abi": QIEC_ABI,
        "root": _encode(value),
    }

from_data

from_data(data: object) -> object

Decode a QIEC graph, rejecting other ABIs and unknown node tags.

PARAMETER DESCRIPTION
data

The decoded envelope.

TYPE: object

RETURNS DESCRIPTION
object

The reconstructed graph.

RAISES DESCRIPTION
SerializationError

If the envelope is malformed, declares another wire format or ABI, or holds a graph that fails to decode. An ABI mismatch is refused rather than attempted, since a payload from another version may use the same tags for different shapes.

Source code in src/quivers/qiec/serialization.py
def from_data(data: object) -> object:
    """Decode a QIEC graph, rejecting other ABIs and unknown node tags.

    Parameters
    ----------
    data : object
        The decoded envelope.

    Returns
    -------
    object
        The reconstructed graph.

    Raises
    ------
    SerializationError
        If the envelope is malformed, declares another wire format or
        ABI, or holds a graph that fails to decode. An ABI mismatch is
        refused rather than attempted, since a payload from another
        version may use the same tags for different shapes.
    """
    if not isinstance(data, dict) or any(not isinstance(key, str) for key in data):
        raise SerializationError("QIEC wire envelope must be an object")
    typed = cast(dict[str, JsonValue], data)
    _exact_keys(typed, {"$schema", "abi", "root"}, "QIEC wire envelope")
    if typed["$schema"] != QIEC_WIRE_FORMAT:
        raise SerializationError(f"unsupported QIEC wire format {typed['$schema']!r}")
    if typed["abi"] != QIEC_ABI:
        raise SerializationError(
            f"QIEC ABI mismatch: expected {QIEC_ABI!r}, got {typed['abi']!r}"
        )
    return _decode(typed["root"])

dumps

dumps(value: object) -> str

Serialize a QIEC graph as deterministic UTF-8-compatible JSON text.

PARAMETER DESCRIPTION
value

The graph to serialize.

TYPE: object

RETURNS DESCRIPTION
str

Compact, key-sorted JSON. Determinism matters because identities downstream are content addressed: the same graph must produce the same bytes on every run and every platform.

RAISES DESCRIPTION
SerializationError

If the graph contains a value that may not cross the boundary.

Source code in src/quivers/qiec/serialization.py
def dumps(value: object) -> str:
    """Serialize a QIEC graph as deterministic UTF-8-compatible JSON text.

    Parameters
    ----------
    value : object
        The graph to serialize.

    Returns
    -------
    str
        Compact, key-sorted JSON. Determinism matters because identities
        downstream are content addressed: the same graph must produce the
        same bytes on every run and every platform.

    Raises
    ------
    SerializationError
        If the graph contains a value that may not cross the boundary.
    """
    return json.dumps(
        to_data(value),
        ensure_ascii=False,
        allow_nan=False,
        separators=(",", ":"),
        sort_keys=True,
    )

loads

loads(text: str | bytes | bytearray) -> object

Deserialize one canonical QIEC JSON document.

PARAMETER DESCRIPTION
text

The document to read.

TYPE: str or bytes or bytearray

RETURNS DESCRIPTION
object

The reconstructed graph.

RAISES DESCRIPTION
SerializationError

If the text is not valid JSON, repeats an object key at any depth, or fails any of the decoding checks.

Source code in src/quivers/qiec/serialization.py
def loads(text: str | bytes | bytearray) -> object:
    """Deserialize one canonical QIEC JSON document.

    Parameters
    ----------
    text : str or bytes or bytearray
        The document to read.

    Returns
    -------
    object
        The reconstructed graph.

    Raises
    ------
    SerializationError
        If the text is not valid JSON, repeats an object key at any
        depth, or fails any of the decoding checks.
    """
    try:
        data = json.loads(text, object_pairs_hook=_unique_object)
    except (json.JSONDecodeError, UnicodeDecodeError) as error:
        raise SerializationError(f"invalid QIEC JSON: {error}") from error
    return from_data(data)

Sparse relations

RationalRelationSpec.of records the topology and semiring of a sparse relation. The wire record preserves each tape's alphabet name and cardinality, the domain and codomain split, and every arc and boundary occurrence in order. Two equal arc records still have different positions. The slot at each position in weight_names refers to the ParameterId at the same position in weight_parameters. Repeating an identity shares a weight across slots.

A decoded specification uses bind to resolve those identities in an explicit runtime mapping. Each trainable value is the caller's original scalar torch.nn.Parameter. A constant may be a scalar leaf tensor. All supplied values that the relation uses must share a dtype and device and satisfy the semiring's carrier. The bind checks the current values, and each score reads and checks them again. The wire record contains the identities and topology. Tensor values and runtime providers belong to the binding.

RationalRelationSpec didactic-model

RationalRelationSpec(*, tapes: tuple[tuple[str, int], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), input_tapes: int, n_states: int, arcs: tuple[tuple[int, int, tuple[Label, ...], int], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), initial: tuple[tuple[int, int], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), final: tuple[tuple[int, int], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), weight_names: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), weight_parameters: tuple[ParameterId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), algebra: ClaimSubject)

Bases: QiecModel

An ordered sparse topology with a stable parameter identity for each slot.

Tape records contain the alphabet's nominal name and cardinality, in tape order. Arc records contain source, target, labels, and a weight slot, in occurrence order. Initial and final records contain a state and a weight slot. A label of None denotes epsilon.

The order of weight_names names the local slots. The corresponding entries of weight_parameters can repeat a ParameterId. This ties weight values without identifying arc or boundary occurrences. algebra states the trusted claim subject of a shipped scalar semiring. Live values are supplied to bind after decoding.

PARAMETER DESCRIPTION
tapes

The nominal alphabet name and cardinality of each tape.

TYPE: tuple of pairs of str and int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

input_tapes

The number of leading tapes in the domain.

TYPE: int

n_states

The number of states, indexed from zero.

TYPE: int

arcs

Source, target, tape labels, and weight slot for each arc occurrence.

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

initial

Initial-state and weight-slot records.

TYPE: tuple of pairs of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

final

Final-state and weight-slot records.

TYPE: tuple of pairs of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

weight_names

The distinct names of the relation's local weight slots.

TYPE: tuple of str DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

weight_parameters

The stable parameter identity for each slot.

TYPE: tuple of ParameterId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

algebra

The trusted identity of the scalar semiring.

TYPE: ClaimSubject

topology cached property

topology: RelationTopology

Reconstruct the topology and its sparse indexes.

RETURNS DESCRIPTION
RelationTopology

The validated, indexed topology of the specification.

of classmethod

of(topology: RelationTopology, algebra: Semiring, weight_parameters: tuple[ParameterId, ...]) -> RationalRelationSpec

Describe a sparse topology and its weight identities as QIEC data.

The topology uses the shipped string sets, finite alphabets, arcs and boundaries. The algebra must be a shipped scalar semiring singleton from the kernel registry.

PARAMETER DESCRIPTION
topology

The ordered sparse topology to encode.

TYPE: RelationTopology

algebra

The registered scalar semiring of the relation.

TYPE: Semiring

weight_parameters

One stable identity per weight slot.

TYPE: tuple of ParameterId

RETURNS DESCRIPTION
RationalRelationSpec

The validated specification.

RAISES DESCRIPTION
TypeError

If the topology representation or algebra is unsupported.

Source code in src/quivers/qiec/relations.py
@classmethod
def of(
    cls,
    topology: RelationTopology,
    algebra: Semiring,
    weight_parameters: tuple[ParameterId, ...],
) -> RationalRelationSpec:
    """Describe a sparse topology and its weight identities as QIEC data.

    The topology uses the shipped string sets, finite alphabets, arcs
    and boundaries. The algebra must be a shipped scalar semiring
    singleton from the kernel registry.

    Parameters
    ----------
    topology : RelationTopology
        The ordered sparse topology to encode.
    algebra : Semiring
        The registered scalar semiring of the relation.
    weight_parameters : tuple of ParameterId
        One stable identity per weight slot.

    Returns
    -------
    RationalRelationSpec
        The validated specification.

    Raises
    ------
    TypeError
        If the topology representation or algebra is unsupported.
    """
    if (
        type(topology) is not RelationTopology
        or any(
            type(tape) is not StringSet or type(tape.alphabet) is not FinSet
            for tape in topology.tapes
        )
        or any(type(arc) is not Arc for arc in topology.arcs)
        or any(
            type(mark) is not Boundary
            for mark in (*topology.initial, *topology.final)
        )
    ):
        raise TypeError("relation topology uses an unsupported representation")
    if (
        not isinstance(algebra, Semiring)
        or KERNEL_ALGEBRAS.get(algebra.subject.name) is not algebra
    ):
        raise TypeError("relation requires a shipped scalar semiring")
    return cls(
        tapes=tuple(
            (tape.alphabet.name, tape.alphabet.cardinality)
            for tape in topology.tapes
        ),
        input_tapes=topology.input_tapes,
        n_states=topology.n_states,
        arcs=tuple(
            (arc.source, arc.target, arc.labels, arc.weight)
            for arc in topology.arcs
        ),
        initial=tuple((mark.state, mark.weight) for mark in topology.initial),
        final=tuple((mark.state, mark.weight) for mark in topology.final),
        weight_names=topology.weight_names,
        weight_parameters=weight_parameters,
        algebra=algebra.subject,
    )

bind

Bind original scalar leaves by stable identity and return a live relation.

Values must be dense scalar leaf tensors in the algebra's carrier, with a common dtype and device. Trainable values must be original torch.nn.Parameter objects. Each distinct identity binds one object, and shared slots must use the same identity. The mapping may also provide identities for other relations. A Markov slot may explicitly use one minus an original unit probability. Its weight is recomputed from that leaf on every read.

PARAMETER DESCRIPTION
parameters

Original leaves and explicit complements by stable identity.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
RationalRelation

The sparse relation with live access to its bound weights.

RAISES DESCRIPTION
TypeError

If the mapping or its tensors do not meet the binding contract.

ValueError

If a required identity is missing, two different identities bind one object, or tensors disagree on dtype or device.

Source code in src/quivers/qiec/relations.py
def bind(self, parameters: RelationWeightBindings) -> RationalRelation:
    """Bind original scalar leaves by stable identity and return a live relation.

    Values must be dense scalar leaf tensors in the algebra's
    carrier, with a common dtype and device. Trainable values must
    be original torch.nn.Parameter objects. Each distinct identity
    binds one object, and shared slots must use the same identity.
    The mapping may also provide identities for other relations.
    A Markov slot may explicitly use one minus an original unit
    probability. Its weight is recomputed from that leaf on every read.

    Parameters
    ----------
    parameters : RelationWeightBindings
        Original leaves and explicit complements by stable identity.

    Returns
    -------
    RationalRelation
        The sparse relation with live access to its bound weights.

    Raises
    ------
    TypeError
        If the mapping or its tensors do not meet the binding contract.
    ValueError
        If a required identity is missing, two different identities bind
        one object, or tensors disagree on dtype or device.
    """
    values, complements = _weight_bindings(
        self.weight_parameters, parameters, description="relation"
    )
    algebra = self._algebra
    assert algebra is not None  # Checked when constructing the specification.
    if complements and algebra is not MARKOV:
        raise ValueError("relation weight complements require the Markov algebra")
    weights = _RelationWeights(self.weight_parameters, values, complements)
    with torch.no_grad():
        algebra.validate(weights())
    return RationalRelation(self.topology, weights, algebra=algebra)

A RelationWeightComplement binds a Markov weight slot to one minus an original probability owner. The owner is a floating-point scalar leaf in the same binding mapping. A composed or derived relation computes the complement from that owner each time it evaluates its weights, so both uses contribute to the original gradient. Decoding the relation restores the weight identities. The complement record can also be serialized with its original owner identity. A new process supplies the leaf tensors when attaching the checked request.

RelationWeightComplement didactic-model

RelationWeightComplement(*, owner: ParameterId = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Use one minus an original probability in a Markov weight slot.

PARAMETER DESCRIPTION
owner

The original scalar leaf in the same binding mapping.

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

RelationWeightBindings

RelationWeightBindings = Mapping[ParameterId, Tensor | RelationWeightComplement]

Process-local bindings of sparse relation weight identities.

Fixed-word relation requests

A FixedRelationRequest pairs a sparse relation specification with observed words in tape order, a scoring operation, and explicit query limits. pair_weight returns the scalar weight of all accepting paths at those words. conditional_log_prob uses the declared input-tape split and returns the log probability of the output under the closure-checked conditional normalizer. path_entropy returns the conditional entropy of the accepting paths in nats as a Real, under the same finite closure contract. Existing pair and conditional requests keep the same wire fields.

A FixedRelationRuntimeProvider checks the declared foreign Compute[Unit, A] handler before attaching to a reference-machine invocation. Its scalar result type follows the request. The provider binds the stable weight identities to the original live tensors and preserves derivatives through the score. The wire record carries the structural request. A run supplies the provider and parameter objects as host attachments.

The Stan, BUGS, and JAGS projections report the checked foreign handler as an obstacle. Hosted targets that preserve the handler declaration require an implementation in the target runtime.

A FixedRelationCostRequest uses a separate wire record for an expected additive cost. Each supplied cost vector follows the original occurrence order of the corresponding boundary table or arc list. An omitted group contributes zero. The provider returns a signed Real and preserves derivatives to the original relation weights. Costs are fixed data in the serialized request.

Checked best-path weights

A FixedRelationRequest with operation best_path_weight selects the highest-weight positive alignment for the observed word on each tape. The exact ranking compares the rational values represented by the input tensors. The returned scalar uses the original Markov or LogProb carrier. A tie follows the fixed topology order and carries the derivative of that selected path's original occurrences.

An empty positive support returns the semiring zero. This objective requires an acyclic productive graph. In the QIEC reference machine a foreign linear Compute[Unit, Real] or Compute[Unit, LogWeight] handler can bind the request. Native score targets report that handler as an unsupported capability.

Checked traversal counts

A FixedRelationArcCountsRequest returns one real expected traversal count for each requested original arc ID, in the requested order. An ID may occur repeatedly in the request. Distinct parallel arcs keep distinct counts, including arcs with the same weight owner. Visits at multiple observed offsets or repeated visits within a productive cycle all contribute to the same original arc's expectation. A requested arc outside the observation has count zero.

The result is a checked Real tensor whose single extent equals the length of the request's ID tuple. The linear Compute provider reads the current weights on every invocation. Cyclic observations require the existing finite closure certificate and an explicit component bound. The conditional count requires a positive finite observed path sum.

FixedRelationArcCountsRequest didactic-model

FixedRelationArcCountsRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), arc_ids: tuple[int, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, max_closure_size: int | None = None)

Bases: QiecModel

Return conditional traversal counts of selected original occurrences.

Each tensor position names one original arc occurrence. Repeated request IDs repeat the corresponding expectation. Parallel arcs that share a parameter remain separate occurrences. Traversals of one original occurrence at several observed offsets, or repeatedly along a walk, all contribute to that occurrence's expectation.

PARAMETER DESCRIPTION
relation

The typed original topology and stable scalar weight identities.

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

words

One observed word per tape in topology order.

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

arc_ids

The ordered original arc IDs whose counts the result exposes.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_states

The reached-state limit for the observation.

TYPE: int

max_work

The examined-arc limit for the observation.

TYPE: int

max_closure_size

The permitted productive closure component size.

TYPE: int or None DEFAULT: None

operation property

operation: Literal['expected_arc_counts']

Return the operation recognized by the reference machine.

RETURNS DESCRIPTION
str

The checked traversal-count objective.

result_type property

result_type: TypeExpr

Return the fixed-length real tensor type for the requested positions.

RETURNS DESCRIPTION
TypeExpr

One Real count per requested occurrence ID.

Checked alignment-marginal output ranking

FixedRelationMarginalMapRequest maximizes the total alignment weight across an explicitly ordered set of output candidates. It holds all input tapes fixed. The choose method returns the selected words, their exact rational mass, and the differentiable log pair weight. The reference provider exposes that log weight through a linear Compute[Unit, LogWeight] attachment.

Candidates require acyclic productive Markov observations and share the declared state and arc limits. The first exact maximum wins a tie. The derivative holds that output fixed. If every candidate has zero mass, the scalar score is negative infinity. Native targets identify the foreign handler that would require this capability.

FixedRelationMarginalMapRequest didactic-model

FixedRelationMarginalMapRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), inputs: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), candidates: tuple[Words, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int)

Bases: QiecModel

A checked request for the greatest alignment sum on declared outputs.

The original Markov coefficients define exact nonnegative rational path sums on acyclic productive observations. The first maximum in the candidate order wins a tie. Gradients through the selected log pair weight keep that selection fixed.

PARAMETER DESCRIPTION
relation

The typed original Markov topology and weight identities.

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

inputs

One fixed word per input tape.

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

candidates

Output words in candidate order, one word per output tape.

TYPE: tuple of Words DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_states

Cumulative reached state budget over all candidate lattices.

TYPE: int

max_work

Cumulative examined arc budget over all candidate lattices.

TYPE: int

operation property

operation: Literal['marginal_map_log_weight']

Return the operation recognized by the scalar score provider.

RETURNS DESCRIPTION
str

The bounded alignment-marginal MAP objective.

result_type property

result_type: TypeExpr

Return the QIEC result type of the selected log pair weight.

RETURNS DESCRIPTION
TypeExpr

The canonical LogWeight carrier.

choose

choose(parameters: RelationWeightBindings) -> MarginalOutputChoice | None

Return the selected output words and differentiable log pair weight.

PARAMETER DESCRIPTION
parameters

Live scalar weights owned by their original parameters.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
MarginalOutputChoice or None

The positive candidate with greatest alignment sum, if any.

Source code in src/quivers/qiec/relation_marginal_map.py
def choose(self, parameters: RelationWeightBindings) -> MarginalOutputChoice | None:
    """Return the selected output words and differentiable log pair weight.

    Parameters
    ----------
    parameters : RelationWeightBindings
        Live scalar weights owned by their original parameters.

    Returns
    -------
    MarginalOutputChoice or None
        The positive candidate with greatest alignment sum, if any.
    """
    return self._choose(self.relation.bind(parameters))

Checked static minimization

A FixedMinimizedRelationRequest wraps a pair_weight observation of an authored deterministic one-tape Markov acceptor. It uses the score's existing checked identity for the original named topology. The provider requires that exact authored identity and reads the original nontrainable weight tensors to produce a detached quotient. It checks the quotient's representability in the input dtype and applies separate minimization and observation limits. The serialized request stores the original topology and limits. The caller supplies the weights for each new binding. An ordinary FixedRelationRequest continues to score the same declaration with its live weights.

FixedRelationRequest didactic-model

FixedRelationRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), operation: Literal['pair_weight', 'conditional_log_prob', 'path_entropy', 'best_path_weight'], words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, max_closure_size: int | None = None)

Bases: QiecModel

A fixed observation and exact-work contract over a sparse topology.

The words are in tape order. For conditional_log_prob, the topology's input split separates conditioning words from scored words. The path_entropy operation returns the conditional entropy of the accepting paths in nats. For best_path_weight, the highest-weight positive path supplies its original scalar weight. This objective requires an acyclic productive graph. The wire contains the request and stable relation specification. The provider binds its live scalar parameters.

PARAMETER DESCRIPTION
relation

The typed sparse topology and original weight identities.

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

operation

The fixed-pair weight, conditional log probability, path entropy, or best path weight objective.

TYPE: str

words

One observed word per tape, in the topology's order.

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

max_states

The budget for fixed-word state exploration.

TYPE: int

max_work

The budget for fixed-word arc exploration.

TYPE: int

max_closure_size

The largest permitted productive closure component, or None to require an acyclic query.

TYPE: int or None DEFAULT: None

result_type property

result_type: TypeExpr

The checked scalar type of the request result.

RETURNS DESCRIPTION
TypeExpr

LogWeight for a conditional or log-domain path or pair score, or Real for entropy and Markov path or pair scores.

FixedRelationCostRequest didactic-model

FixedRelationCostRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, max_closure_size: int | None = None, initial_costs: tuple[float, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), arc_costs: tuple[float, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), final_costs: tuple[float, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A fixed-word expectation of a signed additive path cost.

Costs follow the order of original arc and boundary occurrences. Omitted groups contribute zero. The scalar Real result is the expectation under the normalized distribution of accepting paths. Weight parameters are bound live. The cost literals are fixed data in the wire record.

PARAMETER DESCRIPTION
relation

The typed topology and original scalar weight identities.

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

words

One fixed word per tape, in topology order.

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

max_states

The fixed-word state budget.

TYPE: int

max_work

The fixed-word arc examination budget.

TYPE: int

max_closure_size

The largest permitted productive closure component.

TYPE: int or None DEFAULT: None

initial_costs

One signed real cost per original initial mark, if supplied.

TYPE: tuple of float or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

arc_costs

One signed real cost per original arc, if supplied.

TYPE: tuple of float or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

final_costs

One signed real cost per original final mark, if supplied.

TYPE: tuple of float or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

operation property

operation: Literal['expected_path_cost']

Name the checked signed scalar objective.

RETURNS DESCRIPTION
str

The expected additive path cost objective.

result_type property

result_type: TypeExpr

Name the checked scalar result carrier.

RETURNS DESCRIPTION
TypeExpr

Real, since additive costs may have either sign.

FixedMinimizedRelationRequest didactic-model

FixedMinimizedRelationRequest(*, observation: FixedRelationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_minimization_states: int, max_minimization_work: int)

Bases: QiecModel

Score one declared acceptor through an exact minimized snapshot.

The observation keeps the original authored topology and weight identities. Its fixed-word state and work limits apply to the quotient. The separate minimization limits apply to the source acceptor. Binding requires nontrainable weights and an exactly representable quotient in the dtype supplied by the caller.

PARAMETER DESCRIPTION
observation

The original static Markov acceptor and its fixed pair weight observation. The acceptor has one tape, deterministic symbols, and at most one initial state.

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

max_minimization_states

The source's productive state limit.

TYPE: int

max_minimization_work

The source input record and refinement work limit.

TYPE: int

result_type property

result_type: TypeExpr

Return the checked Real type of the unchanged pair-weight objective.

RETURNS DESCRIPTION
TypeExpr

The scalar Real result type.

plan

Snapshot the source, minimize it, and plan the declared observation.

PARAMETER DESCRIPTION
parameters

The original nontrainable scalar leaves indexed by identity.

TYPE: Mapping of ParameterId to torch.Tensor

RETURNS DESCRIPTION
tuple[FixedStringQuery, StaticMinimizationWork]

The fixed-word plan over detached quotient weights and the source minimization counters. Rebinding takes a new snapshot.

RAISES DESCRIPTION
TypeError

The source weights are unsupported or trainable.

ValueError

A binding is invalid, the acceptor is ambiguous or has epsilon arcs, a budget is exhausted, or a quotient weight is unrepresentable in the input dtype.

Source code in src/quivers/qiec/relations.py
def plan(
    self, parameters: RelationWeightBindings
) -> tuple[FixedStringQuery, StaticMinimizationWork]:
    """Snapshot the source, minimize it, and plan the declared observation.

    Parameters
    ----------
    parameters : Mapping of ParameterId to torch.Tensor
        The original nontrainable scalar leaves indexed by identity.

    Returns
    -------
    tuple[FixedStringQuery, StaticMinimizationWork]
        The fixed-word plan over detached quotient weights and the
        source minimization counters. Rebinding takes a new snapshot.

    Raises
    ------
    TypeError
        The source weights are unsupported or trainable.
    ValueError
        A binding is invalid, the acceptor is ambiguous or has
        epsilon arcs, a budget is exhausted, or a quotient weight
        is unrepresentable in the input dtype.
    """
    source = self.observation
    quotient, work = minimize_static_acceptor_with_work(
        source.relation.bind(parameters),
        max_states=self.max_minimization_states,
        max_work=self.max_minimization_work,
    )
    return quotient.query(
        source.words, max_states=source.max_states, max_work=source.max_work
    ), work

FixedRelationRuntimeProvider

Bind one declared foreign Compute handler to a sparse request.

The checked handler must have type Compute[Unit, A], where A is the result type of the request, and resume once. Weight identities resolve to the caller's original tensors.

PARAMETER DESCRIPTION
request

The checked fixed observation, objective, and resource limits.

TYPE: FixedRelationRequest or FixedRelationCostRequest or FixedComposedRelationRequest or FixedRelationMarginalMapRequest or FixedRelationArcCountsRequest or FixedTransformedRelationRequest or FixedRelationFeatureMomentRequest or FixedCyclicRelationFeatureMomentRequest or FixedComposedArcFeatureMomentRequest or FixedMinimizedRelationRequest or FixedBackoffRelationRequest or FixedRankedOTRelationRequest

parameters

The original scalar tensors supplying the request's weight identities. A minimized request snapshots nontrainable values.

TYPE: RelationWeightBindings

handler_name

The name of the foreign handler to bind in the checked module.

TYPE: str

Source code in src/quivers/qiec/relation_runtime.py
def __init__(
    self,
    request: FixedRelationRequest
    | FixedRelationCostRequest
    | FixedRelationArcCountsRequest
    | FixedComposedRelationRequest
    | FixedRelationMarginalMapRequest
    | FixedTransformedRelationRequest
    | FixedRelationFeatureMomentRequest
    | FixedCyclicRelationFeatureMomentRequest
    | FixedComposedArcFeatureMomentRequest
    | FixedBackoffRelationRequest
    | FixedRankedOTRelationRequest
    | FixedMinimizedRelationRequest,
    parameters: RelationWeightBindings,
    *,
    handler_name: str,
) -> None:
    if not isinstance(handler_name, str) or not handler_name:
        raise ValueError("a fixed relation provider requires a handler name")
    if handler_name.startswith(_BACKOFF_HANDLER_PREFIX) and not isinstance(
        request, FixedBackoffRelationRequest
    ):
        raise ValueError("a checked backoff handler requires its backoff request")
    if handler_name.startswith(_RANKED_OT_HANDLER_PREFIX) and not isinstance(
        request, FixedRankedOTRelationRequest
    ):
        raise ValueError("a checked ranked handler requires its ranked request")
    self._handler_name = handler_name
    self._result_type = request.result_type
    self._result_shape = (
        (len(request.arc_ids),)
        if isinstance(request, FixedRelationArcCountsRequest)
        else ()
    )
    self._score: Callable[[], torch.Tensor]
    self._right_action: (
        Callable[[tuple[float, ...]], PathStatisticRightAction] | None
    ) = None
    self._right_action_parameters: tuple[ParameterId, ...] = ()
    self._right_action_complement = False
    self._feature_size: int | None = None
    self._requires_authored_topology = isinstance(
        request, FixedMinimizedRelationRequest
    )
    if isinstance(request, FixedMinimizedRelationRequest):
        self._operation = request.observation.operation
        self._relation_spec = request.observation.relation
        self._score = request.plan(parameters)[0].weight
        return
    if isinstance(
        request, FixedBackoffRelationRequest | FixedRankedOTRelationRequest
    ):
        if handler_name != request.handler_name:
            raise ValueError(
                f"{type(request).__name__} requires its exact observation handler"
            )
        self._operation = "pair_weight"
        self._relation_spec = request.relation
        self._score = request.plan(parameters).weight
        return
    if isinstance(
        request,
        FixedRelationFeatureMomentRequest
        | FixedCyclicRelationFeatureMomentRequest
        | FixedComposedArcFeatureMomentRequest,
    ):
        if handler_name != request.handler_name:
            raise ValueError(
                "fixed feature moments require their exact observation handler"
            )
        self._operation = "feature_moments"
        if isinstance(request, FixedComposedArcFeatureMomentRequest):
            self._feature_size = request.feature_extent + 1
            self._relation_spec = request.request.relation
        else:
            self._feature_size = request.observation.feature_extent + 1
            self._relation_spec = request.observation.relation
        self._score = request.plan(parameters)
        return
    self._operation = request.operation
    self._relation_spec = request.relation
    if isinstance(
        request, FixedComposedRelationRequest | FixedTransformedRelationRequest
    ):
        self._score = request.plan(parameters).weight
        return
    relation = request.relation.bind(parameters)
    if isinstance(request, FixedRelationMarginalMapRequest):
        zero = relation._weights().new_full((), -torch.inf)

        def marginal_map_score() -> torch.Tensor:
            """Read the live score of the current winning output.

            Returns
            -------
            torch.Tensor
                The selected log pair weight or the LogProb zero.
            """
            choice = request._choose(relation)
            return zero if choice is None else choice.log_pair_weight

        self._score = marginal_map_score
        return
    limits = dict(
        max_states=request.max_states,
        max_work=request.max_work,
        max_closure_size=request.max_closure_size,
    )
    if isinstance(request, FixedRelationArcCountsRequest):
        query = relation.query(request.words, **limits)
        self._score = partial(_selected_arc_counts, query, request.arc_ids)
    elif isinstance(request, FixedRelationCostRequest):
        query = relation.query(request.words, **limits)
        anchor = relation._weights()
        initial, arcs, final = (
            None if group is None else anchor.new_tensor(group)
            for group in (
                request.initial_costs,
                request.arc_costs,
                request.final_costs,
            )
        )
        self._score = partial(_expected_path_cost, query, initial, arcs, final)
        self._right_action = partial(
            query.path_statistic_right_action,
            initial_costs=initial,
            arc_costs=arcs,
            final_costs=final,
        )
    elif request.operation == "pair_weight":
        self._score = relation.query(request.words, **limits).weight
    elif request.operation == "best_path_weight":
        self._score = relation.query(request.words, **limits).best_path_weight
    elif request.operation == "path_entropy":
        query = relation.query(request.words, **limits)
        self._score = lambda: query.path_statistics().entropy
        self._right_action = query.path_statistic_right_action
    else:
        split = relation.topology.input_tapes
        conditional = relation.conditional(
            request.words[:split],
            max_states=request.max_states,
            max_work=request.max_work,
            max_closure_size=request.max_closure_size,
        )
        self._score = conditional._fixed_log_prob(request.words[split:])
    if self._right_action is not None:
        self._right_action_parameters = request.relation.weight_parameters
        self._right_action_complement = any(
            isinstance(parameters[identity], RelationWeightComplement)
            for identity in set(self._right_action_parameters)
        )

for_score classmethod

Bind a fixed request to a source-declared relation score.

PARAMETER DESCRIPTION
name

The name used in the source declaration.

TYPE: str

request

The serialized and validated fixed relation request.

TYPE: FixedRelationRequest | FixedRelationCostRequest | FixedRelationArcCountsRequest | FixedComposedRelationRequest | FixedRelationMarginalMapRequest | FixedTransformedRelationRequest | FixedMinimizedRelationRequest

parameters

The original scalar parameter objects indexed by identity. A minimized request takes a nontrainable snapshot at binding.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
FixedRelationRuntimeProvider

A provider for the generated checked handler.

RAISES DESCRIPTION
ValueError

If the source name is empty or the binding is invalid.

Source code in src/quivers/qiec/relation_runtime.py
@classmethod
def for_score(
    cls,
    name: str,
    request: FixedRelationRequest
    | FixedRelationCostRequest
    | FixedRelationArcCountsRequest
    | FixedComposedRelationRequest
    | FixedRelationMarginalMapRequest
    | FixedTransformedRelationRequest
    | FixedMinimizedRelationRequest,
    parameters: RelationWeightBindings,
) -> FixedRelationRuntimeProvider:
    """Bind a fixed request to a source-declared relation score.

    Parameters
    ----------
    name
        The name used in the source declaration.
    request
        The serialized and validated fixed relation request.
    parameters
        The original scalar parameter objects indexed by identity.
        A minimized request takes a nontrainable snapshot at binding.

    Returns
    -------
    FixedRelationRuntimeProvider
        A provider for the generated checked handler.

    Raises
    ------
    ValueError
        If the source name is empty or the binding is invalid.
    """
    if not isinstance(name, str) or not name:
        raise ValueError("a source-declared relation score requires a name")
    return cls(request, parameters, handler_name=_relation_score_handler_name(name))

path_statistic_right_action

path_statistic_right_action(direction: Mapping[ParameterId, float]) -> PathStatisticRightAction

Check an affine right action of this provider's path statistic.

A direction is indexed by the original parameter identities and copied into every tied slot. Omitted identities are held fixed. The enabled observations are fixed-word path entropy and scalar expected path cost on an acyclic float64 Markov graph.

PARAMETER DESCRIPTION
direction

One finite coefficient per varied original parameter.

TYPE: Mapping[ParameterId, float]

RETURNS DESCRIPTION
PathStatisticRightAction

The same named objective and its explicit finite right action, or its defined entropy value and reason for no finite action.

RAISES DESCRIPTION
ValueError

If the requested statistics route, direction identity or affine complement bindings are outside the admitted scope.

TypeError

If a coordinate or the numeric carrier is unsupported.

ProductiveEpsilonCycleError

If the productive observation is cyclic.

FloatingPointError

If the finite action is outside working precision.

Source code in src/quivers/qiec/relation_runtime.py
def path_statistic_right_action(
    self, direction: Mapping[ParameterId, float]
) -> PathStatisticRightAction:
    """Check an affine right action of this provider's path statistic.

    A direction is indexed by the original parameter identities
    and copied into every tied slot. Omitted identities are held
    fixed. The enabled observations are fixed-word path entropy
    and scalar expected path cost on an acyclic float64 Markov graph.

    Parameters
    ----------
    direction
        One finite coefficient per varied original parameter.

    Returns
    -------
    PathStatisticRightAction
        The same named objective and its explicit finite right action,
        or its defined entropy value and reason for no finite action.

    Raises
    ------
    ValueError
        If the requested statistics route, direction identity or
        affine complement bindings are outside the admitted scope.
    TypeError
        If a coordinate or the numeric carrier is unsupported.
    ProductiveEpsilonCycleError
        If the productive observation is cyclic.
    FloatingPointError
        If the finite action is outside working precision.
    """
    if self._right_action is None:
        raise ValueError(
            "a path right action requires a fixed entropy or cost request"
        )
    if self._right_action_complement:
        raise ValueError("path right action does not accept complement coordinates")
    if not isinstance(direction, Mapping) or not set(direction).issubset(
        self._right_action_parameters
    ):
        raise ValueError("path right action needs original parameter identities")
    return self._right_action(
        tuple(
            direction.get(identity, 0.0)
            for identity in self._right_action_parameters
        )
    )

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach the provider to its exact checked foreign handler.

PARAMETER DESCRIPTION
module

The checked module declaring the handler.

TYPE: QiecModule

attachments

The runtime bindings for the invocation.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

The module has no unique handler with the requested name.

TypeError

The declaration does not have the required linear compute contract.

Source code in src/quivers/qiec/relation_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach the provider to its exact checked foreign handler.

    Parameters
    ----------
    module : QiecModule
        The checked module declaring the handler.
    attachments : RuntimeAttachments
        The runtime bindings for the invocation.

    Raises
    ------
    ValueError
        The module has no unique handler with the requested name.
    TypeError
        The declaration does not have the required linear compute contract.
    """
    result = self._result_type
    definition = _fixed_compute_definition(module, self._handler_name, result)
    score_name = definition.name.removeprefix(_RELATION_SCORE_HANDLER_PREFIX)
    if self._requires_authored_topology and score_name == definition.name:
        raise TypeError("a minimized relation score requires its authored topology")
    if score_name != definition.name:
        expected_id = _relation_score_handler_id(
            module.module, score_name, self._operation
        )
        if self._requires_authored_topology or definition.id != expected_id:
            bound_id = _relation_score_handler_id(
                module.module, score_name, self._operation, self._relation_spec
            )
            if definition.id != bound_id:
                raise TypeError(
                    f"relation score {score_name!r} has a different declared operation "
                    f"or authored topology from the supplied {self._operation!r} request"
                )
    validation = self.validator_for(result)
    assert validation is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validation,
        answer_type=result,
        key=self._handler_name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Validate the request's differentiable result.

PARAMETER DESCRIPTION
type_

The requested checked result type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The predicate for this request's result type, or None for other types.

Source code in src/quivers/qiec/relation_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Validate the request's differentiable result.

    Parameters
    ----------
    type_ : TypeExpr
        The requested checked result type.

    Returns
    -------
    RuntimeValidator or None
        The predicate for this request's result type, or `None` for other types.
    """
    if type_ != self._result_type:
        return None
    core = CoreRuntimeProvider().validator_for(type_)
    if self._feature_size is not None:
        assert core is not None
        return lambda value: (
            isinstance(value, torch.Tensor)
            and core(value)
            and bool(LOG_PROB.contains(value).all())
        )
    if self._result_shape:
        return core
    algebra = LOG_PROB if type_ == LOG_WEIGHT else None

    def validate(value: object) -> bool:
        """Check a value against the declared scalar carrier.

        Parameters
        ----------
        value : object
            The runtime value to check.

        Returns
        -------
        bool
            Whether the value inhabits the requested type.
        """
        if core is not None and core(value):
            return True
        if not (
            isinstance(value, torch.Tensor)
            and value.shape == ()
            and value.is_floating_point()
        ):
            return False
        return bool(
            torch.isfinite(value) if algebra is None else algebra.contains(value)
        )

    return validate

Compact backoff relation requests

A FixedBackoffRelationRequest scores a word against an authored deterministic one-tape Markov or LogProb topology with explicit failure links. The checked foreign handler name identifies the original topology, ordered failure links and their weight identities, and the observation. State and work limits are invocation settings. An ordinary pair-weight request cannot bind this handler.

For a missing symbol, a chain of failures leaves the symbol unconsumed until the first ordinary match. Its weight is the ordered product of the failure weights followed by the matching ordinary weight. This is the same transition a full deterministic expansion would supply for that state and symbol. Each ordinary transition is present structurally, so a zero ordinary coefficient takes precedence over any fallback. At the end of the word, only the current state's final mark can contribute. The compact plan follows this sequence for the observed word and keeps the original tensors, including shared and failure-only identities.

In QVR, a named computation can install a foreign Compute[Unit, A] handler using the request's handler_name, with apply resumes 1. Here A is Real or LogWeight according to the request. A native run supplies FixedRelationRuntimeProvider and the original weight tensors. The budget counts visited state configurations and ordinary symbol probes after validation of the sparse graph. The exhaustive alphabet expansion is only an equivalence description.

FixedBackoffRelationRequest didactic-model

FixedBackoffRelationRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), failures: tuple[tuple[int, int, ParameterId], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), word: tuple[int, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int)

Bases: QiecModel

Check one word against a deterministic acceptor with failure arcs.

Ordinary arcs have structural priority, including when their current weights are zero. Each missing symbol follows an acyclic failure chain until it finds an ordinary match or runs out of failures. The failure leaves the symbol unconsumed and never supplies a final mark.

PARAMETER DESCRIPTION
relation

The original deterministic, epsilon-free one-tape topology, with Markov or LogProb weights and at most one initial mark.

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

failures

Ordered failure arc sources, targets and original scalar weight identities. Identities may be shared with the ordinary topology or supplied only for failure arcs.

TYPE: tuple of triples of int, int, ParameterId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

word

The word on the original nominal alphabet.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_states

The limit on visited configurations, including failures.

TYPE: int

max_work

The limit on ordinary symbol probes, including misses. Topology validation runs separately in the size of the supplied graph.

TYPE: int

handler_name property

handler_name: str

Return the checked foreign name for the exact backoff observation.

RETURNS DESCRIPTION
str

A portable digest of the original specification, ordered failure arcs and fixed word. Limits are invocation settings.

result_type property

result_type: TypeExpr

Return the scalar type of the ordinary algebra's pair weight.

RETURNS DESCRIPTION
TypeExpr

LogWeight for LogProb and Real for Markov.

plan

Plan the selected compact path with the original live tensors.

PARAMETER DESCRIPTION
parameters

All the original scalar owners, including failure-only owners.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
FixedStringQuery

The reusable path plan for the declared word.

RAISES DESCRIPTION
TypeError

A scalar binding fails its carrier or original leaf contract.

ValueError

A scalar binding or a construction limit fails.

Source code in src/quivers/qiec/relation_backoff.py
def plan(self, parameters: RelationWeightBindings) -> FixedStringQuery:
    """Plan the selected compact path with the original live tensors.

    Parameters
    ----------
    parameters : RelationWeightBindings
        All the original scalar owners, including failure-only owners.

    Returns
    -------
    FixedStringQuery
        The reusable path plan for the declared word.

    Raises
    ------
    TypeError
        A scalar binding fails its carrier or original leaf contract.
    ValueError
        A scalar binding or a construction limit fails.
    """
    relation, failures = self._binding
    return backoff_query(
        relation.bind(parameters),
        failures,
        self.word,
        max_states=self.max_states,
        max_work=self.max_work,
    )

Capped ranked relation requests

A FixedRankedOTRelationRequest supplies one ordered violation profile per original generator arc and one finite cap per rank. For each input, the compiler retains all original accepting paths whose capped profiles are lexicographically minimal. The pair score then sums the weights of the retained paths at the observed output. Tied parallel paths remain distinct, and the weights may change without altering their ranked preferences. The result is an unnormalized pair mass. A conditional output distribution would additionally require its own output normalizer and positive finite mass.

A nonnegative cap is a part of the model. For instance, a cap of one makes a rank binary, and a cap of zero ignores it. The competitor tracker charges its work separately from the subsequent fixed-word query. Its intermediate subset count can grow exponentially. Exhausted limits raise without returning a truncated ranked result. This request uses the finite capped ranking of the sparse calculus. Eisner (2002).

A named QVR computation installs the request's foreign Compute[Unit, A] handler as with compact backoff. Its checked handler identity includes the original typed generator, original occurrence profiles, caps, and the observed pair. The reference provider validates that identity and binds the original weight tensors. The Stan, BUGS and JAGS projections name the foreign handler when refusing this provider.

FixedRankedOTRelationRequest didactic-model

FixedRankedOTRelationRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), violations: tuple[tuple[int, ...], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), caps: tuple[int, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_rank_states: int, max_rank_work: int, max_states: int, max_work: int, max_closure_size: int | None = None)

Bases: QiecModel

Score an observed pair among the paths that minimize capped ranks.

The minimum capped lexicographic profile is computed separately for every input over the structural candidate paths. The scalar result sums all winning paths at the observed pair in the declared algebra. Ranking takes place before reading the numerical weights, and the result is an unnormalized pair weight.

PARAMETER DESCRIPTION
relation

The original one-input, one-output Markov or LogProb transducer.

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

words

The input and output observations in nominal tape order.

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

violations

One nonnegative profile per original arc occurrence. Initial and final marks have zero violations.

TYPE: tuple of tuples of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

caps

A nonnegative finite saturation limit per rank. A zero cap ignores the corresponding coordinate.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_rank_states

Maximum reached states during compilation for all inputs.

TYPE: int

max_rank_work

Maximum combined weighted product and competitor construction work.

TYPE: int

max_states

Maximum visited states during the fixed-word query.

TYPE: int

max_work

Maximum examined arcs during the fixed-word query.

TYPE: int

max_closure_size

Largest supported productive closure in the fixed-word query.

TYPE: int or None DEFAULT: None

handler_name property

handler_name: str

Return the foreign name for the exact ranked observation.

RETURNS DESCRIPTION
str

A digest of the ordered original topology, words, violations, and caps. Limits are independent invocation settings.

result_type property

result_type: TypeExpr

Return the scalar type of the winning-path pair weight.

RETURNS DESCRIPTION
TypeExpr

LogWeight for LogProb and Real for Markov.

plan

Compile the capped filter and read live weights in the pair plan.

PARAMETER DESCRIPTION
parameters

The original scalar tensors by stable identity.

TYPE: Mapping of ParameterId to torch.Tensor

RETURNS DESCRIPTION
FixedStringQuery

The reusable observation plan for the winning paths.

RAISES DESCRIPTION
TypeError

A parameter fails the original scalar binding contract.

ValueError

A parameter, compilation or fixed-word limit fails.

Source code in src/quivers/qiec/relation_ranked.py
def plan(self, parameters: RelationWeightBindings) -> FixedStringQuery:
    """Compile the capped filter and read live weights in the pair plan.

    Parameters
    ----------
    parameters : Mapping of ParameterId to torch.Tensor
        The original scalar tensors by stable identity.

    Returns
    -------
    FixedStringQuery
        The reusable observation plan for the winning paths.

    Raises
    ------
    TypeError
        A parameter fails the original scalar binding contract.
    ValueError
        A parameter, compilation or fixed-word limit fails.
    """
    winner = compile_ranked_ot(
        self.relation.bind(parameters),
        self.violations,
        self.caps,
        max_states=self.max_rank_states,
        max_work=self.max_rank_work,
    )
    return winner.query(
        self.words,
        max_states=self.max_states,
        max_work=self.max_work,
        max_closure_size=self.max_closure_size,
    )

Packed contextual edit requests

A FixedContextualEditRequest records paired observations in batch order, their nominal alphabets, the consecutive insertion bound, construction limits, and a stable AttachmentId for the channel. Its result is a LogWeight tensor with one entry per observed pair. Each entry is the conditional log probability of the observed output and sums over the compatible alignments. The local normalization still includes every legal edit at each input position and insertion count.

A native ContextualEditRuntimeProvider binds the original channel and builds its packed plan once. The scorer reads the complete fixed input batch on every execution, so later optimizer steps reach the same original parameters. The request can travel on the wire, and the caller supplies the original network as a runtime attachment. A QVR computation can install the request's named foreign Compute handler, as shown in the contextual edit example. The Stan, BUGS and JAGS projections report that foreign handler when refusing the computation.

To use raw neural path scores, wrap the same observation in a FixedGlobalContextualEditRequest. Its handler identity includes the global objective as well as the original channel, alphabets and ordered observation. The result has the same batch shape. The checked provider evaluates one live binary64 scorer call and uses the all-output suffix normalizer, with the suffix chart included in the request's limits. See the global edit plan for the arithmetic and support contract.

FixedContextualEditRequest didactic-model

FixedContextualEditRequest(*, channel: AttachmentId, input_alphabet: tuple[str, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), output_alphabet: tuple[str, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), inputs: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), outputs: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), max_insertions: int, max_states: int, max_work: int)

Bases: QiecModel

Request one packed batch of alignment-marginal conditional scores.

The request carries nominal alphabets, paired fixed observations, the insertion bound and a stable channel attachment. The caller supplies the existing channel with its original live scorer. Each result entry is the log probability of the corresponding output under the channel conditioned on that entry's complete input.

PARAMETER DESCRIPTION
channel

The stable runtime attachment for the original model.

TYPE: AttachmentId

input_alphabet

The nominal alphabet names and sizes in their respective roles.

TYPE: tuple of str and int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

output_alphabet

The nominal alphabet names and sizes in their respective roles.

TYPE: tuple of str and int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

inputs

Nonempty batches containing one input and output per position.

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

outputs

Nonempty batches containing one input and output per position.

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

max_insertions

The channel's maximum number of consecutive insertions.

TYPE: int

max_states

The total permitted observation configurations across the batch.

TYPE: int

max_work

The total permitted padded action cells and compatible edit arcs.

TYPE: int

handler_name property

handler_name: str

Return the checked foreign name for this channel and batch.

RETURNS DESCRIPTION
str

A digest binding the channel, nominal alphabets, ordered observations and insertion bound. Limits are invocation settings.

result_type property

result_type: TypeExpr

Return the precise batch type of the conditional log scores.

RETURNS DESCRIPTION
TypeExpr

LogWeight tensor with exactly one entry per pair.

plan

Bind one original channel and construct one reusable packed plan.

PARAMETER DESCRIPTION
channels

Live channels supplied by the reference runtime caller.

TYPE: Mapping of AttachmentId to ContextualEditChannel

RETURNS DESCRIPTION
ContextualEditPlan

The bounded plan sharing the supplied channel's live scorer.

RAISES DESCRIPTION
TypeError

The mapped runtime value is outside the contextual channel type.

ValueError

The requested channel is missing, a nominal tape or insertion bound differs, or a construction budget is exhausted.

Source code in src/quivers/qiec/contextual_edit_runtime.py
def plan(
    self, channels: Mapping[AttachmentId, ContextualEditChannel]
) -> ContextualEditPlan:
    """Bind one original channel and construct one reusable packed plan.

    Parameters
    ----------
    channels : Mapping of AttachmentId to ContextualEditChannel
        Live channels supplied by the reference runtime caller.

    Returns
    -------
    ContextualEditPlan
        The bounded plan sharing the supplied channel's live scorer.

    Raises
    ------
    TypeError
        The mapped runtime value is outside the contextual channel type.
    ValueError
        The requested channel is missing, a nominal tape or insertion
        bound differs, or a construction budget is exhausted.
    """
    return self._plan(channels, normalization="local")

FixedGlobalContextualEditRequest didactic-model

FixedGlobalContextualEditRequest(*, observation: FixedContextualEditRequest = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Score fixed pairs under a globally normalized neural edit model.

PARAMETER DESCRIPTION
observation

Ordered inputs and outputs, nominal alphabets, and the original channel attachment. The state and work limits include both the all-output suffix and fixed-output observation charts.

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

handler_name property

handler_name: str

Return a checked identity for the global objective and observations.

RETURNS DESCRIPTION
str

The global handler name, binding the same owner, nominal tape identities, ordered words, and insertion bound.

result_type property

result_type: TypeExpr

Return the exact ordered batch type of the scores.

RETURNS DESCRIPTION
TypeExpr

One log probability per fixed pair.

plan

Bind the original live scorer for globally normalized evaluation.

PARAMETER DESCRIPTION
channels

Original channels from the runtime caller.

TYPE: Mapping of AttachmentId to ContextualEditChannel

RETURNS DESCRIPTION
ContextualEditPlan

A bounded packed plan retaining the live scorer.

RAISES DESCRIPTION
TypeError

A channel has the wrong type.

ValueError

The owner, nominal tape, insertion bound, or budget does not meet the request.

Source code in src/quivers/qiec/contextual_edit_runtime.py
def plan(
    self, channels: Mapping[AttachmentId, ContextualEditChannel]
) -> ContextualEditPlan:
    """Bind the original live scorer for globally normalized evaluation.

    Parameters
    ----------
    channels : Mapping of AttachmentId to ContextualEditChannel
        Original channels from the runtime caller.

    Returns
    -------
    ContextualEditPlan
        A bounded packed plan retaining the live scorer.

    Raises
    ------
    TypeError
        A channel has the wrong type.
    ValueError
        The owner, nominal tape, insertion bound, or budget does not
        meet the request.
    """
    return self.observation._plan(channels, normalization="global")

ContextualEditRuntimeProvider

ContextualEditRuntimeProvider(request: FixedContextualEditRequest | FixedGlobalContextualEditRequest, channels: Mapping[AttachmentId, ContextualEditChannel])

Bind an authored packed score to the original contextual edit channel.

PARAMETER DESCRIPTION
request

The typed batch and limits carried by checked QIEC data.

TYPE: FixedContextualEditRequest or FixedGlobalContextualEditRequest

channels

Original process-local channels indexed by attachment identity.

TYPE: Mapping of AttachmentId to ContextualEditChannel

Source code in src/quivers/qiec/contextual_edit_runtime.py
def __init__(
    self,
    request: FixedContextualEditRequest | FixedGlobalContextualEditRequest,
    channels: Mapping[AttachmentId, ContextualEditChannel],
) -> None:
    self._handler_name = request.handler_name
    self._result_type = request.result_type
    self._plan = request.plan(channels)

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach to the exact foreign handler declared by the checked program.

PARAMETER DESCRIPTION
module

The checked module with the original channel and batch identity.

TYPE: QiecModule

attachments

The reference machine's process-local bindings.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

The module lacks the required checked handler name.

TypeError

The declaration lacks the exact batch and Compute contract.

Source code in src/quivers/qiec/contextual_edit_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach to the exact foreign handler declared by the checked program.

    Parameters
    ----------
    module : QiecModule
        The checked module with the original channel and batch identity.
    attachments : RuntimeAttachments
        The reference machine's process-local bindings.

    Raises
    ------
    ValueError
        The module lacks the required checked handler name.
    TypeError
        The declaration lacks the exact batch and Compute contract.
    """
    result = self._result_type
    definition = _fixed_compute_definition(module, self._handler_name, result)
    validation = self.validator_for(result)
    assert validation is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validation,
        answer_type=result,
        key=self._handler_name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Validate the exact ordered batch and its log carrier.

PARAMETER DESCRIPTION
type_

The checked type requested by the runtime.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The validator for this batch type, including log zero, or no validation contribution for other types.

Source code in src/quivers/qiec/contextual_edit_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Validate the exact ordered batch and its log carrier.

    Parameters
    ----------
    type_ : TypeExpr
        The checked type requested by the runtime.

    Returns
    -------
    RuntimeValidator or None
        The validator for this batch type, including log zero, or no
        validation contribution for other types.
    """
    if type_ != self._result_type:
        return None
    core = CoreRuntimeProvider().validator_for(type_)
    assert core is not None
    return lambda value: (
        isinstance(value, torch.Tensor)
        and core(value)
        and bool(LOG_PROB.contains(value).all())
    )

Sparse relation composition requests

A ComposedRelationSpec records the two original operands of a binary composition. Each has one input and one output tape. The contract checks the nominal shared tape and the common scalar algebra. The operands' parameter identities are resolved from one runtime map, so tied weights retain their original gradient owner.

A FixedComposedRelationRequest scores the pair of outer words. With lazy execution it builds only the reachable fixed-word product. With materialized execution it builds a reusable sparse product and can close an explicitly permitted productive component. The three-state epsilon filter gives each compatible pair of original paths exactly one product contribution. The selected execution mode and its limits are part of the wire record.

The existing pair-weight provider serves a composed request for an unbound source score. A score bound to a specific authored primitive relation checks that declaration's topology instead.

ComposedRelationSpec didactic-model

ComposedRelationSpec(*, left: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), right: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A checked binary composition that keeps both original topologies.

Each operand has one input and one output tape. The left output and right input must have the same nominal type. Both operands have the same trusted Markov or LogProb algebra.

PARAMETER DESCRIPTION
left

The source-side operand.

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

right

The target-side operand.

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

bind

Bind the original identities and construct a sparse composition.

PARAMETER DESCRIPTION
parameters

One explicit mapping for scalar weights of both operands.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
ComposedRelation

The checked composition, with the original live parameters.

RAISES DESCRIPTION
TypeError

If an operand cannot bind the proposed tensors.

ValueError

If different identities alias one tensor or the bindings have different dtypes or devices.

Source code in src/quivers/qiec/relation_composition.py
def bind(self, parameters: RelationWeightBindings) -> ComposedRelation:
    """Bind the original identities and construct a sparse composition.

    Parameters
    ----------
    parameters : RelationWeightBindings
        One explicit mapping for scalar weights of both operands.

    Returns
    -------
    ComposedRelation
        The checked composition, with the original live parameters.

    Raises
    ------
    TypeError
        If an operand cannot bind the proposed tensors.
    ValueError
        If different identities alias one tensor or the bindings have
        different dtypes or devices.
    """
    left, right = _bind_relation_operands(
        self.left, self.right, parameters, description="composition"
    )
    return ComposedRelation(left, right)

FixedComposedRelationRequest didactic-model

FixedComposedRelationRequest(*, relation: ComposedRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, execution: Literal['lazy', 'materialized'] = 'lazy', max_closure_size: int | None = None)

Bases: QiecModel

A checked fixed outer-word composition score and explicit work limits.

The wire keeps separate operands and their original weight owners. Lazy scoring constructs a fixed-word product. Materialized scoring constructs a reusable sparse product and can use explicitly permitted productive component closure.

PARAMETER DESCRIPTION
relation

The algebra and the two typed operand topologies.

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

words

The source input word and target output word in that order.

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

execution

Select lazy fixed-word or materialized sparse product.

TYPE: str DEFAULT: 'lazy'

max_states

State limits for each product construction and word query.

TYPE: int

max_work

Work limits for each product construction and word query.

TYPE: int

max_closure_size

The productive closure bound for a materialized word query.

TYPE: int or None DEFAULT: None

operation property

operation: Literal['pair_weight']

Return the scalar objective recognized by the QIEC provider.

RETURNS DESCRIPTION
str

The pair-weight objective.

result_type property

result_type: TypeExpr

Return the checked scalar type of the composed pair weight.

RETURNS DESCRIPTION
TypeExpr

LogWeight for LogProb and Real for Markov.

plan

Compile the requested sparse plan with its original weight owners.

PARAMETER DESCRIPTION
parameters

The original scalar weights shared by the two operands.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
ComposedStringQuery or FixedStringQuery

The checked lazy or materialized fixed-word query.

Source code in src/quivers/qiec/relation_composition.py
def plan(
    self, parameters: RelationWeightBindings
) -> ComposedStringQuery | FixedStringQuery:
    """Compile the requested sparse plan with its original weight owners.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The original scalar weights shared by the two operands.

    Returns
    -------
    ComposedStringQuery or FixedStringQuery
        The checked lazy or materialized fixed-word query.
    """
    relation = self.relation.bind(parameters)
    if self.execution == "lazy":
        return relation.query(
            self.words, max_states=self.max_states, max_work=self.max_work
        )
    materialized = relation.materialize(
        max_states=self.max_states, max_work=self.max_work
    )
    return materialized.query(
        self.words,
        max_states=self.max_states,
        max_work=self.max_work,
        max_closure_size=self.max_closure_size,
    )

Checked Markov path certificates

FixedMarkovPathCertificateRequest adds exact rational absolute or relative tolerances to an existing Markov pair-weight request. The original request keeps its wire fields. The computed foreign handler name binds the nominal topology, weight owner identities, observed words, and canonical tolerances. A check against the same numerical target may use a different resource budget.

The ordinary named Compute returns status, diagnostic, availability, a detached Real score, String[Fin 4, Fin 2], relative-bound availability, and Int[Fin 3] counters. The four string rows encode the lower endpoint, upper endpoint, absolute error bound, and optional relative error bound in that order. Each row has the exact hexadecimal numerator and positive denominator. These strings preserve ratios beyond the Int range. A missing relative bound uses an empty row and a false availability flag. A verified exact zero has numerator 0x0, denominator 0x1, and true availability.

The counters give exact operations, the maximum charged bit bound, and closure cells. A resource limit, divergent or undecided closure, unsupported closure or precision, and unverified accuracy have separate unavailable statuses. Unavailable reports carry empty rows, false flags, and zero placeholders. Consumers check availability before reading the scalar or evidence.

The provider reuses the compiled sparse chart and reads one current binary64 slot snapshot per evaluation. Its returned interval concerns that evaluated vector. The checked report carries value assurance and has no derivative. Targets without this native foreign handler report that missing capability.

FixedMarkovPathCertificateRequest didactic-model

FixedMarkovPathCertificateRequest(*, observation: FixedRelationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_exact_bits: int, max_exact_work: int, max_closure_cells: int, absolute_tolerance: _Ratio | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), relative_tolerance: _Ratio | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Request an exact forward-error witness for an evaluated Markov pair score.

PARAMETER DESCRIPTION
observation

The original nominal Markov pair request and its live weight identities.

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

max_exact_bits

Exact arithmetic limits for the rational witness.

TYPE: int

max_exact_work

Exact arithmetic limits for the rational witness.

TYPE: int

max_closure_cells

Aggregate local star cell limit, including auxiliary states.

TYPE: int

absolute_tolerance

Exact numerator and positive denominator of each required tolerance. At least one tolerance is required.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

relative_tolerance

Exact numerator and positive denominator of each required tolerance. At least one tolerance is required.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

handler_name property

handler_name: str

Derive the checked nominal owner for the observation and requirements.

RETURNS DESCRIPTION
str

The foreign handler name for the exact topology, words, and tolerances.

result_type property

result_type: TypeExpr

Give the value and exact-rational evidence carrier.

RETURNS DESCRIPTION
TypeExpr

Status, reason, availability, score, four encoded rational bounds, relative-bound availability, and three work counters.

FixedMarkovPathCertificateRuntimeProvider

FixedMarkovPathCertificateRuntimeProvider(request: FixedMarkovPathCertificateRequest, parameters: RelationWeightBindings)

Return a value-only report through checked native Compute.

Available reports contain exact signed hexadecimal numerator and positive denominator strings for the interval endpoints and error bounds. A relative bound is present only when requested and verified. Unavailable reports identify the failed condition and have no bounds.

PARAMETER DESCRIPTION
request

The checked observation, tolerances, and certification limits.

TYPE: FixedMarkovPathCertificateRequest

parameters

The original live owners, snapshotted independently on each call.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/relation_path_certificate.py
def __init__(
    self,
    request: FixedMarkovPathCertificateRequest,
    parameters: RelationWeightBindings,
) -> None:
    self._request = request
    self._relation = request.observation.relation.bind(parameters)
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach to the exact ordinary authored foreign Compute handler.

PARAMETER DESCRIPTION
module

The checked module declaring the nominal certificate handler.

TYPE: QiecModule

attachments

The runtime binding table for this invocation.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

The module lacks the correct certificate handler name.

TypeError

The matching declaration has an incompatible Compute contract.

Source code in src/quivers/qiec/relation_path_certificate.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach to the exact ordinary authored foreign Compute handler.

    Parameters
    ----------
    module : QiecModule
        The checked module declaring the nominal certificate handler.
    attachments : RuntimeAttachments
        The runtime binding table for this invocation.

    Raises
    ------
    ValueError
        The module lacks the correct certificate handler name.
    TypeError
        The matching declaration has an incompatible Compute contract.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Supply the canonical validator for the exact report product.

PARAMETER DESCRIPTION
type_

The carrier requested by the reference machine.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The checked report validator when the carrier matches.

Source code in src/quivers/qiec/relation_path_certificate.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Supply the canonical validator for the exact report product.

    Parameters
    ----------
    type_ : TypeExpr
        The carrier requested by the reference machine.

    Returns
    -------
    RuntimeValidator or None
        The checked report validator when the carrier matches.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

Checked acyclic LogProb path certificates

FixedLogProbPathCertificateRequest adds an exact rational absolute tolerance in log units to an acyclic LogProb pair-weight request. The foreign handler identity binds the exact nominal relation and its original parameter owners, the observed words in tape order, and the canonical tolerance. The declared execution limits can vary while checking the same objective. A closure limit is outside this request's domain.

The native Compute returns status, diagnostic, score availability, a detached LogWeight, three exact witness rows in String[Fin 3, Fin 2], endpoint availability, and three counters in Int[Fin 3]. The witness rows give the lower and upper log endpoints and the absolute log error bound. Each row encodes the signed numerator and positive denominator as hexadecimal strings. A verified zero mass has score −∞, absent endpoints, and error (0x0, 0x1).

The counters record Decimal calls and binary64 conversions, exact rational operations, and the maximum charged integer bit bound. A resource limit, productive epsilon cycle, unsupported precision, or failure to prove the requested accuracy yields its own unavailable status. An unavailable report has false availability flags, empty witness rows, and zero placeholders.

The provider reuses the compiled topology and evaluates the score and witness from a single current binary64 weight vector. The certificate covers that vector and the reported value. Gradient assurance is outside the contract. The core arithmetic and limits

Use the ordinary checked foreign Compute[Unit, A] declaration and bind its request-specific handler to FixedLogProbPathCertificateRuntimeProvider at execution. A target that lacks the native handler reports the missing capability.

FixedLogProbPathCertificateRequest didactic-model

FixedLogProbPathCertificateRequest(*, observation: FixedRelationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), absolute_log_tolerance: tuple[int, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int)

Bases: QiecModel

Request absolute log accuracy for a checked native pair weight.

PARAMETER DESCRIPTION
observation

The acyclic LogProb pair observation and its original weight owners.

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

absolute_log_tolerance

Nonnegative numerator and positive denominator in log units.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

decimal_precision

Significant digits, symmetric adjusted exponent bound, and number of Decimal calls and binary64 conversions allowed.

TYPE: int

max_decimal_exponent

Significant digits, symmetric adjusted exponent bound, and number of Decimal calls and binary64 conversions allowed.

TYPE: int

max_decimal_work

Significant digits, symmetric adjusted exponent bound, and number of Decimal calls and binary64 conversions allowed.

TYPE: int

max_exact_bits

Integer bit and operation bounds for the rational report.

TYPE: int

max_exact_work

Integer bit and operation bounds for the rational report.

TYPE: int

handler_name property

handler_name: str

Derive the handler identity for the exact numerical objective.

RETURNS DESCRIPTION
str

The name binding the relation, ordered words, and canonical tolerance.

result_type property

result_type: TypeExpr

Give the checked score and exact-rational evidence carrier.

RETURNS DESCRIPTION
TypeExpr

Status, diagnostic, score availability, log score, three rational rows, endpoint availability, and three work counters.

FixedLogProbPathCertificateRuntimeProvider

FixedLogProbPathCertificateRuntimeProvider(request: FixedLogProbPathCertificateRequest, parameters: RelationWeightBindings)

Bases: _LogProbCertificateRuntime

Bind one checked acyclic LogProb value report to original live owners.

The provider reuses the structural observation plan. Each evaluation uses one binary64 weight snapshot to score and to verify the result. The native report is detached and supplies value-only assurance.

PARAMETER DESCRIPTION
request

The checked observation, tolerance, and numerical limits.

TYPE: FixedLogProbPathCertificateRequest

parameters

The binding to the original scalar owners.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/relation_log_path_certificate.py
def __init__(
    self,
    request: FixedLogProbPathCertificateRequest,
    parameters: RelationWeightBindings,
) -> None:
    if not isinstance(request, FixedLogProbPathCertificateRequest):
        raise TypeError("the acyclic provider requires an acyclic request")
    super().__init__(request, parameters)

Checked cyclic LogProb path certificates

FixedCyclicLogProbPathCertificateRequest requires a LogProb pair observation with a local closure order bound. It also declares an aggregate closure cell limit and the arithmetic limits for exact endpoint solves. The handler name identifies the cyclic objective, the relation and original parameter owners, the tape-ordered words, and the canonical absolute tolerance in log units. Execution limits can vary for the same handler.

FixedCyclicLogProbPathCertificateRuntimeProvider returns the same typed log score and exact witness fields as the acyclic provider. The ordinary checked native computation uses a single evaluated binary64 snapshot for its score and bounds. The value report is detached. Targets missing the native handler report that capability.

A divergent lower-endpoint star yields divergent_closure. This diagnostic concerns the local structurally productive component. An upper star that cannot be proved finite gives unverified_accuracy when its lower endpoint provides no divergence witness. The native star may separately yield undecided_closure if its working precision cannot establish a usable closure. Resource exhaustion and unsupported dtype have separate unavailable statuses. The cyclic arithmetic and limits

FixedCyclicLogProbPathCertificateRequest didactic-model

FixedCyclicLogProbPathCertificateRequest(*, observation: FixedRelationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), absolute_log_tolerance: tuple[int, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_closure_cells: int, decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int)

Bases: QiecModel

Request log accuracy with explicitly bounded productive epsilon closure.

PARAMETER DESCRIPTION
observation

The checked LogProb pair observation, original weight owners, and required local closure order limit.

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

absolute_log_tolerance

Nonnegative numerator and positive denominator in log units.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_closure_cells

The aggregate local star cell bound, including auxiliary states.

TYPE: int

decimal_precision

Significant digits, symmetric adjusted exponent bound, and number of primitive calls and exact Decimal input conversions permitted.

TYPE: int

max_decimal_exponent

Significant digits, symmetric adjusted exponent bound, and number of primitive calls and exact Decimal input conversions permitted.

TYPE: int

max_decimal_work

Significant digits, symmetric adjusted exponent bound, and number of primitive calls and exact Decimal input conversions permitted.

TYPE: int

max_exact_bits

Integer bit and operation bounds for the rational report.

TYPE: int

max_exact_work

Integer bit and operation bounds for the rational report.

TYPE: int

handler_name property

handler_name: str

Derive the identity of the exact bounded cyclic objective.

RETURNS DESCRIPTION
str

The handler binding the relation, ordered words, and tolerance.

result_type property

result_type: TypeExpr

Give the checked log score and exact-rational evidence carrier.

RETURNS DESCRIPTION
TypeExpr

Status, diagnostic, score availability, log score, three rational rows, endpoint availability, and three work counters.

FixedCyclicLogProbPathCertificateRuntimeProvider

FixedCyclicLogProbPathCertificateRuntimeProvider(request: FixedCyclicLogProbPathCertificateRequest, parameters: RelationWeightBindings)

Bases: _LogProbCertificateRuntime

Bind one checked cyclic LogProb value report to original live owners.

Each evaluation scores and verifies the same evaluated binary64 vector. A proven divergent local star has a different status from an upper enclosure that cannot establish convergence. The native report is detached and supplies value-only assurance.

PARAMETER DESCRIPTION
request

The exact checked observation, arithmetic policy, and closure limits.

TYPE: FixedCyclicLogProbPathCertificateRequest

parameters

The binding to the original scalar owners.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/relation_log_path_certificate.py
def __init__(
    self,
    request: FixedCyclicLogProbPathCertificateRequest,
    parameters: RelationWeightBindings,
) -> None:
    if not isinstance(request, FixedCyclicLogProbPathCertificateRequest):
        raise TypeError("the cyclic provider requires a bounded cyclic request")
    super().__init__(request, parameters)

Typed sparse path posteriors

A FixedRelationPathSampleRequest binds a fixed word tuple and a reproducible CPU generator to the original Markov or LogProb weights. The result is a checked Sampleable whose values contain the initial state, final state, and a fixed-size vector of original arc IDs. Trailing positions use -1 padding. Parallel arcs remain distinct even when their weights share one parameter.

The productive fixed-word graph must be acyclic. Before binding a law, a reverse topological pass verifies that every structurally accepting path fits the trace capacity, including paths whose current weights are zero. This preserves the full support after changes to the weights. Scoring validates each original trace and subtracts the observed log partition from its log weight. Draws use the existing float64 conditional suffix sampler. Multiplying the successive choice probabilities cancels the intermediate suffix weights and leaves the same normalized path probability.

Pass the law to a checked Random.sample operation or use it in log_prob and log_mass. A trace that violates the path topology, does not match the words, or has zero weight has log probability negative infinity. The law reads live parameter values and scoring differentiates on the current positive support. The reference machine can replay a trace by site name with the same checked result type.

FixedCyclicRelationPathSampleRequest adds a closure-component limit to the original typed request. A productive cyclic observation must have a certified positive, finite path normalizer. The sampler uses the same float64 suffix weights. At a configuration \(s\), a transition with weight \(w\) to \(t\) has conditional probability \(w h(t)/h(s)\), where \(h\) is the total suffix weight. The accepting choice uses the final weight divided by \(h(s)\). Along a returned walk the intermediate suffix weights cancel, giving the trace probability \(W_{\pi}/Z\) under the full posterior.

The fixed trace capacity bounds the number of arcs in one attempted draw. If the next choice would take another arc, the draw raises a resource error. Successful draws record complete walks with ordinary padding. Their log_prob and replay scores use \(\log W_{\pi}-\log Z\) on the full posterior. Gradients follow the supplied trace and the finite normalizer. The discrete draw has no pathwise derivative. log_mass on the bounded carrier and finite enumeration refuse a structurally cyclic law, whose live support can contain arbitrarily long walks. The original acyclic request keeps its full-capacity law and serialized fields.

FixedRelationPathSampleRequest didactic-model

FixedRelationPathSampleRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), trace_capacity: int, max_states: int, max_work: int)

Bases: QiecModel

A sparse posterior law whose typed values identify complete paths.

Paths are recorded as the pair of original boundary states and a vector of original arc occurrences. Its capacity is finite. Trailing positions use -1 padding. The reachable and coaccessible fixed-word graph must be acyclic, and its longest accepting path must fit the capacity, even if the path currently has zero weight.

PARAMETER DESCRIPTION
relation

The original typed Markov or LogProb topology and weight identities.

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

words

One observed word per tape in tape order.

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

trace_capacity

The fixed number of positions in the result's arc tensor.

TYPE: int

max_states

The state budget for constructing the fixed-word graph.

TYPE: int

max_work

The arc examination budget for constructing the fixed-word graph.

TYPE: int

element_type property

element_type: TypeExpr

Return the checked type of one complete path trace.

RETURNS DESCRIPTION
TypeExpr

A product of two Int states and a tensor of Int arc IDs.

result_type property

result_type: TypeExpr

Return the type of the posterior law.

RETURNS DESCRIPTION
TypeExpr

The Sampleable instance over the declared trace carrier.

bind

bind(parameters: RelationWeightBindings, *, generator: Generator) -> RelationPathLaw

Bind the law for a checked Random.sample operation.

PARAMETER DESCRIPTION
parameters

Original live scalar parameter owners.

TYPE: RelationWeightBindings

generator

The CPU generator used for posterior path draws.

TYPE: Generator

RETURNS DESCRIPTION
RelationPathLaw

A reusable Sampleable of the declared trace type.

RAISES DESCRIPTION
ValueError

The generator is unsupported, the trace capacity is too small, or the observed probability mass is invalid.

Source code in src/quivers/qiec/relation_path_law.py
def bind(
    self,
    parameters: RelationWeightBindings,
    *,
    generator: torch.Generator,
) -> RelationPathLaw:
    """Bind the law for a checked Random.sample operation.

    Parameters
    ----------
    parameters : RelationWeightBindings
        Original live scalar parameter owners.
    generator : torch.Generator
        The CPU generator used for posterior path draws.

    Returns
    -------
    RelationPathLaw
        A reusable Sampleable of the declared trace type.

    Raises
    ------
    ValueError
        The generator is unsupported, the trace capacity is too
        small, or the observed probability mass is invalid.
    """
    query = self.relation.bind(parameters).query(
        self.words, max_states=self.max_states, max_work=self.max_work
    )
    return RelationPathLaw(
        query, trace_capacity=self.trace_capacity, generator=generator
    )

FixedCyclicRelationPathSampleRequest didactic-model

FixedCyclicRelationPathSampleRequest(*, request: FixedRelationPathSampleRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_closure_size: int)

Bases: QiecModel

Admit certified cyclic sampling with bounded complete trace encoding.

The existing trace capacity also bounds the number of drawn arcs. A draw that needs another arc raises a resource error. Each returned trace records a complete original walk and receives its full posterior log probability. A bound on the execution does not truncate or renormalize the model distribution.

PARAMETER DESCRIPTION
request

The original typed observation, trace capacity and construction limits.

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

max_closure_size

Maximum local matrix order for a productive certified closure.

TYPE: int

element_type property

element_type: TypeExpr

Return the original complete trace type.

RETURNS DESCRIPTION
TypeExpr

A product of two Int states and a tensor of original arc IDs.

result_type property

result_type: TypeExpr

Return the checked Sampleable type for complete traces.

RETURNS DESCRIPTION
TypeExpr

The Sampleable instance over the original trace carrier.

bind

bind(parameters: RelationWeightBindings, *, generator: Generator) -> RelationPathLaw

Bind the original live weights to a closure-checked Random law.

PARAMETER DESCRIPTION
parameters

The original live weight owners.

TYPE: RelationWeightBindings

generator

The CPU generator for each attempted draw.

TYPE: Generator

RETURNS DESCRIPTION
RelationPathLaw

The bounded draw operation with full posterior trace scores.

RAISES DESCRIPTION
ValueError

The generator, binding, capacity, or normalizer is invalid.

RelationLimitError

Observation construction or closure exceeds its limit.

Source code in src/quivers/qiec/relation_path_law.py
def bind(
    self, parameters: RelationWeightBindings, *, generator: torch.Generator
) -> RelationPathLaw:
    """Bind the original live weights to a closure-checked Random law.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The original live weight owners.
    generator : torch.Generator
        The CPU generator for each attempted draw.

    Returns
    -------
    RelationPathLaw
        The bounded draw operation with full posterior trace scores.

    Raises
    ------
    ValueError
        The generator, binding, capacity, or normalizer is invalid.
    RelationLimitError
        Observation construction or closure exceeds its limit.
    """
    source = self.request
    query = source.relation.bind(parameters).query(
        source.words,
        max_states=source.max_states,
        max_work=source.max_work,
        max_closure_size=self.max_closure_size,
    )
    return RelationPathLaw(
        query,
        trace_capacity=source.trace_capacity,
        generator=generator,
        allow_cyclic=True,
    )

RelationPathLaw

RelationPathLaw(query: FixedStringQuery, *, trace_capacity: int, generator: Generator, allow_cyclic: bool = False)

Draw and score fixed-word posterior paths in a checked trace type.

PARAMETER DESCRIPTION
query

The observed path graph with live owned weights.

TYPE: FixedStringQuery

trace_capacity

Number of arc positions in a padded trace. Acyclic support must fit. A permitted cyclic draw fails if it needs another arc.

TYPE: int

generator

The CPU generator supplying each Random draw.

TYPE: Generator

allow_cyclic

Permit a certified cyclic fixed-word query with a per-draw resource ceiling and full posterior trace scores.

TYPE: bool DEFAULT: False

Source code in src/quivers/qiec/relation_path_law.py
def __init__(
    self,
    query: FixedStringQuery,
    *,
    trace_capacity: int,
    generator: torch.Generator,
    allow_cyclic: bool = False,
) -> None:
    _check_trace_capacity(query._relation.topology, trace_capacity)
    if not isinstance(generator, torch.Generator) or generator.device.type != "cpu":
        raise ValueError("a sparse path law needs a CPU generator")
    self._cyclic = query._walks._cyclic
    longest = None if allow_cyclic and self._cyclic else query.max_path_length
    if longest is not None and longest > trace_capacity:
        raise ValueError(
            "trace_capacity is smaller than a structurally accepting path"
        )
    with torch.no_grad():
        query._path_log_normalizer(query._log_path_weights())
    self._query = query
    self._capacity = trace_capacity
    self._generator = generator
    self._element = _trace_element_type(trace_capacity)

has_productive_cycle property

has_productive_cycle: bool

Whether the observation has structurally unbounded path support.

RETURNS DESCRIPTION
bool

True when a productive cycle can admit unbounded walks as the original live weights change.

element property

element: TypeExpr

Return the exact checked type of one complete path.

RETURNS DESCRIPTION
TypeExpr

A product with two states and the padded arc vector.

sample

sample() -> tuple[Tensor, Tensor, Tensor]

Draw a trace using the law's current weights and CPU generator.

RETURNS DESCRIPTION
tuple of torch.Tensor

The initial state, final state, and padded original arc IDs.

RAISES DESCRIPTION
RelationLimitError

A cyclic sample attempted to traverse past the trace capacity.

Source code in src/quivers/qiec/relation_path_law.py
def sample(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Draw a trace using the law's current weights and CPU generator.

    Returns
    -------
    tuple of torch.Tensor
        The initial state, final state, and padded original arc IDs.

    Raises
    ------
    RelationLimitError
        A cyclic sample attempted to traverse past the trace capacity.
    """
    with torch.no_grad():
        path = self._query._walks.sample(
            self._query._log_path_weights(dtype=torch.float64),
            LOG_PROB,
            self._generator,
            self._capacity,
        )
    padding = (-1,) * (self._capacity - len(path.arc_ids))
    values = path.initial_state, path.final_state, (*path.arc_ids, *padding)
    return (
        torch.tensor(values[0], dtype=torch.int64, device=path.weight.device),
        torch.tensor(values[1], dtype=torch.int64, device=path.weight.device),
        torch.tensor(values[2], dtype=torch.int64, device=path.weight.device),
    )

log_prob

log_prob(value: object, keep_batch: bool = False) -> Tensor

Score one trace in the fixed-word posterior.

PARAMETER DESCRIPTION
value

The initial state, final state, and padded original arc IDs in the checked machine's representation.

TYPE: object

keep_batch

This unbatched law accepts False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Tensor

The differentiable log probability, or negative infinity for a well-typed value outside the support.

RAISES DESCRIPTION
ValueError

A batch or a value outside the machine carrier was supplied.

Source code in src/quivers/qiec/relation_path_law.py
def log_prob(self, value: object, keep_batch: bool = False) -> torch.Tensor:
    """Score one trace in the fixed-word posterior.

    Parameters
    ----------
    value : object
        The initial state, final state, and padded original arc IDs
        in the checked machine's representation.
    keep_batch : bool
        This unbatched law accepts False.

    Returns
    -------
    torch.Tensor
        The differentiable log probability, or negative infinity
        for a well-typed value outside the support.

    Raises
    ------
    ValueError
        A batch or a value outside the machine carrier was supplied.
    """
    if keep_batch:
        raise ValueError("a sparse path law has no batch axes")
    if not isinstance(value, tuple) or len(value) != 3:
        raise ValueError(
            "a sparse path trace must have two states and an arc tensor"
        )
    initial = host_index(value[0], "path initial state")
    final = host_index(value[1], "path final state")
    arcs = value[2]
    if (
        not isinstance(arcs, torch.Tensor)
        or arcs.dtype != torch.int64
        or arcs.shape != (self._capacity,)
    ):
        raise ValueError(
            "path arc occurrence tensor does not match its Int capacity"
        )
    if depends_on_position(arcs):
        raise PositionDependentControl("path arc occurrence tensor")
    ids = tuple(arcs.tolist())
    if -1 in ids:
        stop = ids.index(-1)
        if all(arc_id == -1 for arc_id in ids[stop:]):
            ids = ids[:stop]
    return self._query.path_log_prob(initial, ids, final)

log_mass

log_mass(batch_axes: int = 0) -> Tensor

Return zero when the trace carrier represents the whole law.

PARAMETER DESCRIPTION
batch_axes

The retained batch rank, which must be zero.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Scalar log total mass in the underlying number domain.

RAISES DESCRIPTION
ValueError

A batch axis was requested or the current normalizer is invalid.

ProductiveEpsilonCycleError

The bounded trace carrier does not represent the whole cyclic law.

Source code in src/quivers/qiec/relation_path_law.py
def log_mass(self, batch_axes: int = 0) -> torch.Tensor:
    """Return zero when the trace carrier represents the whole law.

    Parameters
    ----------
    batch_axes : int
        The retained batch rank, which must be zero.

    Returns
    -------
    torch.Tensor
        Scalar log total mass in the underlying number domain.

    Raises
    ------
    ValueError
        A batch axis was requested or the current normalizer is invalid.
    ProductiveEpsilonCycleError
        The bounded trace carrier does not represent the whole cyclic law.
    """
    if type(batch_axes) is not int or batch_axes != 0:
        raise ValueError("a sparse path law has no batch axes")
    if self._cyclic:
        raise ProductiveEpsilonCycleError(
            "log_mass of a cyclic path law is unavailable on its bounded trace carrier"
        )
    weights = self._query._log_path_weights()
    self._query._path_log_normalizer(weights)
    return weights.new_zeros(())

Centered acyclic string log probabilities

CenteredStringLogProbRequest wraps either an authored fixed-input conditional request or an authored tree word query with LogProb weights. The centered evaluator requires binary64 weights and acyclic productive observations. Both likelihood sums read one evaluated vector of live original weights. The request sets a combined occurrence limit and an exact-work limit in addition to the original observation limits.

An ordinary QVR foreign Compute declaration uses the checked handler name from the request. The name records the exact original relation and ordered words, or the original graph, variable, and word. Execution returns the differentiable log probability and a four-element Int tensor of productive states, occurrences, weight slots, and dyadic work. Other policy bounds can reuse the same declaration. Stan, BUGS, and JAGS report the named native capability as unavailable.

CenteredStringLogProbRequest didactic-model

CenteredStringLogProbRequest(*, observation: FixedRelationRequest | TreeStringGraphRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_center_occurrences: int, max_dyadic_work: int)

Bases: QiecModel

Request a bounded centered native LogProb likelihood.

PARAMETER DESCRIPTION
observation

A checked fixed-input conditional or fixed-word tree marginal. It must declare a LogProb model without a productive closure.

TYPE: FixedRelationRequest or TreeStringGraphRequest DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_center_occurrences

The combined cap for productive arcs and boundary marks across the numerator and denominator.

TYPE: int

max_dyadic_work

The combined upper limit on exact-pass slot, state, and occurrence visits.

TYPE: int

handler_name property

handler_name: str

Identify the nominal graph, objective and words of this request.

RETURNS DESCRIPTION
str

The checked handler name shared by resource policies for the same objective.

result_type property

result_type: TypeExpr

Return the checked type for the log score and measured work.

RETURNS DESCRIPTION
TypeExpr

A LogWeight and the four state, occurrence, slot and exact-pass counts.

CenteredStringLogProbRuntimeProvider

CenteredStringLogProbRuntimeProvider(request: CenteredStringLogProbRequest, parameters: RelationWeightBindings)

Bind one centered native report to its original live weight owners.

PARAMETER DESCRIPTION
request

The fixed objective, typed model and compilation limits.

TYPE: CenteredStringLogProbRequest

parameters

The live scalar owners expected by the checked relation or graph.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/centered_string_runtime.py
def __init__(
    self, request: CenteredStringLogProbRequest, parameters: RelationWeightBindings
) -> None:
    self._query = request._compile(parameters)
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Install the runtime for this exact checked Compute declaration.

PARAMETER DESCRIPTION
module

The module containing the named foreign handler.

TYPE: QiecModule

attachments

The checked invocation's attachment table.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
TypeError

The corresponding declaration does not have the checked contract.

ValueError

The module lacks the expected foreign handler.

Source code in src/quivers/qiec/centered_string_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Install the runtime for this exact checked Compute declaration.

    Parameters
    ----------
    module : QiecModule
        The module containing the named foreign handler.
    attachments : RuntimeAttachments
        The checked invocation's attachment table.

    Raises
    ------
    TypeError
        The corresponding declaration does not have the checked contract.
    ValueError
        The module lacks the expected foreign handler.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Supply the runtime predicate for the checked report.

PARAMETER DESCRIPTION
type_

The requested runtime result type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The canonical validator for the matching report type.

Source code in src/quivers/qiec/centered_string_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Supply the runtime predicate for the checked report.

    Parameters
    ----------
    type_ : TypeExpr
        The requested runtime result type.

    Returns
    -------
    RuntimeValidator or None
        The canonical validator for the matching report type.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

Checked centered log-ratio certificates

CenteredStringLogProbCertificateRequest wraps the ordinary centered conditional or tree request with a rational absolute log tolerance and bounded verification settings. Its separate foreign handler identity includes the exact original centered objective and the tolerance. The provider reads one original weight snapshot for both the nominal packed score and the directed proof.

The existing value-certificate report shape returns a detached score, two rational log endpoints, a rational absolute error bound, and Decimal and exact-arithmetic work. A certified log-zero numerator has an available log-zero score, absent endpoints, and zero error by convention. The provider distinguishes insufficient accuracy, an undefined denominator, numerical range failure, unsupported closure or precision, and resource exhaustion. The certificate concerns the original dyadic inputs, including the effects of rounding the reduced factors. A refusal supplies no score or witness. The ordinary centered score and its live derivative remain available through their own request and handler.

CenteredStringLogProbCertificateRequest didactic-model

CenteredStringLogProbCertificateRequest(*, observation: CenteredStringLogProbRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), absolute_log_tolerance: tuple[int, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int)

Bases: QiecModel

Request a value-only certificate for a centered string log ratio.

PARAMETER DESCRIPTION
observation

The checked conditional or tree word score and its original owners.

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

absolute_log_tolerance

Nonnegative numerator and positive denominator in log units.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

decimal_precision

Precision, exponent bound, and combined work for directed residuals.

TYPE: int

max_decimal_exponent

Precision, exponent bound, and combined work for directed residuals.

TYPE: int

max_decimal_work

Precision, exponent bound, and combined work for directed residuals.

TYPE: int

max_exact_bits

Integer bit and operation caps for the exact verification pass.

TYPE: int

max_exact_work

Integer bit and operation caps for the exact verification pass.

TYPE: int

handler_name property

handler_name: str

Identify the checked observation and its exact absolute tolerance.

RETURNS DESCRIPTION
str

The distinct foreign handler name for this value guarantee.

result_type property

result_type: TypeExpr

Give the checked carrier of a score and exact rational endpoints.

RETURNS DESCRIPTION
TypeExpr

Status, diagnostic, score availability, log score, three rational rows, endpoint availability, and three work counters.

CenteredStringLogProbCertificateRuntimeProvider

CenteredStringLogProbCertificateRuntimeProvider(request: CenteredStringLogProbCertificateRequest | CenteredCyclicStringLogProbCertificateRequest, parameters: RelationWeightBindings)

Bind a centered value certificate to live original weight owners.

PARAMETER DESCRIPTION
request

The checked ratio, tolerance and directed arithmetic policy.

TYPE: CenteredStringLogProbCertificateRequest or CenteredCyclicStringLogProbCertificateRequest

parameters

The stable live scalar owner mapping for the relation or graph.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/centered_string_certificate.py
def __init__(
    self,
    request: CenteredStringLogProbCertificateRequest
    | CenteredCyclicStringLogProbCertificateRequest,
    parameters: RelationWeightBindings,
) -> None:
    self._request = request
    self._parameters = dict(parameters)
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Install the runtime on the exact checked foreign computation.

PARAMETER DESCRIPTION
module

The module declaring this observation and value guarantee.

TYPE: QiecModule

attachments

The invocation's checked attachment table.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
TypeError

The expected declaration does not have the checked contract.

ValueError

The module lacks the expected foreign handler.

Source code in src/quivers/qiec/centered_string_certificate.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Install the runtime on the exact checked foreign computation.

    Parameters
    ----------
    module : QiecModule
        The module declaring this observation and value guarantee.
    attachments : RuntimeAttachments
        The invocation's checked attachment table.

    Raises
    ------
    TypeError
        The expected declaration does not have the checked contract.
    ValueError
        The module lacks the expected foreign handler.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Supply the validator for this request's exact result type.

PARAMETER DESCRIPTION
type_

The requested runtime result type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The canonical validator when the type matches this report.

Source code in src/quivers/qiec/centered_string_certificate.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Supply the validator for this request's exact result type.

    Parameters
    ----------
    type_ : TypeExpr
        The requested runtime result type.

    Returns
    -------
    RuntimeValidator or None
        The canonical validator when the type matches this report.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

Checked centered cyclic string log ratios

CenteredCyclicStringLogProbCertificateRequest wraps a checked fixed-input LogProb conditional observation with a local closure order limit. It adds a shared closure-cell cap and the two centered proof budgets. The distinct handler keeps the original relation, words and absolute log tolerance. The centered certificate provider returns the same value-only rational endpoint report shape. Proven divergence, unverified upper-star finiteness, and an unavailable numerical star have distinct statuses. The cyclic centered contract is available for fixed-input conditionals. Tree-centered certificates use the acyclic request.

CenteredCyclicStringLogProbCertificateRequest didactic-model

CenteredCyclicStringLogProbCertificateRequest(*, observation: FixedRelationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_center_occurrences: int, max_dyadic_work: int, max_closure_cells: int, absolute_log_tolerance: tuple[int, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int)

Bases: QiecModel

Request a bounded checked fixed-input cyclic likelihood certificate.

PARAMETER DESCRIPTION
observation

The original LogProb conditional objective, words, and local star order limit.

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

max_center_occurrences

Aggregate centered observation occurrence and graph visit caps.

TYPE: int

max_dyadic_work

Aggregate centered observation occurrence and graph visit caps.

TYPE: int

max_closure_cells

Combined numeric closure cells, including auxiliary states.

TYPE: int

absolute_log_tolerance

Nonnegative numerator and positive denominator in log units.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

decimal_precision

Directed precision, exponent limit, and combined Decimal work.

TYPE: int

max_decimal_exponent

Directed precision, exponent limit, and combined Decimal work.

TYPE: int

max_decimal_work

Directed precision, exponent limit, and combined Decimal work.

TYPE: int

max_exact_bits

Integer bit and operation caps for gauges, endpoint stars, and the value test.

TYPE: int

max_exact_work

Integer bit and operation caps for gauges, endpoint stars, and the value test.

TYPE: int

handler_name property

handler_name: str

Identify the original conditional objective and rational tolerance.

RETURNS DESCRIPTION
str

The distinct checked handler name for the cyclic value guarantee.

result_type property

result_type: TypeExpr

Give the checked carrier of a score and its exact rational endpoints.

RETURNS DESCRIPTION
TypeExpr

Status, diagnostic, score availability, log score, three rational rows, endpoint availability, and three arithmetic work counters.

A tail outcome for capped cyclic paths

FixedCappedCyclicRelationPathSampleRequest specifies a different checked law on the same original paths. At capacity \(K\) it retains each accepting walk of at most \(K\) traversals and maps every longer walk to one Tail outcome. The tagged element type is (Bool * Int * Int * Int[Fin K]). A false tag carries a complete original trace with trailing -1 padding. A true tag carries -1 in both state fields and every arc position. This distinguishes a genuine empty trace at capacity zero. Noncanonical typed records have zero probability.

Write \(\alpha_j(s)\) for the mass of prefixes that start at an initial mark, take exactly \(j\) original arcs, and arrive at observation state \(s\). Write \(h(s)\) for its total accepting suffix mass and \(Z\) for the original fixed-word normalizer. Each longer accepting walk has exactly one prefix of length \(K+1\). Thus

\[ P(\mathrm{Tail})=\frac{\sum_s \alpha_{K+1}(s)h(s)}{Z}. \]

The prefix pass ignores stop choices and preserves parallel arc multiplicity. The suffix includes all accepting stops and longer continuations, using the same convergence-checked local stars as the ordinary path law. A retained trace has its original mass divided by \(Z\). These outcomes partition the full posterior, so log_mass gives zero after checking the live \(Z\). Evaluation computes Tail from the positive terms of its own sum. This preserves a finite log tail even when its probability is below the linear float64 range.

For a draw, the sampler uses float64 suffix conditionals. After \(K\) traversals, stopping returns the retained trace and continuing returns Tail, with no further random choices. The checked Random and replay handlers use the same tagged value type. Probability and normalization statements describe the mathematical pushforward. Computed scores, their gradients, and random choice probabilities use float64 arithmetic. Scores differentiate the fixed outcome through the live weights, suffix closure, and normalizer on positive support. The checked law supports log_prob and log_mass directly, and the implicit support is unavailable to the finite enumeration handler.

For \(V\) active states and \(E\) active original arc occurrences, the packed prefix map has \(O(V+E)\) stored entries and reuses its incoming groups across all \(K+1\) layers. The work cap uses the conservative count \((K+1)(3E+2V)+|I|+2V\), including padded reductions and initial and final work for \(|I|\) initial states. The depth grid has \((K+2)V\) state cells, bounded by max_prefix_cells. Without autograd the prefix sweep needs \(O(V+E)\) live tensor entries. Backward through it may retain \(O((K+1)(V+E))\) entries, with the suffix chart and its held closure tensors accounted for separately. Observation, order, aggregate closure cells, and prefix limits are checked before a draw. The existing untagged path request retains its bounded-attempt execution contract.

FixedCappedCyclicRelationPathSampleRequest didactic-model

FixedCappedCyclicRelationPathSampleRequest(*, request: FixedCyclicRelationPathSampleRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_closure_cells: int, max_prefix_work: int, max_prefix_cells: int)

Bases: QiecModel

Request a checked cyclic path posterior with a single tail outcome.

PARAMETER DESCRIPTION
request

Original nominal weights, ordered words, graph and local closure order limits, and the retained original trace capacity.

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

max_closure_cells

The aggregate local star cell limit, including auxiliary states.

TYPE: int

max_prefix_work

The bound on charged prefix gathers, padded joins, layer values, and initial and final reductions.

TYPE: int

max_prefix_cells

The bound on the number of active state and prefix depth pairs.

TYPE: int

element_type property

element_type: TypeExpr

Return the distinct tagged outcome type.

RETURNS DESCRIPTION
TypeExpr

The carrier of a retained trace or the tail.

result_type property

result_type: TypeExpr

Return the Sampleable type for capped paths.

RETURNS DESCRIPTION
TypeExpr

The Sampleable instance over the distinct tagged carrier.

bind

bind(parameters: RelationWeightBindings, *, generator: Generator) -> CappedRelationPathLaw

Bind the requested law to the original live weights.

PARAMETER DESCRIPTION
parameters

The original live scalar weight owners.

TYPE: RelationWeightBindings

generator

The CPU generator for native Random draws.

TYPE: Generator

RETURNS DESCRIPTION
CappedRelationPathLaw

The normalized law on retained traces and one tail value.

RAISES DESCRIPTION
ValueError

A binding, generator, or observed normalizer is invalid.

RelationLimitError

Graph or prefix construction exceeds a declared limit.

Source code in src/quivers/qiec/relation_capped_path_law.py
def bind(
    self, parameters: RelationWeightBindings, *, generator: torch.Generator
) -> CappedRelationPathLaw:
    """Bind the requested law to the original live weights.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The original live scalar weight owners.
    generator : torch.Generator
        The CPU generator for native Random draws.

    Returns
    -------
    CappedRelationPathLaw
        The normalized law on retained traces and one tail value.

    Raises
    ------
    ValueError
        A binding, generator, or observed normalizer is invalid.
    RelationLimitError
        Graph or prefix construction exceeds a declared limit.
    """
    return CappedRelationPathLaw(self, parameters, generator=generator)

CappedRelationPathLaw

CappedRelationPathLaw(request: FixedCappedCyclicRelationPathSampleRequest, parameters: RelationWeightBindings, *, generator: Generator)

Push a fixed-word posterior onto retained original traces and one tail.

A true tag denotes the tail and accompanies -1 in every trace field. A false tag denotes a complete original trace, with -1 suffix padding. The tail contains every accepting path with more than the capacity's original arc traversals. The law samples and scores in float64. Scores differentiate with respect to the original weights.

PARAMETER DESCRIPTION
request

The checked observation, capacity, and evaluation limits.

TYPE: FixedCappedCyclicRelationPathSampleRequest

parameters

The original live scalar weight owners.

TYPE: RelationWeightBindings

generator

The CPU generator for native Random draws.

TYPE: Generator

Source code in src/quivers/qiec/relation_capped_path_law.py
def __init__(
    self,
    request: FixedCappedCyclicRelationPathSampleRequest,
    parameters: RelationWeightBindings,
    *,
    generator: torch.Generator,
) -> None:
    if not isinstance(generator, torch.Generator) or generator.device.type != "cpu":
        raise ValueError("a capped path law needs a CPU generator")
    cyclic = request.request
    source = cyclic.request
    paths = _CappedPaths(
        source.relation.bind(parameters),
        source.words,
        source.trace_capacity,
        max_states=source.max_states,
        max_work=source.max_work,
        max_closure_size=cyclic.max_closure_size,
        max_closure_cells=request.max_closure_cells,
        max_prefix_work=request.max_prefix_work,
        max_prefix_cells=request.max_prefix_cells,
    )
    with torch.no_grad():
        paths.log_mass()
    self._paths = paths
    self._capacity = source.trace_capacity
    self._element = _capped_trace_type(self._capacity)
    self._generator = generator

element property

element: TypeExpr

Return the exact checked carrier of a draw.

RETURNS DESCRIPTION
TypeExpr

The tagged original trace product.

sample

sample() -> tuple[Tensor, Tensor, Tensor, Tensor]

Draw a retained path or the tail from the live full posterior.

RETURNS DESCRIPTION
tuple of torch.Tensor

The CPU outcome flag, boundary states, and padded arc IDs.

Source code in src/quivers/qiec/relation_capped_path_law.py
def sample(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """Draw a retained path or the tail from the live full posterior.

    Returns
    -------
    tuple of torch.Tensor
        The CPU outcome flag, boundary states, and padded arc IDs.
    """
    with torch.no_grad():
        path = self._paths.sample(self._generator)
    if path is None:
        start, end, ids = -1, -1, (-1,) * self._capacity
    else:
        start, end = path.initial_state, path.final_state
        padding = (-1,) * (self._capacity - len(path.arc_ids))
        ids = (*path.arc_ids, *padding)
    return (
        torch.tensor(path is None, dtype=torch.bool),
        torch.tensor(start, dtype=torch.int64),
        torch.tensor(end, dtype=torch.int64),
        torch.tensor(ids, dtype=torch.int64),
    )

log_prob

log_prob(value: object, keep_batch: bool = False) -> Tensor

Score one tagged outcome under the current pushforward law.

PARAMETER DESCRIPTION
value

The native tagged trace or tail record.

TYPE: object

keep_batch

The unbatched law accepts False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Tensor

Its differentiable log mass, or log zero outside the support.

RAISES DESCRIPTION
ValueError

A batch or a value outside the typed carrier was supplied.

PositionDependentControl

A tag or occurrence identity depends on the evaluation position.

Source code in src/quivers/qiec/relation_capped_path_law.py
def log_prob(self, value: object, keep_batch: bool = False) -> torch.Tensor:
    """Score one tagged outcome under the current pushforward law.

    Parameters
    ----------
    value : object
        The native tagged trace or tail record.
    keep_batch : bool
        The unbatched law accepts False.

    Returns
    -------
    torch.Tensor
        Its differentiable log mass, or log zero outside the support.

    Raises
    ------
    ValueError
        A batch or a value outside the typed carrier was supplied.
    PositionDependentControl
        A tag or occurrence identity depends on the evaluation position.
    """
    if keep_batch:
        raise ValueError("a capped path law has no batch axes")
    if not isinstance(value, tuple) or len(value) != 4:
        raise ValueError("a capped outcome needs a tag and three trace fields")
    tag, start, end, occurrences = value
    if (
        not isinstance(tag, torch.Tensor)
        or tag.ndim != 0
        or tag.dtype != torch.bool
    ):
        raise ValueError("a capped outcome needs a scalar Bool tag")
    initial = host_index(start, "path initial state")
    final = host_index(end, "path final state")
    if (
        not isinstance(occurrences, torch.Tensor)
        or occurrences.dtype != torch.int64
        or occurrences.shape != (self._capacity,)
    ):
        raise ValueError(
            "path arc occurrence tensor does not match its Int capacity"
        )
    if depends_on_position(tag) or depends_on_position(occurrences):
        raise PositionDependentControl("capped path outcome")
    ids = tuple(occurrences.tolist())
    if bool(tag):
        canonical = initial == final == -1 and all(arc == -1 for arc in ids)
        return self._paths.log_prob(None, tail=canonical)
    if -1 in ids:
        stop = ids.index(-1)
        if any(arc != -1 for arc in ids[stop:]):
            return self._paths.log_prob(None)
        ids = ids[:stop]
    return self._paths.log_prob((initial, ids, final))

log_mass

log_mass(batch_axes: int = 0) -> Tensor

Return the log mass of the full tagged carrier.

PARAMETER DESCRIPTION
batch_axes

The retained batch rank, which must be zero.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Tensor

Log one after checking the live full path normalizer.

RAISES DESCRIPTION
ValueError

A batch axis was requested or the current normalizer is invalid.

Source code in src/quivers/qiec/relation_capped_path_law.py
def log_mass(self, batch_axes: int = 0) -> torch.Tensor:
    """Return the log mass of the full tagged carrier.

    Parameters
    ----------
    batch_axes : int
        The retained batch rank, which must be zero.

    Returns
    -------
    torch.Tensor
        Log one after checking the live full path normalizer.

    Raises
    ------
    ValueError
        A batch axis was requested or the current normalizer is invalid.
    """
    if type(batch_axes) is not int or batch_axes != 0:
        raise ValueError("a capped path law has no batch axes")
    return self._paths.log_mass()

Checked deterministic path ranking

FixedRelationPathRankRequest ranks up to \(k\) positive complete paths at a fixed word tuple. Choose \(k=1\) for the deterministic best path. The native result contains an Int valid-row count, a \(k\times2\) matrix of original boundary states, a \(k\times C\) matrix of ordered original arc occurrence IDs, and \(k\) original-algebra path weights. LogProb uses LogWeight, and Markov uses Real. Absent rows have both states set to -1 and semiring-zero weight. An empty accepting path has real boundary states and no arc IDs. All unused arc positions use -1.

Ties follow original initial-mark order. From a fixed configuration, the stop precedes outgoing arcs. All-epsilon arcs precede the indexed first emitting tape order, and arcs within that index keep their original occurrence order. The same comparison applies recursively to the remaining path. Score derivatives hold the selected occurrence sequence fixed, including at a tie.

The checked provider constructs the sparse observation once and reads the original weights for each invocation. max_states and max_work bound observation construction. With \(Q\) active states, the retained suffix records and the selected path positions each have a bound of \(k(Q+1)\), checked against max_rank_entries. Let \(d\) range over all structural local merge degrees, including the initial merge. Each degree counts one stream per productive arc and one for a stop when available. The max_rank_work allowance sums \(d+k(1+\lceil\log_2(d+1)\rceil)\) over positive degrees and adds the number of original weight slots. This accounts for weight-slot reads, stream visits, and the growth in heap work per retained entry. Rank arithmetic uses exact binary rationals, whose bit costs depend on the weights and lengths.

The output requires \(1+k(C+3)\) cells and checks max_result_cells before compilation. A selected path longer than \(C\) raises a resource error. Productive cycles are outside the ranking capability. The reserved foreign Compute name binds the exact original nominal topology, word tuple, and result dimensions. No code generation fallback is supplied for a target without this native capability.

FixedRelationPathRankRequest didactic-model

FixedRelationPathRankRequest(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), k: int, trace_capacity: int, max_states: int, max_work: int, max_rank_entries: int, max_rank_work: int, max_result_cells: int)

Bases: QiecModel

Rank positive original paths on a fixed-word productive DAG.

The result contains a valid-row count, a pair of original boundary states per row, ordered original arc IDs, and unnormalized path weights. Trailing arc positions and missing rows use -1. Missing weights use the semiring zero. The first row with rank count one is the ordinary deterministic best path.

PARAMETER DESCRIPTION
relation

The typed Markov or LogProb topology and original weight owners.

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

words

One observed word per tape in tape order.

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

k

Positive number of result rows and maximum retained path rank.

TYPE: int

trace_capacity

Extent of each row's original arc occurrence vector.

TYPE: int

max_states

Limits on states and candidate arcs in the fixed-word graph.

TYPE: int

max_work

Limits on states and candidate arcs in the fixed-word graph.

TYPE: int

max_rank_entries

Bound on the product of k and one plus the active state count.

TYPE: int

max_rank_work

Bound on weight-slot reads, stream visits, and the heap work allowance.

TYPE: int

max_result_cells

Total scalar-cell limit across the result's four fields.

TYPE: int

handler_name property

handler_name: str

Derive the checked owner of the observation and rank shape.

RETURNS DESCRIPTION
str

The foreign handler identity of the topology, words and shape.

result_type property

result_type: TypeExpr

Type the count, endpoints, original arc IDs, and scores.

RETURNS DESCRIPTION
TypeExpr

A scalar Int, two Int matrices, and an algebra-specific vector.

FixedRelationPathRankRuntimeProvider

FixedRelationPathRankRuntimeProvider(request: FixedRelationPathRankRequest, parameters: RelationWeightBindings)

Bind a deterministic sparse path ranking to checked native Compute.

The provider compiles the observation graph once. Each evaluation reads the current weights and ranks complete original paths. A returned score differentiates its selected path with the occurrence IDs fixed, including at ties in the deterministic ordering.

PARAMETER DESCRIPTION
request

The checked topology, observation, exact rank, and limits.

TYPE: FixedRelationPathRankRequest

parameters

The original live weight owners of the relation.

TYPE: RelationWeightBindings

RAISES DESCRIPTION
ProductiveEpsilonCycleError

The structural observation graph has a productive epsilon cycle.

RelationLimitError

Observation construction, rank storage, or rank work exceeds a limit.

Source code in src/quivers/qiec/relation_path_rank.py
def __init__(
    self, request: FixedRelationPathRankRequest, parameters: RelationWeightBindings
) -> None:
    self._request = request
    self._walks = _PathWalks(
        request.relation.topology,
        request.words,
        request.max_states,
        request.max_work,
        None,
    )
    if self._walks._cyclic:
        raise ProductiveEpsilonCycleError(
            "path ranking requires an acyclic productive graph"
        )
    if request.k * (len(self._walks._order) + 1) > request.max_rank_entries:
        raise RelationLimitError("ranked paths exceed max_rank_entries")
    degrees = (
        len(self._walks._initial),
        *(
            len(self._walks._arcs[state]) + int(state in self._walks._final)
            for state in self._walks._order
        ),
    )
    # Each merge visits d structural streams and uses at most k rank
    # positions with an O(1 + log(d + 1)) heap operation per position.
    rank_work = len(request.relation.topology.weight_names) + sum(
        d + request.k * (1 + d.bit_length()) for d in degrees if d
    )
    if rank_work > request.max_rank_work:
        raise RelationLimitError("ranked paths exceed max_rank_work")
    self._relation = request.relation.bind(parameters)
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Bind the provider to the matching authored foreign Compute.

PARAMETER DESCRIPTION
module

Module with the checked once-resuming handler.

TYPE: QiecModule

attachments

Runtime handler bindings for the computation.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

The module has no handler for this exact observation and shape.

TypeError

The matched handler has an incompatible Compute contract.

Source code in src/quivers/qiec/relation_path_rank.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Bind the provider to the matching authored foreign Compute.

    Parameters
    ----------
    module : QiecModule
        Module with the checked once-resuming handler.
    attachments : RuntimeAttachments
        Runtime handler bindings for the computation.

    Raises
    ------
    ValueError
        The module has no handler for this exact observation and shape.
    TypeError
        The matched handler has an incompatible Compute contract.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Supply the core validator for this exact numeric product.

PARAMETER DESCRIPTION
type_

The result carrier requested by the reference machine.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The checked product validator, when the result carrier matches.

Source code in src/quivers/qiec/relation_path_rank.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Supply the core validator for this exact numeric product.

    Parameters
    ----------
    type_ : TypeExpr
        The result carrier requested by the reference machine.

    Returns
    -------
    RuntimeValidator or None
        The checked product validator, when the result carrier matches.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

Checked sparse relation transformations

A UnaryRelationTransformSpec stores the original typed topology, parameter identities, and one supported operation. Projection sums over erased tapes. Conditioning fixes one tape word. Inversion exchanges the input and output groups, trim retains only structurally productive records, and closure permits all finite repetitions.

The auto_intersect recipe constrains two distinct positions with the same nominal tape type to emit equal words, retaining both tapes in their original positions. It uses the checked signed-delay construction. Every accepted source path contributes once with its original weights. A cascade may project away either or both constrained tapes afterward. The compiler charges signed-cycle relaxations and residual product arc visits to max_work, after the linear structural trim. Productive paths with opposite-sign cycles fail the applicability check. The budget applies to the exact transformation and carries no approximation claim. In ordinary QVR, write relation synced = auto_intersect(original, 0, 1). A typed score binding can use that recipe directly or use a cascade that projects away the synchronized tapes. The score owner includes the authored tape positions and operand identity.

A BinaryRelationTransformSpec keeps both original operands in order. Union adds their weights. Concatenation sums over the possible splits of each observed word. A join synchronizes one common typed tape and can retain it once or sum over it. Intersection is the shared-tape case for two languages. These products use the bounded epsilon filter to count each compatible pair of paths once.

A FixedTransformedRelationRequest provides the retained word tuple and explicit query limits. Conditioning also uses those limits for its intermediate topology. A binary sparse product uses the same limits for its own construction. The reference provider builds and reuses the transformed topology and query. Each evaluation reads the original live parameters. A productive cycle needs a declared closure bound up to the limit supported by the scalar algebra.

This request supports a linear Compute pair weight, including an typed QVR binding that calls pair_weight(). Native targets identify the foreign handler as a required runtime capability.

UnaryRelationTransformSpec didactic-model

UnaryRelationTransformSpec(*, source: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), operation: _UnaryOperation, positions: tuple[int, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), word: tuple[int, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A checked unary recipe that retains the source's original weight identities.

Projection sums over erased tapes. Conditioning keeps paths that match one fixed tape. Inversion exchanges input and output tape order; trimming removes structurally unproductive records. Closure adds all finite repetitions of the original paths. Auto-intersection requires two tapes to realize the same word.

PARAMETER DESCRIPTION
source

The checked original topology and live parameter identities.

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

operation

The specific supported topology transformation.

TYPE: str

positions

For projection, the increasing retained tape positions. For conditioning, the single fixed tape. For auto-intersection, the two distinct tapes with the same nominal type.

TYPE: tuple of int DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

word

The fixed word for conditioning, including an empty tuple.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

bind

bind(parameters: RelationWeightBindings, *, max_states: int, max_work: int) -> RationalRelation

Construct and bind the transformed sparse relation.

PARAMETER DESCRIPTION
parameters

The original scalar weight bindings.

TYPE: RelationWeightBindings

max_states

State limit for conditioning or tape-equality configurations.

TYPE: int

max_work

Arc examination and signed-delay analysis limit.

TYPE: int

RETURNS DESCRIPTION
RationalRelation

The transformed topology with the original weights.

Source code in src/quivers/qiec/relation_transforms.py
def bind(
    self,
    parameters: RelationWeightBindings,
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Construct and bind the transformed sparse relation.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The original scalar weight bindings.
    max_states : int
        State limit for conditioning or tape-equality configurations.
    max_work : int
        Arc examination and signed-delay analysis limit.

    Returns
    -------
    RationalRelation
        The transformed topology with the original weights.
    """
    _validate_limits(max_states, max_work)
    source = self.source.bind(parameters)
    return _apply_unary(
        source,
        self.operation,
        self.positions,
        self.word,
        max_states=max_states,
        max_work=max_work,
    )

BinaryRelationTransformSpec didactic-model

BinaryRelationTransformSpec(*, left: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), right: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), operation: Literal['union', 'concatenate', 'intersect', 'join'], shared_tapes: tuple[int, int] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), keep_shared: bool = False)

Bases: QiecModel

A checked two-operand recipe with ordered typed weight sources.

Union adds masses with distinct path occurrences. Concatenation sums over word splittings. Intersection and join sum over compatible pairs, using the bounded epsilon-filtered product.

PARAMETER DESCRIPTION
left

The ordered original typed operands.

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

right

The ordered original typed operands.

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

operation

The supported binary transformation.

TYPE: str

shared_tapes

One position per operand when using a single-tape join.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

keep_shared

Whether a join retains the selected tape at its left position.

TYPE: bool DEFAULT: False

bind

bind(parameters: RelationWeightBindings, *, max_states: int, max_work: int) -> RationalRelation

Construct the checked sparse operation with its original leaves.

PARAMETER DESCRIPTION
parameters

The original shared scalar parameters of the two operands.

TYPE: RelationWeightBindings

max_states

State limit for a sparse product.

TYPE: int

max_work

Label-probe and arc examination limit for a sparse product.

TYPE: int

RETURNS DESCRIPTION
RationalRelation

The transformed sparse relation with live weight sources.

Source code in src/quivers/qiec/relation_transforms.py
def bind(
    self,
    parameters: RelationWeightBindings,
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Construct the checked sparse operation with its original leaves.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The original shared scalar parameters of the two operands.
    max_states : int
        State limit for a sparse product.
    max_work : int
        Label-probe and arc examination limit for a sparse product.

    Returns
    -------
    RationalRelation
        The transformed sparse relation with live weight sources.
    """
    _validate_limits(max_states, max_work)
    left, right = _bind_relation_operands(
        self.left, self.right, parameters, description="binary relation"
    )
    return _apply_binary(
        left,
        right,
        self.operation,
        self.shared_tapes,
        self.keep_shared,
        max_states=max_states,
        max_work=max_work,
    )

A RelationCascadeSpec extends this recipe to a dependency-ordered table of named declarations. A reference to an earlier step can occur in either operand position or in both. Sharing construction and weight reads preserves the path multiplicity of each operation. Cycles between declarations, ill-typed layouts, and unused steps are refused before binding. The provider evaluates the table in order and keeps a fresh weight snapshot for each call, so parameter mutations and gradients use the original owners.

In a cascade, max_states limits the state count of each intermediate topology. max_work limits the number of distinct steps, the number of retained topology records at each step, and the native sparse construction work at each conditioned or product step. The storage count includes tapes, arcs, per-tape labels, initial and final marks, and weight slots. Linear operations that expand the topology check their output size before allocation. Native sparse products can temporarily produce labels for up to the allowed arcs at the inferred tape width before checking the retained record count. The final fixed observation and any productive component closure have their own query limits. For \(s\) steps and limits \(S\) and \(W\), the retained intermediate tables have at most \(sS\) states and \(sW\) records. Each evaluation reads each distinct weight source once. Both references to a shared operand still contribute to the enclosing operation's path sum and gradient.

RelationCascadeStep didactic-model

RelationCascadeStep(*, name: str, primitive: RationalRelationSpec | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), operation: Literal['project', 'condition', 'invert', 'trim', 'closure', 'auto_intersect', 'compose', 'union', 'concatenate', 'intersect', 'join'] | None = None, operands: tuple[int, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), positions: tuple[int, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), word: tuple[int, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), keep_shared: bool = False)

Bases: QiecModel

One named primitive relation or an ordered operation in a cascade.

PARAMETER DESCRIPTION
name

The nominal source declaration name.

TYPE: str

primitive

The original topology and weight owners of a primitive step.

TYPE: RationalRelationSpec or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

operation

The sparse operation of a derived step.

TYPE: str or None DEFAULT: None

operands

The earlier step indices, in operation order.

TYPE: tuple of int DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

positions

Tape positions for project, condition, join, and auto-intersection.

TYPE: tuple of int DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

word

The fixed tape word for conditioning.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

keep_shared

Whether a join retains its synchronized tape.

TYPE: bool DEFAULT: False

RelationCascadeSpec didactic-model

RelationCascadeSpec(*, steps: tuple[RelationCascadeStep, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An acyclic checked sparse relation program with the last step as its result.

Every step is used by the result. The step table preserves names, dependency sharing, ordered operand occurrences, and primitive parameter ownership. Each native operation uses the same sparse compiler as a single checked relation transformation.

PARAMETER DESCRIPTION
steps

Dependency-ordered steps, each referring only to earlier indices.

TYPE: tuple of RelationCascadeStep DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

algebra property

algebra: ClaimSubject

Return the trusted identity of the cascade's scalar semiring.

RETURNS DESCRIPTION
ClaimSubject

The algebra of every primitive and operation in the result.

bind

bind(parameters: RelationWeightBindings, *, max_states: int, max_work: int) -> RationalRelation

Build one bounded sparse topology per step with live original weights.

Construction uses at most one visit per shared declaration. The per-step bound limits native construction states, probes or matched arcs, and topology records. The same work limit bounds the number of distinct steps. Evaluation visits this table once and reads each weight source once per call, caching only within that differentiable call. The final fixed observation has its own limits.

PARAMETER DESCRIPTION
parameters

The live scalar tensors for original primitive parameter IDs.

TYPE: RelationWeightBindings

max_states

The state limit for each sparse intermediate.

TYPE: int

max_work

The operation work and intermediate topology record limit, and the number of distinct steps.

TYPE: int

RETURNS DESCRIPTION
RationalRelation

The cascade result with live reads of its primitive weights.

RAISES DESCRIPTION
RelationLimitError

Construction, storage, or the step count exceeds the budget.

ValueError

Different IDs alias a tensor or bindings disagree on tensor domain.

Source code in src/quivers/qiec/relation_cascades.py
def bind(
    self,
    parameters: RelationWeightBindings,
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Build one bounded sparse topology per step with live original weights.

    Construction uses at most one visit per shared declaration. The
    per-step bound limits native construction states, probes or
    matched arcs, and topology records. The same work limit bounds
    the number of distinct steps. Evaluation visits this table
    once and reads each weight source once per call, caching only
    within that differentiable call. The final fixed observation
    has its own limits.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The live scalar tensors for original primitive parameter IDs.
    max_states : int
        The state limit for each sparse intermediate.
    max_work : int
        The operation work and intermediate topology record limit,
        and the number of distinct steps.

    Returns
    -------
    RationalRelation
        The cascade result with live reads of its primitive weights.

    Raises
    ------
    RelationLimitError
        Construction, storage, or the step count exceeds the budget.
    ValueError
        Different IDs alias a tensor or bindings disagree on tensor domain.
    """
    self._check_budgets(max_states, max_work)
    primitives = tuple(
        step.primitive for step in self.steps if step.primitive is not None
    )
    _weight_bindings(
        (identity for spec in primitives for identity in spec.weight_parameters),
        parameters,
        description="cascade",
    )
    primitive_machines = iter(tuple(spec.bind(parameters) for spec in primitives))
    results: list[RationalRelation] = []
    for step in self.steps:
        if step.primitive is not None:
            results.append(next(primitive_machines))
            continue
        assert step.operation is not None
        left = results[step.operands[0]]
        right = results[step.operands[1]] if len(step.operands) == 2 else None
        _preflight_expanding_step(
            step.operation,
            left.topology,
            None if right is None else right.topology,
            max_states,
            max_work,
        )
        if right is None:
            result = _apply_unary(
                left,
                cast(_UnaryOperation, step.operation),
                step.positions,
                step.word,
                max_states=max_states,
                max_work=max_work,
            )
        else:
            result = _apply_binary(
                left,
                right,
                cast(_BinaryOperation, step.operation),
                step.positions or None,
                step.keep_shared,
                max_states=max_states,
                max_work=max_work,
            )
        top = result.topology
        _check_size(top.n_states, _records(top), max_states, max_work)
        results.append(result)
    root = results[-1]
    return RationalRelation(
        root.topology, _CascadeWeights(tuple(results)), algebra=root.algebra
    )

FixedTransformedRelationRequest didactic-model

FixedTransformedRelationRequest(*, relation: UnaryRelationTransformSpec | BinaryRelationTransformSpec | RelationCascadeSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, max_closure_size: int | None = None)

Bases: QiecModel

A typed fixed observation of a transformed sparse relation.

The wire preserves the original relation and the operation name. The provider creates the sparse topology and query once. Reads of the compiled query always evaluate the current original weights.

PARAMETER DESCRIPTION
relation

The original relation and its transformation.

TYPE: UnaryRelationTransformSpec or BinaryRelationTransformSpec or RelationCascadeSpec DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

words

One observed word per transformed tape.

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

max_states

State budget for sparse transforms and each fixed observation.

TYPE: int

max_work

Work budget for sparse transforms and each fixed observation. A cascade also limits the number of steps and the records in each topology.

TYPE: int

max_closure_size

Optional bound for productive cyclic closure components.

TYPE: int or None DEFAULT: None

operation property

operation: Literal['pair_weight']

Return the fixed-tuple path sum objective.

RETURNS DESCRIPTION
str

The checked pair-weight objective.

result_type property

result_type: TypeExpr

Return the scalar score carrier of the transformed relation.

RETURNS DESCRIPTION
TypeExpr

LogWeight for LogProb and Real for Markov.

plan

Compile the bounded sparse query with original scalar weights.

PARAMETER DESCRIPTION
parameters

The live original source weights.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
FixedStringQuery

The reusable fixed observation plan.

Source code in src/quivers/qiec/relation_transforms.py
def plan(self, parameters: RelationWeightBindings) -> FixedStringQuery:
    """Compile the bounded sparse query with original scalar weights.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The live original source weights.

    Returns
    -------
    FixedStringQuery
        The reusable fixed observation plan.
    """
    relation = self.relation.bind(
        parameters, max_states=self.max_states, max_work=self.max_work
    )
    return relation.query(
        self.words,
        max_states=self.max_states,
        max_work=self.max_work,
        max_closure_size=self.max_closure_size,
    )

Checked log feature moments

A FixedRelationFeatureObservation records fixed words, the original typed relation, a positive feature extent \(d\), and optional boundary features. Each table has one row per original occurrence and \(d\) columns. Entries contain finite log increments or None for log zero. The codec preserves None as JSON null. The provider restores it as negative infinity on the original weight dtype and device.

The observation's handler_name identifies its exact topology, words, and ordered features. A checked foreign handler at that name declares Compute[Unit, LogWeight[Fin d+1]]. Its result places the log total first and the unnormalized log moments in feature order. Use FixedRelationRuntimeProvider with the request and its handler_name to attach the evaluator. The provider reads the original parameter objects each time the handler runs. An observation with no accepting mass returns log zero in every position.

FixedRelationFeatureMomentRequest sets independent state, examined-arc, and feature-cell limits. The feature-cell count is \((d+1)(N+V+E)\), where \(N\) counts original arc and boundary occurrences, and \(V\) and \(E\) count productive states and arcs in the observation. Budget changes keep the observation's handler name. A productive epsilon cycle requires a different carrier capability. Native targets that require foreign calls to be discharged report the observation's handler as the obstacle.

FixedRelationFeatureObservation didactic-model

FixedRelationFeatureObservation(*, relation: RationalRelationSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), words: Words = field(opaque=True, extras=OPAQUE_BY_VALUE), feature_extent: int, arc_logs: _LogTable = field(opaque=True, extras=OPAQUE_BY_VALUE), initial_logs: _LogTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), final_logs: _LogTable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A fixed typed relation observation and nonnegative local features.

The original topology fixes the order of initial, arc, and final occurrences. Feature columns remain ordered even when some are identically zero. Each entry is a finite log increment or None for log zero. An omitted boundary table is all log zero.

PARAMETER DESCRIPTION
relation

The original typed topology and stable weight identities.

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

words

The fixed words in declared tape order.

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

feature_extent

The positive number of feature columns.

TYPE: int

arc_logs

Log features by original arc or boundary occurrence.

TYPE: tuple or None DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

initial_logs

Log features by original arc or boundary occurrence.

TYPE: tuple or None DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

final_logs

Log features by original arc or boundary occurrence.

TYPE: tuple or None DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

handler_name property

handler_name: str

Return the normal foreign handler name for this exact observation.

RETURNS DESCRIPTION
str

A canonical name derived from the original topology, words and feature data.

result_type property

result_type: TypeExpr

Return the fixed tensor type for the total and ordered moments.

RETURNS DESCRIPTION
TypeExpr

A log-weight tensor with the total followed by each moment.

FixedRelationFeatureMomentRequest didactic-model

FixedRelationFeatureMomentRequest(*, observation: FixedRelationFeatureObservation = field(opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, max_feature_cells: int)

Bases: QiecModel

Collect packed nonnegative feature moments for a fixed observation.

The observation owns the foreign handler identity. Work limits may change without changing that identity. A feature-cell budget separately bounds the product of feature width and sparse graph records.

PARAMETER DESCRIPTION
observation

The exact typed topology, words, and feature tables.

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

max_states

The reached-state budget for this fixed observation.

TYPE: int

max_work

The examined-arc budget for this fixed observation.

TYPE: int

max_feature_cells

The budget for chart cells. This counts one mass plus the feature extent, multiplied by original occurrences and productive chart states and arcs.

TYPE: int

handler_name property

handler_name: str

Return the requested observation's canonical foreign handler name.

RETURNS DESCRIPTION
str

The name the checked source declares for the observation.

result_type property

result_type: TypeExpr

Return the log tensor type of the requested feature moments.

RETURNS DESCRIPTION
TypeExpr

One log total and one log moment per feature.

plan

plan(parameters: RelationWeightBindings) -> Callable[[], Tensor]

Compile the bounded feature evaluator with original weight tensors.

PARAMETER DESCRIPTION
parameters

The live primitive scalar weights by original identity.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
callable

A reusable evaluator of the log total and moments.

RAISES DESCRIPTION
RelationLimitError

The fixed observation exceeds a declared resource budget.

Source code in src/quivers/qiec/relation_feature_moments.py
def plan(self, parameters: RelationWeightBindings) -> Callable[[], torch.Tensor]:
    """Compile the bounded feature evaluator with original weight tensors.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The live primitive scalar weights by original identity.

    Returns
    -------
    callable
        A reusable evaluator of the log total and moments.

    Raises
    ------
    RelationLimitError
        The fixed observation exceeds a declared resource budget.
    """
    return self._plan(parameters, max_closure_size=None)

FixedCyclicRelationFeatureMomentRequest adds an explicit per-component closure order to the same observation and chart budgets. It uses the same handler identity and returns the same unnormalized log-space observable. Its marked-occurrence calculation combines certified scalar prefix and suffix closures, including repeated visits. The component order includes auxiliary states needed to preserve parallel occurrences. Insufficient order, divergence, and an uncertifiable closure are reported by the scalar evaluator.

FixedCyclicRelationFeatureMomentRequest didactic-model

FixedCyclicRelationFeatureMomentRequest(*, request: FixedRelationFeatureMomentRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), max_closure_size: int)

Bases: QiecModel

Collect unnormalized nonnegative moments with certified scalar closure.

The original observation owns the same foreign name and result type in either execution mode. This request supplies the extra operation that a productive cyclic component requires.

PARAMETER DESCRIPTION
request

The observation and its fixed state, arc and feature-cell bounds.

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

max_closure_size

The maximum order of each productive scalar component closure.

TYPE: int

observation property

Return the unchanged typed observation.

RETURNS DESCRIPTION
FixedRelationFeatureObservation

The original topology, words and fixed feature increments.

handler_name property

handler_name: str

Return the canonical foreign handler of the original observation.

RETURNS DESCRIPTION
str

The checked handler name, independent of closure limits.

result_type property

result_type: TypeExpr

Return the unchanged closed log tensor result type.

RETURNS DESCRIPTION
TypeExpr

One log total followed by one unnormalized log moment per feature.

plan

plan(parameters: RelationWeightBindings) -> Callable[[], Tensor]

Bind live weights and prepare the certified cyclic feature query.

PARAMETER DESCRIPTION
parameters

The original live scalar weights.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
callable

The reusable result evaluator. Divergent or uncertifiable scalar closures report their failure at evaluation.

Source code in src/quivers/qiec/relation_feature_moments.py
def plan(self, parameters: RelationWeightBindings) -> Callable[[], torch.Tensor]:
    """Bind live weights and prepare the certified cyclic feature query.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The original live scalar weights.

    Returns
    -------
    callable
        The reusable result evaluator. Divergent or uncertifiable
        scalar closures report their failure at evaluation.
    """
    return self.request._plan(parameters, max_closure_size=self.max_closure_size)

FixedComposedArcFeatureMomentRequest uses a materialized composition and one log feature row per original arc of each operand. A product arc keeps the supplying operand and occurrence ID, including when two arcs share a weight. The epsilon filter contributes one accepting product path per compatible original path pair. A matched step has one edge for each primitive factor, so their two feature rows both enter the moment even when the shared word is erased. Boundary marks still contribute their weights. The request assigns increments only to operand arcs.

The feature-cell count is the feature extent plus one, times the sum of operand arc rows, materialized state, arc and boundary records, and active observation states and arcs. Limits on the product and any productive scalar closure also apply. The handler binds the ordered operands, outer observation, and original feature rows. Its result is the log total followed by unnormalized log feature moments.

FixedComposedArcFeatureMomentRequest didactic-model

FixedComposedArcFeatureMomentRequest(*, request: FixedComposedRelationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), feature_extent: int, left_arc_logs: _LogTable = field(opaque=True, extras=OPAQUE_BY_VALUE), right_arc_logs: _LogTable = field(opaque=True, extras=OPAQUE_BY_VALUE), max_feature_cells: int)

Bases: QiecModel

Collect original-arc features of compatible path pairs in composition.

A materialized epsilon-filtered product marks each edge by its supplying operand and original arc occurrence. Distinct arcs can share scalar weights. Even when the shared word is hidden, every compatible pair contributes its two paths' additive feature totals.

PARAMETER DESCRIPTION
request

The original ordered operands, outer words and product, query, and optional scalar closure limits. Execution is materialized.

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

feature_extent

The positive number of features for both operands.

TYPE: int

left_arc_logs

Log increments in original operand arc order. None is log zero.

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

right_arc_logs

Log increments in original operand arc order. None is log zero.

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

max_feature_cells

The feature-cell budget for operand rows, the materialized topology records, and the active observation chart.

TYPE: int

handler_name property

handler_name: str

Return the foreign name for the exact ordered composed observation.

RETURNS DESCRIPTION
str

The name binding the operands, outer words and original features.

result_type property

result_type: TypeExpr

Return the fixed shape of the composed log feature result.

RETURNS DESCRIPTION
TypeExpr

The log total followed by its unnormalized log feature moments.

plan

plan(parameters: RelationWeightBindings) -> Callable[[], Tensor]

Build an occurrence-tagged product and bind its original weights.

PARAMETER DESCRIPTION
parameters

The caller's original scalar tensor owners across both operands.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
callable

The reusable vector of unnormalized log statistics.

RAISES DESCRIPTION
RelationLimitError

Operand, output topology, or active chart cells exceed the limit.

Source code in src/quivers/qiec/relation_feature_moments.py
def plan(self, parameters: RelationWeightBindings) -> Callable[[], torch.Tensor]:
    """Build an occurrence-tagged product and bind its original weights.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The caller's original scalar tensor owners across both operands.

    Returns
    -------
    callable
        The reusable vector of unnormalized log statistics.

    Raises
    ------
    RelationLimitError
        Operand, output topology, or active chart cells exceed the limit.
    """
    request = self.request
    columns = self.feature_extent + 1
    left_size = len(self.left_arc_logs)
    operand_rows = left_size + len(self.right_arc_logs)
    if columns * operand_rows > self.max_feature_cells:
        raise RelationLimitError("operand feature cells exceed max_feature_cells")
    relation, origins = request.relation.bind(parameters)._materialize(
        max_states=request.max_states,
        max_work=request.max_work,
        capture_origins=True,
    )
    assert origins is not None
    topology = relation.topology
    rows = (
        operand_rows
        + topology.n_states
        + len(topology.arcs)
        + len(topology.initial)
        + len(topology.final)
    )
    if columns * rows > self.max_feature_cells:
        raise RelationLimitError(
            "materialized feature cells exceed max_feature_cells"
        )
    query = relation.query(
        request.words,
        max_states=request.max_states,
        max_work=request.max_work,
        max_closure_size=request.max_closure_size,
    )
    work = query.work
    if (
        columns * (rows + work.active_states + work.active_arcs)
        > self.max_feature_cells
    ):
        raise RelationLimitError(
            "composed observation feature cells exceed max_feature_cells"
        )
    anchor = relation._weights()
    left = _feature_tensor(self.left_arc_logs, self.feature_extent, anchor)
    right = _feature_tensor(self.right_arc_logs, self.feature_extent, anchor)
    assert left is not None and right is not None
    indices = torch.tensor(
        [index + side * left_size for side, index in origins],
        dtype=torch.long,
        device=anchor.device,
    )
    arcs = torch.cat((left, right)).index_select(0, indices)
    return partial(
        _moment_vector,
        query,
        arcs,
        None,
        None,
        allow_cyclic=request.max_closure_size is not None,
    )

String factor graphs

StringFactorGraphSpec records the nominal alphabet and optional observation of each variable, the sparse relations by name, and the ordered variable scope of each factor occurrence. A factor's scope must match the corresponding relation's tape order and types. Bind the record to a single parameter store to share a relation across repeated factor occurrences and to share stable weight identities across distinct relations. An entry can hold a primitive topology or a named RelationCascadeSpec. The graph checks each factor against the resulting cascade tape layout. It constructs each referenced derived relation once and shares that machine across all occurrences of its name. Tree, pruned, MAP, and EP requests use their state and work bounds for each cascade intermediate. Direct graph binding requires both limits when a used factor is derived.

StringFactorGraphSpec didactic-model

StringFactorGraphSpec(*, variables: tuple[tuple[str, str, int, tuple[int, ...] | None], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), relations: tuple[tuple[str, RationalRelationSpec | RelationCascadeSpec], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), factors: tuple[tuple[str, tuple[str, ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A checked string factor graph with named reusable relation specifications.

Factor records are ordered occurrences. Two factors can refer to the same relation name, which binds one runtime relation and shares its weight source. Distinct relations can also share stable parameter identities. The wire record contains these identities and topology. Runtime binding supplies the tensor values. A derived factor retains a checked sparse cascade and builds its intermediate relations under explicit construction limits.

PARAMETER DESCRIPTION
variables

The variable name, alphabet name, alphabet cardinality, and observed word or None for each variable.

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

relations

Distinct relation names and their sparse relation specifications.

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

factors

A relation name and its ordered variable scope for each factor occurrence. Each variable in the scope corresponds to one tape.

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

algebra property

algebra: ClaimSubject

Return the common checked algebra of the referenced relations.

RETURNS DESCRIPTION
ClaimSubject

The nominal identity of the graph's scalar algebra.

bind

bind(parameters: RelationWeightBindings, *, max_states: int | None = None, max_work: int | None = None) -> StringFactorGraph

Bind the graph's referenced relations to their live scalar leaves.

PARAMETER DESCRIPTION
parameters

The live scalar tensor for each used stable identity. All used tensors share one dtype and device, and distinct identities bind distinct tensor objects.

TYPE: RelationWeightBindings

max_states

State and work limits for each intermediate of a derived factor. Both are required when a used factor is derived.

TYPE: int or None DEFAULT: None

max_work

State and work limits for each intermediate of a derived factor. Both are required when a used factor is derived.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
StringFactorGraph

The typed graph with original tensor objects and reusable sparse relations.

RAISES DESCRIPTION
TypeError

If the parameter store or a required tensor is invalid.

ValueError

If a binding is missing, ambiguous, incompatible with the algebra, or inconsistent in dtype or device, or a derived construction has no explicit limits.

Source code in src/quivers/qiec/string_graphs.py
def bind(
    self,
    parameters: RelationWeightBindings,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
) -> StringFactorGraph:
    """Bind the graph's referenced relations to their live scalar leaves.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The live scalar tensor for each used stable identity. All
        used tensors share one dtype and device, and distinct
        identities bind distinct tensor objects.
    max_states, max_work : int or None
        State and work limits for each intermediate of a derived
        factor. Both are required when a used factor is derived.

    Returns
    -------
    StringFactorGraph
        The typed graph with original tensor objects and reusable
        sparse relations.

    Raises
    ------
    TypeError
        If the parameter store or a required tensor is invalid.
    ValueError
        If a binding is missing, ambiguous, incompatible with the
        algebra, or inconsistent in dtype or device, or a derived
        construction has no explicit limits.
    """
    relations = dict(self.relations)
    used = dict.fromkeys(name for name, _ in self.factors)
    identities = dict.fromkeys(
        parameter
        for name in used
        for parameter in _factor_parameters(relations[name])
    )
    _validate_limits(max_states, max_work)
    _weight_bindings(identities, parameters, description="string graph")
    bound = {}
    for name in used:
        spec = relations[name]
        if isinstance(spec, RationalRelationSpec):
            bound[name] = spec.bind(parameters)
        else:
            if max_states is None or max_work is None:
                raise ValueError(
                    "derived string graph factors require explicit construction limits"
                )
            bound[name] = spec.bind(
                parameters, max_states=max_states, max_work=max_work
            )
    return StringFactorGraph(
        self._variables,
        tuple(StringFactor(scope, bound[name]) for name, scope in self.factors),
    )

TreeStringGraphRequest stores a partition or a normalized word query with explicit construction limits. The checked handler includes the operation in its stable identity. A runtime provider compiles the query once and uses the live graph parameters on every invocation.

TreeStringGraphRequest didactic-model

TreeStringGraphRequest(*, graph: StringFactorGraphSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), variable: str, word: tuple[int, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), max_states: int, max_work: int, max_closure_size: int | None = None)

Bases: QiecModel

A bounded exact tree query over a serialized string factor graph.

A partition uses the graph's scalar algebra. Supplying a word selects its normalized log probability at the named variable. An empty tuple queries the empty word. The exact executor checks the forest topology and the sparse construction and closure limits when bound.

PARAMETER DESCRIPTION
graph

The checked graph, including any observed words.

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

variable

The root variable for the marginal schedule.

TYPE: str

word

The word whose normalized log probability is requested. None requests the full graph partition.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

max_states

The maximum states for each intermediate construction or query.

TYPE: int

max_work

The maximum candidate arc examinations for each construction or query.

TYPE: int

max_closure_size

The maximum productive closure component, or None to require an acyclic query.

TYPE: int or None DEFAULT: None

operation property

operation: str

Return the objective identified by this request.

RETURNS DESCRIPTION
str

Partition or normalized log probability.

result_type property

result_type: TypeExpr

Return the closed QIEC scalar type of the objective.

RETURNS DESCRIPTION
TypeExpr

LogWeight for log-domain results, or Real for a Markov partition.

bind

bind(parameters: RelationWeightBindings) -> Callable[[], Tensor]

Compile a reusable query over live parameters.

PARAMETER DESCRIPTION
parameters

The live scalar tensor for each parameter identity in the graph.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
Callable

A zero-argument objective that reads the original parameters.

RAISES DESCRIPTION
TypeError

If the live parameter binding is invalid.

ValueError

If the graph is cyclic or the construction exceeds a limit.

Source code in src/quivers/qiec/string_graphs.py
def bind(self, parameters: RelationWeightBindings) -> Callable[[], torch.Tensor]:
    """Compile a reusable query over live parameters.

    Parameters
    ----------
    parameters : RelationWeightBindings
        The live scalar tensor for each parameter identity in the graph.

    Returns
    -------
    Callable
        A zero-argument objective that reads the original parameters.

    Raises
    ------
    TypeError
        If the live parameter binding is invalid.
    ValueError
        If the graph is cyclic or the construction exceeds a limit.
    """
    graph = self.graph.bind(
        parameters, max_states=self.max_states, max_work=self.max_work
    )
    marginal = graph.tree_marginal(
        self.variable,
        max_states=self.max_states,
        max_work=self.max_work,
        max_closure_size=self.max_closure_size,
    )
    word = self.word
    if word is None:
        return marginal.partition
    return marginal.query(word)

tree_string_graph_handler

tree_string_graph_handler(module: str, name: str, request: TreeStringGraphRequest) -> HandlerDef

Declare a linear unit-argument handler for a checked graph query.

The stable identity includes the graph query's objective. A log partition and normalized log probability have distinct handler identities while inhabiting the same LogWeight result type.

PARAMETER DESCRIPTION
module

The checked module name.

TYPE: str

name

The handler name in the module.

TYPE: str

request

The operation and result type to serve.

TYPE: TreeStringGraphRequest

RETURNS DESCRIPTION
HandlerDef

The checked foreign Compute declaration.

RAISES DESCRIPTION
ValueError

If the module or handler name is empty.

Source code in src/quivers/qiec/string_graph_runtime.py
def tree_string_graph_handler(
    module: str, name: str, request: TreeStringGraphRequest
) -> HandlerDef:
    """Declare a linear unit-argument handler for a checked graph query.

    The stable identity includes the graph query's objective. A log
    partition and normalized log probability have distinct handler
    identities while inhabiting the same LogWeight result type.

    Parameters
    ----------
    module : str
        The checked module name.
    name : str
        The handler name in the module.
    request : TreeStringGraphRequest
        The operation and result type to serve.

    Returns
    -------
    HandlerDef
        The checked foreign Compute declaration.

    Raises
    ------
    ValueError
        If the module or handler name is empty.
    """
    if not module or not name:
        raise ValueError(
            "a tree string graph handler requires module and handler names"
        )
    return _tree_string_graph_handler(
        module, name, request.operation, request.result_type
    )

TreeStringGraphRuntimeProvider

TreeStringGraphRuntimeProvider(request: TreeStringGraphRequest, parameters: RelationWeightBindings, *, handler_name: str)

Serve an exact graph objective through its checked Compute declaration.

PARAMETER DESCRIPTION
request

The graph, query objective, and resource limits.

TYPE: TreeStringGraphRequest

parameters

The caller's original scalar leaves supplying the graph weights.

TYPE: RelationWeightBindings

handler_name

The name of the exact handler declared in the checked module.

TYPE: str

Source code in src/quivers/qiec/string_graph_runtime.py
def __init__(
    self,
    request: TreeStringGraphRequest,
    parameters: RelationWeightBindings,
    *,
    handler_name: str,
) -> None:
    if not isinstance(handler_name, str) or not handler_name:
        raise ValueError("a tree string graph provider requires a handler name")
    self._request = request
    self._handler_name = handler_name
    self._score = request.bind(parameters)

for_score classmethod

for_score(name: str, request: TreeStringGraphRequest, parameters: RelationWeightBindings) -> TreeStringGraphRuntimeProvider

Bind the request to a named QVR string graph score.

PARAMETER DESCRIPTION
name

The name declared in QVR source.

TYPE: str

request

The checked graph objective.

TYPE: TreeStringGraphRequest

parameters

The original scalar tensors indexed by parameter identity.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
TreeStringGraphRuntimeProvider

The provider for the source-generated handler.

RAISES DESCRIPTION
ValueError

If the score name is empty or the request cannot be bound.

Source code in src/quivers/qiec/string_graph_runtime.py
@classmethod
def for_score(
    cls,
    name: str,
    request: TreeStringGraphRequest,
    parameters: RelationWeightBindings,
) -> TreeStringGraphRuntimeProvider:
    """Bind the request to a named QVR string graph score.

    Parameters
    ----------
    name
        The name declared in QVR source.
    request
        The checked graph objective.
    parameters
        The original scalar tensors indexed by parameter identity.

    Returns
    -------
    TreeStringGraphRuntimeProvider
        The provider for the source-generated handler.

    Raises
    ------
    ValueError
        If the score name is empty or the request cannot be bound.
    """
    if not isinstance(name, str) or not name:
        raise ValueError("a source graph score requires a name")
    return cls(
        request, parameters, handler_name=_string_graph_score_handler_name(name)
    )

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Install the provider for the exact declared operation.

PARAMETER DESCRIPTION
module

The checked module declaring the foreign handler.

TYPE: QiecModule

attachments

The invocation's runtime handler table.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
TypeError

If the checked handler does not declare this objective and type.

Source code in src/quivers/qiec/string_graph_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Install the provider for the exact declared operation.

    Parameters
    ----------
    module : QiecModule
        The checked module declaring the foreign handler.
    attachments : RuntimeAttachments
        The invocation's runtime handler table.

    Raises
    ------
    TypeError
        If the checked handler does not declare this objective and type.
    """
    expected = tree_string_graph_handler(
        module.module, self._handler_name, self._request
    )
    if expected not in module.handlers:
        expected = _tree_string_graph_handler(
            module.module,
            self._handler_name,
            self._request.operation,
            self._request.result_type,
            graph=self._request.graph,
        )
        if expected not in module.handlers:
            raise TypeError(
                f"incompatible tree string graph handler {self._handler_name!r} "
                "for the supplied objective, result type, or authored graph"
            )
    validator = self.validator_for(self._request.result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=expected.effect,
        result_validator=validator,
        answer_type=expected.output_type,
        key=self._handler_name,
    )
    attachments.bind_handler(runtime.with_(definition=expected))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Validate torch scalars inhabiting the declared result type.

PARAMETER DESCRIPTION
type_

The closed QIEC type requested by the runtime.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The scalar predicate for this result type, or None for other types.

Source code in src/quivers/qiec/string_graph_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Validate torch scalars inhabiting the declared result type.

    Parameters
    ----------
    type_ : TypeExpr
        The closed QIEC type requested by the runtime.

    Returns
    -------
    RuntimeValidator or None
        The scalar predicate for this result type, or None for other types.
    """
    if type_ != self._request.result_type:
        return None
    core = CoreRuntimeProvider().validator_for(type_)

    def validate(value: object) -> bool:
        """Check a host value against the expected scalar carrier.

        Parameters
        ----------
        value
            The host value.

        Returns
        -------
        bool
            Whether the value inhabits the requested type.
        """
        if core is not None and core(value):
            return True
        if not isinstance(value, torch.Tensor) or (
            value.shape != () or not value.is_floating_point()
        ):
            return False
        return bool(
            LOG_PROB.contains(value)
            if type_ == LOG_WEIGHT
            else torch.isfinite(value)
        )

    return validate

QVR can name these queries as ordinary scalar computations.

define log_evidence : LogWeight = tree_partition()
define reading : LogWeight = tree_log_prob()

Bind each declaration with TreeStringGraphRuntimeProvider.for_score. A partition uses Real for a Markov graph or LogWeight for a LogProb graph. A word query has type LogWeight and sums out the other variables before normalizing. Attachments serve these computations on the checked reference machine, with foreign-handler diagnostics for targets that cannot lower them.

Checked pruned string beliefs

PrunedStringGraphRequest uses that same graph with a PrunedStringBPConfig and selects one variable to report. The output coordinates are the variable's declared candidate words in order. An observed variable has one coordinate for its fixed word. The checked pruned_string_graph_handler binds the graph, the ordered candidate pools, and the variable. The same handler can run with a different beam, damping schedule, or resource limits. The provider retains the compiled factor queries and reads the original weights on every invocation.

An ordinary QVR computation can declare a foreign Compute[Unit, A] handler using request.handler_name and the closed report type A, with apply resumes 1. The provider checks the digest of the original graph, ordered supports, and selected variable, together with the full typed Compute declaration. Programmatically created checked handlers continue to use pruned_string_graph_handler.

The foreign computation returns a checked product with these fields in order.

  1. Status and diagnostic text. Status is converged, limit for exhausted sweeps, empty_support for a support conflict, or resource_limit for a factor table or observation construction limit.
  2. Completed sweep count, message residual, and a Boolean truncation flag. The residual is \(-1\) when undefined.
  3. The selected variable's log belief tensor. An unavailable belief has log zero in every coordinate.
  4. A Boolean indicating whether a complete proposal table is available, and the table's log masses. Each row gives full, retained, and omitted mass before renormalization. Rows follow the original factor and tape order. Unavailable rows contain log zero.

Convergence concerns the pruned update. The belief remains an approximation over the declared finite pool. Native targets that require foreign calls to be discharged report the checked pruned handler as an obstacle.

PrunedStringGraphRequest didactic-model

PrunedStringGraphRequest(*, graph: StringFactorGraphSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), config: PrunedStringBPConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), variable: str)

Bases: QiecModel

A bounded approximate query over one checked graph and finite support.

The same authored graph can use other solvers with their own checked capabilities. The ordered candidate pools and requested variable identify this foreign declaration. Operational settings can change within the same declaration.

PARAMETER DESCRIPTION
graph

The original typed factor declarations and parameter owners.

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

config

The ordered supports and existing beam inference settings.

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

variable

The variable whose approximate belief the query returns.

TYPE: str

candidate_words property

candidate_words: tuple[tuple[int, ...], ...]

Return the query variable's checked output coordinate order.

RETURNS DESCRIPTION
tuple of tuples of int

Its ordered candidates, or the observed singleton.

handler_name property

handler_name: str

Return the declared foreign name bound to the graph and candidate axes.

RETURNS DESCRIPTION
str

A name derived from the exact graph, ordered supports, and query variable.

result_type property

result_type: TypeExpr

Return the typed product of measured approximate beliefs and diagnostics.

RETURNS DESCRIPTION
TypeExpr

Status, reason, sweeps, residual, truncation, log belief, proposal presence, and factor-tape log masses in that order.

PrunedStringGraphRuntimeProvider

PrunedStringGraphRuntimeProvider(request: PrunedStringGraphRequest, parameters: RelationWeightBindings)

Serve one checked bounded approximate string belief query.

PARAMETER DESCRIPTION
request

The authored graph, ordered candidates, selected variable and limits.

TYPE: PrunedStringGraphRequest

parameters

Original live scalar leaves and any permitted Markov complements.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/pruned_string_graph_runtime.py
def __init__(
    self,
    request: PrunedStringGraphRequest,
    parameters: RelationWeightBindings,
) -> None:
    self._request = request
    self._resource_failure: str | None = None
    try:
        self._plan = request.config._plan(request.graph, parameters)
    except RelationLimitError as error:
        self._resource_failure = str(error)
        self._plan = None

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach the evaluator to its exact typed foreign declaration.

PARAMETER DESCRIPTION
module

The module declaring the pruned graph handler.

TYPE: QiecModule

attachments

The invocation's runtime handler table.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
TypeError

The expected graph, supports, or linear Compute contract is absent.

Source code in src/quivers/qiec/pruned_string_graph_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach the evaluator to its exact typed foreign declaration.

    Parameters
    ----------
    module : QiecModule
        The module declaring the pruned graph handler.
    attachments : RuntimeAttachments
        The invocation's runtime handler table.

    Raises
    ------
    TypeError
        The expected graph, supports, or linear Compute contract is absent.
    """
    expected = pruned_string_graph_handler(module.module, self._request)
    if expected not in module.handlers:
        try:
            expected = _fixed_compute_definition(
                module, expected.name, expected.output_type
            )
        except (TypeError, ValueError) as error:
            raise TypeError(
                "incompatible pruned string handler for the graph, supports, or result type"
            ) from error
    validator = self.validator_for(self._request.result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=expected.effect,
        result_validator=validator,
        answer_type=expected.output_type,
        key=expected.name,
    )
    attachments.bind_handler(runtime.with_(definition=expected))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Return the validator for this query's typed report.

PARAMETER DESCRIPTION
type_

The closed type requested by the reference machine.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The canonical product predicate when the type matches.

Source code in src/quivers/qiec/pruned_string_graph_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Return the validator for this query's typed report.

    Parameters
    ----------
    type_ : TypeExpr
        The closed type requested by the reference machine.

    Returns
    -------
    RuntimeValidator or None
        The canonical product predicate when the type matches.
    """
    if type_ != self._request.result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

Checked true marginal error for pruned string beliefs

CertifiedPrunedStringGraphRequest takes an existing pruned graph request and an exact rational total variation goal in \([0,1]\). The foreign name binds the graph, ordered candidate axes, requested variable, beam, sweep policy, damping, and accuracy goal. The proof resource limits can tighten under the same declaration.

The verifier uses the same live binary64 Markov slot snapshot as the pruned schedule. On an admitted finite model it compares the exact normalization of the selected returned log row with the true marginal on that variable's effective finite support. The core verifier derives the bound from positive acyclic factor weights and bounded singleton Gibbs comparison. The derivative of the returned log row follows its executed pruned updates.

The report starts with the certificate status, diagnostic, and a Boolean for availability of the original pruned report. The fourth through eleventh fields give that report in its original order, including the executed sweep status, truncation flag, log probabilities, and proposal masses. The last fields are String[Fin 2, Fin 2] and Int[Fin 5]. The two witness rows give the selected marginal's total variation bound and the maximum conditional influence row sum. Each row contains its hexadecimal numerator and denominator as strings. The five counters give conditional cells, compared boundary pairs, exact arithmetic work, the largest unreduced intermediate bit charge, and directed Decimal work. Exact arithmetic includes the comparison with the requested goal.

certified means the verified bound meets the requested goal. tolerance_unmet still returns the original pruned report and a valid upper bound, above the requested goal. A schedule can return limit and meet the independent accuracy goal. Graph support or contraction failure, unavailable schedule beliefs, unsupported algebra or closure or precision, and resource limits report their own conditions. Unavailable reports have an absent pruned report, empty witness strings, and zero counters. A target without the foreign handler reports the native capability requirement.

CertifiedPrunedStringGraphRequest didactic-model

CertifiedPrunedStringGraphRequest(*, query: PrunedStringGraphRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), total_variation_tolerance: tuple[int, int] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_conditional_cells: int, max_exact_work: int, max_exact_bits: int, decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int)

Bases: QiecModel

Request a true marginal total variation bound on checked pruned beliefs.

PARAMETER DESCRIPTION
query

The original checked graph, word axes, variable, and pruned schedule.

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

total_variation_tolerance

Exact nonnegative numerator and positive denominator of the requested total variation limit, at most one.

TYPE: tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_conditional_cells

Cumulative conditional probability entries over effective blankets.

TYPE: int

max_exact_work

Verified rational arithmetic budget including the final goal check.

TYPE: int

max_exact_bits

Verified rational arithmetic budget including the final goal check.

TYPE: int

decimal_precision

Directed exponential resource limits for the returned log rows.

TYPE: int

max_decimal_exponent

Directed exponential resource limits for the returned log rows.

TYPE: int

max_decimal_work

Directed exponential resource limits for the returned log rows.

TYPE: int

handler_name property

handler_name: str

Bind the exact graph, schedule, and metric goal to the handler.

RETURNS DESCRIPTION
str

A foreign handler name with a stable certificate identity.

result_type property

result_type: TypeExpr

Give the typed schedule and rational error report.

RETURNS DESCRIPTION
TypeExpr

Certificate status, diagnostic, schedule availability, pruned report, exact rational bound and influence, and verifier work.

CertifiedPrunedStringGraphRuntimeProvider

CertifiedPrunedStringGraphRuntimeProvider(request: CertifiedPrunedStringGraphRequest, parameters: RelationWeightBindings)

Return the existing pruned report and verified true marginal error.

PARAMETER DESCRIPTION
request

The checked finite query, selected marginal, and accuracy target.

TYPE: CertifiedPrunedStringGraphRequest

parameters

The original live owners used for the pruned run and certificate.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/pruned_belief_certificate.py
def __init__(
    self,
    request: CertifiedPrunedStringGraphRequest,
    parameters: RelationWeightBindings,
) -> None:
    self._request = request
    self._parameters = parameters
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach only to the declared graph, schedule, and requested goal.

PARAMETER DESCRIPTION
module

The module containing the matching foreign Compute.

TYPE: QiecModule

attachments

The current invocation's handler table.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

The named handler is absent or ambiguous.

TypeError

The declaration has an incompatible Compute contract.

Source code in src/quivers/qiec/pruned_belief_certificate.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach only to the declared graph, schedule, and requested goal.

    Parameters
    ----------
    module : QiecModule
        The module containing the matching foreign Compute.
    attachments : RuntimeAttachments
        The current invocation's handler table.

    Raises
    ------
    ValueError
        The named handler is absent or ambiguous.
    TypeError
        The declaration has an incompatible Compute contract.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Supply the exact checked certificate carrier validator.

PARAMETER DESCRIPTION
type_

The runtime carrier type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The canonical validator if the requested type matches.

Source code in src/quivers/qiec/pruned_belief_certificate.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Supply the exact checked certificate carrier validator.

    Parameters
    ----------
    type_ : TypeExpr
        The runtime carrier type.

    Returns
    -------
    RuntimeValidator or None
        The canonical validator if the requested type matches.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

pruned_string_graph_handler

pruned_string_graph_handler(module: str, request: PrunedStringGraphRequest) -> HandlerDef

Declare the checked linear foreign Compute capability for a pruned query.

PARAMETER DESCRIPTION
module

The checked module name.

TYPE: str

request

The graph, candidate axes and typed result.

TYPE: PrunedStringGraphRequest

RETURNS DESCRIPTION
HandlerDef

The checked declaration with the canonical observation name.

RAISES DESCRIPTION
ValueError

The module name is empty.

Source code in src/quivers/qiec/pruned_string_graph_runtime.py
def pruned_string_graph_handler(
    module: str, request: PrunedStringGraphRequest
) -> HandlerDef:
    """Declare the checked linear foreign Compute capability for a pruned query.

    Parameters
    ----------
    module : str
        The checked module name.
    request : PrunedStringGraphRequest
        The graph, candidate axes and typed result.

    Returns
    -------
    HandlerDef
        The checked declaration with the canonical observation name.

    Raises
    ------
    ValueError
        The module name is empty.
    """
    if not module:
        raise ValueError("a pruned string graph handler requires a module name")
    return _tree_string_graph_handler(
        module,
        request.handler_name,
        request.config.objective,
        request.result_type,
        graph=request.graph,
    )

String solver configurations

Encode a StringFactorGraphSpec and its solver settings separately. A JointAlignmentMapConfig reconstructs the exact acyclic local decoder with the saved iteration, feature, state, and work limits. Its rational step is stored as two integers. Local maximization adds the original path scores, including boundary marks. The dual bound applies to the best joint alignment and words, and a certificate requires agreement on the complete words. An iteration limit may return a feasible assignment and bound without a certificate. The solver verifies original trace scores, local optima, and cancellation of the saved feature multipliers before returning a certified interval. General joint string MAP can be undecidable for cyclic multi-tape factors, as the reduction from Post's correspondence problem shows. See §2.5 of Peng, Cotterell, and Eisner (2015).

The local max_work is a cap per forward decoder and per verification scan. Each independently verified local witness requires two scans of the same candidate arc set, at most twice max_work, and a separate check of its original trace. The result reports these counts separately.

The default step_ratio=(p, q) uses a harmonic step of \(p/(qt)\) at iteration \(t\). An explicit step_ratio=("constant", p, q) uses \(p/q\) at each update. For each feature, every copy subtracts its count from the mean count and multiplies by the same rational step. The increments sum to zero, so both schedules preserve the dual bound. The independent certificate verifies the local optima and the complete-word agreement under the actual final multipliers.

JointAlignmentMapGapConfig pairs the ordinary solver settings with one or both rational gap targets. The executor checks them against the feasible score and dual bound computed from the original live model. An unsupported relative guarantee or a missing feasible assignment cannot satisfy the target. A gap stop reports that the objective bound was established. The optimal status and agreement certificate retain their stricter condition. The original settings record keeps its wire representation.

JointAlignmentMapFeatureBudgetConfig wraps the ordinary or gap policy with limits on cumulative feature work and peak charged feature cells. The work includes ranked windows, active-prefix probes, direct update counts, and independent witness counts. The cells measure feature workspace, including retained symbols. Local graph limits still apply separately. The two limits use the existing host meter for singleton and grouped MAP. If that meter refuses an operation, native execution returns resource_limit with absent assignment and certificate evidence. The optional limits travel under an additive QIEC wire tag. The previous solver and request records retain their bytes and handler names.

JointAlignmentMapDecomposition wraps a portable alignment search policy with a partition into singleton and paired factor occurrences. A pair shares exactly one tape variable and has explicit product limits. The same authored graph supplies both the ordinary and grouped solver. The grouped certificate follows the partition order. Feasible paths expanded from the certificate or lower-bound witness follow original factor order and keep the original boundary and arc identities.

A RegularStringEPConfig uses the same factor declaration for approximate sum-product. Its settings record finite regular reference languages, ordered candidate n-grams, penalty, synchronous scheduling limits, and projection tolerances. Reference weights enter the model for this run. A reference that gives unit weight to each supported word only restricts support. The result distinguishes local projection failure from an outer sweep limit. Relation resource failures are reported by the underlying operation. Message stabilization alone does not certify exact marginals.

RegularStringEPPolicy wraps the existing configuration with a choice of fixed-Lipschitz or adaptive-backtracking steps and optional finite initial sites. Each site identifies its factor occurrence, variable, and ordered candidate features. A different nominal tape or reordered site refuses before building the graph. The default initializes unit sites. The detached gradient policy refuses requests for finite-unrolled and converged-solution derivatives. A request for a certified global posterior error also refuses. The existing config and request retain their wire bytes.

Both solvers bind the original weight identities at invocation. The wire records carry neither a previous fitted belief nor an optimum certificate.

A PrunedStringBPConfig records ordered finite word supports, a positive beam width, damping, and construction and sweep limits. Bind it to the same graph specification used for exact tree inference. The executor derives convergence, support failures, and the pre-normalization message masses from the live weights. These observations belong to the returned approximate result.

JointAlignmentMapConfig didactic-model

JointAlignmentMapConfig(*, max_iterations: int, max_ngram_order: int, max_features: int, max_states: int, max_work: int, step_ratio: tuple[int, int] | tuple[Literal['constant'], int, int] = field(default=(1, 1), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Configure exact local decoders for joint alignment and word MAP.

The record travels separately from the factor graph and its parameters. Its decoder capability requires acyclic productive LogProb factors. Only an execution whose exact local paths agree on complete words can return an optimum certificate. A finite budget can end in disagreement.

PARAMETER DESCRIPTION
max_iterations

Positive bound on updates of the dual variables.

TYPE: int

max_ngram_order

Highest order of a distinguishing feature.

TYPE: int

max_features

Maximum number of active variable-feature pairs.

TYPE: int

max_states

Configuration limit per exact factor decode.

TYPE: int

max_work

Transition examinations allowed per exact factor decode or individual verification scan. The independent final check has two such scans and a separate original trace check.

TYPE: int

step_ratio

A numerator and denominator gives the harmonic step scale. Prefix the ratio with "constant" to apply the same positive step each iteration.

TYPE: tuple DEFAULT: field(default=(1, 1), opaque=True, extras=OPAQUE_BY_VALUE)

objective property

objective: Literal['joint_alignment_map']

Identify the objective selected by this record.

RETURNS DESCRIPTION
Literal['joint_alignment_map']

Joint maximization over words and local paths.

solve

solve(model: StringFactorGraphSpec, parameters: Mapping[ParameterId, Tensor], *, absolute_gap: Fraction | int | None = None, relative_gap: Fraction | int | None = None, max_feature_work: int | None = None, max_feature_cells: int | None = None) -> StringAlignmentMapResult

Run exact local decoding on a bound graph and return its search result.

PARAMETER DESCRIPTION
model

The checked string factors, variables, and observations.

TYPE: StringFactorGraphSpec

parameters

The original scalar tensors used by the model.

TYPE: Mapping of ParameterId to torch.Tensor

absolute_gap

Optional exact objective gap targets. Serialize these using JointAlignmentMapGapConfig when they form part of the policy.

TYPE: Fraction or int or None DEFAULT: None

relative_gap

Optional exact objective gap targets. Serialize these using JointAlignmentMapGapConfig when they form part of the policy.

TYPE: Fraction or int or None DEFAULT: None

max_feature_work

Optional cumulative feature work and peak feature workspace limits. JointAlignmentMapFeatureBudgetConfig carries them in a portable policy.

TYPE: int or None DEFAULT: None

max_feature_cells

Optional cumulative feature work and peak feature workspace limits. JointAlignmentMapFeatureBudgetConfig carries them in a portable policy.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
StringAlignmentMapResult

The feasible assignment, bound, and certificate when available.

Source code in src/quivers/qiec/string_solvers.py
def solve(
    self,
    model: StringFactorGraphSpec,
    parameters: Mapping[ParameterId, torch.Tensor],
    *,
    absolute_gap: Fraction | int | None = None,
    relative_gap: Fraction | int | None = None,
    max_feature_work: int | None = None,
    max_feature_cells: int | None = None,
) -> StringAlignmentMapResult:
    """Run exact local decoding on a bound graph and return its search result.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The checked string factors, variables, and observations.
    parameters : Mapping of ParameterId to torch.Tensor
        The original scalar tensors used by the model.
    absolute_gap, relative_gap : Fraction or int or None
        Optional exact objective gap targets. Serialize these using
        `JointAlignmentMapGapConfig` when they form part of the policy.
    max_feature_work, max_feature_cells : int or None
        Optional cumulative feature work and peak feature workspace
        limits. `JointAlignmentMapFeatureBudgetConfig` carries them
        in a portable policy.

    Returns
    -------
    StringAlignmentMapResult
        The feasible assignment, bound, and certificate when available.
    """
    schedule, numerator, denominator = self._step_spec()
    return dual_alignment_map(
        model.bind(parameters, max_states=self.max_states, max_work=self.max_work),
        max_iterations=self.max_iterations,
        max_ngram_order=self.max_ngram_order,
        max_features=self.max_features,
        max_states=self.max_states,
        max_work=self.max_work,
        step_size=Fraction(numerator, denominator),
        step_schedule=schedule,
        absolute_gap=absolute_gap,
        relative_gap=relative_gap,
        max_feature_work=max_feature_work,
        max_feature_cells=max_feature_cells,
    )

JointAlignmentMapGapConfig didactic-model

JointAlignmentMapGapConfig(*, solver: JointAlignmentMapConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), absolute_gap_ratio: tuple[int, int] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), relative_gap_ratio: tuple[int, int] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Configure proved objective-gap stopping for exact local alignment MAP.

The plain MAP configuration retains its original encoding. This record adds one or both exact tolerances alongside it. Reaching the requested bounds can end a disagreeing run without producing an agreement certificate.

PARAMETER DESCRIPTION
solver

The exact local decoder, feature schedule and resource settings.

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

absolute_gap_ratio

Nonnegative numerator and positive denominator for absolute suboptimality. None specifies no absolute constraint.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

relative_gap_ratio

Nonnegative ratio for suboptimality relative to the optimal objective's magnitude. None specifies no relative constraint.

TYPE: tuple of int or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

objective property

objective: Literal['joint_alignment_map']

Identify the unchanged objective of the exact local solver.

RETURNS DESCRIPTION
Literal['joint_alignment_map']

Joint maximization over words and local paths.

solve

solve(model: StringFactorGraphSpec, parameters: Mapping[ParameterId, Tensor]) -> StringAlignmentMapResult

Run alignment MAP until agreement, the proved target, or a limit.

PARAMETER DESCRIPTION
model

The checked graph, separate from the solver configuration.

TYPE: StringFactorGraphSpec

parameters

Original scalar parameters used by the graph's factors.

TYPE: Mapping of ParameterId to torch.Tensor

RETURNS DESCRIPTION
StringAlignmentMapResult

The feasible assignment and upper bound, whether the gap target was established, and any agreement certificate.

Source code in src/quivers/qiec/string_solvers.py
def solve(
    self,
    model: StringFactorGraphSpec,
    parameters: Mapping[ParameterId, torch.Tensor],
) -> StringAlignmentMapResult:
    """Run alignment MAP until agreement, the proved target, or a limit.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The checked graph, separate from the solver configuration.
    parameters : Mapping of ParameterId to torch.Tensor
        Original scalar parameters used by the graph's factors.

    Returns
    -------
    StringAlignmentMapResult
        The feasible assignment and upper bound, whether the gap
        target was established, and any agreement certificate.
    """
    absolute, relative = self._targets()
    return self.solver.solve(
        model, parameters, absolute_gap=absolute, relative_gap=relative
    )

JointAlignmentMapFeatureBudgetConfig didactic-model

JointAlignmentMapFeatureBudgetConfig(*, solver: JointAlignmentMapConfig | JointAlignmentMapGapConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), max_feature_work: int | None = None, max_feature_cells: int | None = None)

Bases: QiecModel

Carry the adaptive feature limits with an exact alignment MAP policy.

PARAMETER DESCRIPTION
solver

The existing exact local policy and optional gap targets.

TYPE: JointAlignmentMapConfig or JointAlignmentMapGapConfig DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_feature_work

Cumulative candidate windows, prefix probes, direct count symbol visits and independent witness symbol visits. Zero is a valid cap.

TYPE: int or None DEFAULT: None

max_feature_cells

Peak charged cells for feature workspace, including retained feature symbols. This limit has the host meter's scope.

TYPE: int or None DEFAULT: None

objective property

objective: Literal['joint_alignment_map']

Identify the unchanged objective selected by the enclosed policy.

RETURNS DESCRIPTION
Literal['joint_alignment_map']

Joint maximization over words and original paths.

solve

solve(model: StringFactorGraphSpec, parameters: Mapping[ParameterId, Tensor]) -> StringAlignmentMapResult

Run the exact solver with the shared feature search and witness meter.

PARAMETER DESCRIPTION
model

The checked string factors, variables, and observations.

TYPE: StringFactorGraphSpec

parameters

Original live scalar weights for the declared owners.

TYPE: Mapping of ParameterId to torch.Tensor

RETURNS DESCRIPTION
StringAlignmentMapResult

The ordinary exact-scope report when the requested limits admit it.

Source code in src/quivers/qiec/string_solvers.py
def solve(
    self,
    model: StringFactorGraphSpec,
    parameters: Mapping[ParameterId, torch.Tensor],
) -> StringAlignmentMapResult:
    """Run the exact solver with the shared feature search and witness meter.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The checked string factors, variables, and observations.
    parameters : Mapping of ParameterId to torch.Tensor
        Original live scalar weights for the declared owners.

    Returns
    -------
    StringAlignmentMapResult
        The ordinary exact-scope report when the requested limits admit it.
    """
    solver, absolute, relative = _alignment_gap_settings(self.solver)
    return solver.solve(
        model,
        parameters,
        absolute_gap=absolute,
        relative_gap=relative,
        max_feature_work=self.max_feature_work,
        max_feature_cells=self.max_feature_cells,
    )

JointAlignmentMapDecomposition didactic-model

JointAlignmentMapDecomposition(*, solver: JointAlignmentMapConfig | JointAlignmentMapGapConfig | JointAlignmentMapFeatureBudgetConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), groups: tuple[tuple[int, ...], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), max_group_states: int, max_group_work: int)

Bases: QiecModel

Configure exact singleton and one-shared-tape paired subproblems.

Factor indices refer to occurrences in the separate checked graph. Equal factor definitions can appear at different positions. The group order specifies multiplier scope order. Returned original traces follow the graph's original factor order.

PARAMETER DESCRIPTION
solver

The search, local bounds, and optional gap and feature limits.

TYPE: JointAlignmentMapConfig, JointAlignmentMapGapConfig, or JointAlignmentMapFeatureBudgetConfig DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

groups

An ordered partition of all original factor occurrence indices into singletons and pairs sharing exactly one tape variable.

TYPE: tuple of tuples of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_group_states

Maximum states constructed by each filtered pair join.

TYPE: int

max_group_work

Maximum label probes and arcs constructed by each pair join.

TYPE: int

objective property

objective: Literal['joint_alignment_map']

Identify the exact objective shared with the singleton solver.

RETURNS DESCRIPTION
Literal['joint_alignment_map']

Joint maximization over full words and original local paths.

solve

solve(model: StringFactorGraphSpec, parameters: Mapping[ParameterId, Tensor]) -> PairedAlignmentMapResult

Bind the graph and run the verified grouped local search.

PARAMETER DESCRIPTION
model

The unchanged checked graph and original occurrence order.

TYPE: StringFactorGraphSpec

parameters

Original live LogProb scalar owners for the factor graph.

TYPE: Mapping of ParameterId to torch.Tensor

RETURNS DESCRIPTION
PairedAlignmentMapResult

Grouped local evidence and feasible traces in original factor order.

Source code in src/quivers/qiec/string_solvers.py
def solve(
    self,
    model: StringFactorGraphSpec,
    parameters: Mapping[ParameterId, torch.Tensor],
) -> PairedAlignmentMapResult:
    """Bind the graph and run the verified grouped local search.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The unchanged checked graph and original occurrence order.
    parameters : Mapping of ParameterId to torch.Tensor
        Original live LogProb scalar owners for the factor graph.

    Returns
    -------
    PairedAlignmentMapResult
        Grouped local evidence and feasible traces in original factor order.
    """
    policy = self.solver
    work = cells = None
    if isinstance(policy, JointAlignmentMapFeatureBudgetConfig):
        work, cells = policy.max_feature_work, policy.max_feature_cells
        policy = policy.solver
    solver, absolute, relative = _alignment_gap_settings(policy)
    schedule, numerator, denominator = solver._step_spec()
    return paired_dual_alignment_map(
        model.bind(
            parameters, max_states=solver.max_states, max_work=solver.max_work
        ),
        groups=self.groups,
        max_group_states=self.max_group_states,
        max_group_work=self.max_group_work,
        max_iterations=solver.max_iterations,
        max_ngram_order=solver.max_ngram_order,
        max_features=solver.max_features,
        max_states=solver.max_states,
        max_work=solver.max_work,
        step_size=Fraction(numerator, denominator),
        step_schedule=schedule,
        absolute_gap=absolute,
        relative_gap=relative,
        max_feature_work=work,
        max_feature_cells=cells,
    )

Checked native joint alignment MAP

JointAlignmentMapRequest combines a checked string factor graph with a portable singleton exact-local solver and optional gap or feature limits. Compile the ordinary QVR graph to get its specification. Declare a total foreign Compute[Unit, A] handler using the request's handler name and result carrier, then bind a JointAlignmentMapRuntimeProvider to the original live scalar owners. The handler identity binds the ordered graph, nominal tapes and observations, parameter identities, complete solver record, and word capacity. The solver reads the current weights on each invocation.

For \(V\) declared variables and word capacity \(K\), the report follows this order.

Field QVR carrier
Search status and diagnostic String * String
Feasible assignment availability Bool
Word tokens in variable declaration order Int[Fin V, Fin K]
Word lengths in the same order Int[Fin V]
Feasible score, dual upper bound, absolute gap, relative gap String[Fin 4, Fin 2]
Agreement certificate and attained gap target Bool * Bool
Iterations, peak local states, local arc examinations, peak verification states, verification arc examinations Int[Fin 5]

Words use -1 suffix padding. An available empty word has length zero. An absent assignment uses length -1 and a false availability flag. A run without a feasible assignment may still report an exact dual upper bound.

Each available rational has its signed hexadecimal numerator and positive denominator. Their exact integers can exceed both the floating-point mantissa and the QVR Int range. An unavailable ratio has two empty strings. A request admits \(V(K+1)\) assignment cells before any output allocation. Each report checks the actual word lengths, symbol and count ranges, and total integer bit count before formatting ratios or packing observed words. A report_limit returns absent evidence when the encoding cannot represent the result. A solver state or work limit returns resource_limit.

An agreement certificate flag means the solver independently verified the original local trace scores and the exact local optima under the cancelling multipliers. The optimal status requires whole-word agreement. A verified absolute or relative gap may yield gap and an attained target with the agreement flag false. The result concerns the discrete optimization of the evaluated parameter snapshot, with no optimizer derivative. Native targets requiring foreign calls to be discharged report the exact missing handler.

JointAlignmentMapRequest didactic-model

JointAlignmentMapRequest(*, graph: StringFactorGraphSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), solver: JointAlignmentMapConfig | JointAlignmentMapGapConfig | JointAlignmentMapFeatureBudgetConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), word_capacity: int, max_assignment_cells: int, max_ratio_bits: int)

Bases: QiecModel

Request one exact-scope joint alignment MAP report from authored QVR.

The graph and already portable singleton or gap solver remain separate fields. The named handler binds both together with the word capacity. The exact score and bound refer to the live evaluated graph.

PARAMETER DESCRIPTION
graph

The original nominal tapes, observations, factor occurrences and owners.

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

solver

The exact local policy, optional gap targets, and feature limits.

TYPE: JointAlignmentMapConfig, JointAlignmentMapGapConfig, or JointAlignmentMapFeatureBudgetConfig DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

word_capacity

Allocated token positions for each variable's returned word.

TYPE: int

max_assignment_cells

Combined allocation limit for the padded words and their length vector.

TYPE: int

max_ratio_bits

Combined numerator and denominator bit limit for four rational fields. The search has separately declared graph and iteration limits.

TYPE: int

objective property

objective: Literal['joint_alignment_map']

Give the exact objective chosen by the checked request.

RETURNS DESCRIPTION
Literal['joint_alignment_map']

Joint maximization over one original alignment per factor and its words.

handler_name property

handler_name: str

Bind the handler to the exact graph, solver, and word capacity.

RETURNS DESCRIPTION
str

The canonical name used in the source Compute declaration.

result_type property

result_type: TypeExpr

Give the checked representation of the exact report.

RETURNS DESCRIPTION
TypeExpr

Status, diagnostic, assignment presence, padded symbols, lengths, rational rows, agreement and gap flags, and five work counts.

JointAlignmentMapRuntimeProvider

JointAlignmentMapRuntimeProvider(request: JointAlignmentMapRequest, parameters: Mapping[ParameterId, Tensor])

Bases: _MapReportRuntime

Run the declared exact joint MAP solver through ordinary native QVR.

Each invocation uses the original live parameter identities. The portable solver verifies its witnesses before the report is encoded. The report contains discrete words and exact rational evidence.

PARAMETER DESCRIPTION
request

The checked authored graph, solver and report bounds.

TYPE: JointAlignmentMapRequest

parameters

Original live LogProb scalar weights used by the graph.

TYPE: Mapping of ParameterId to torch.Tensor

Source code in src/quivers/qiec/alignment_map_runtime.py
def __init__(
    self,
    request: JointAlignmentMapRequest,
    parameters: Mapping[ParameterId, torch.Tensor],
) -> None:
    super().__init__(
        request.graph,
        request.word_capacity,
        request.max_ratio_bits,
        request.handler_name,
        request.result_type,
    )
    self._request = request
    self._parameters = parameters

Checked paired alignment MAP

PairedAlignmentMapRequest binds the same authored graph to its portable JointAlignmentMapDecomposition. The checked foreign identity includes the ordered factor groups, all exact solver settings, and both output capacities. Each pair shares exactly one nominal tape variable. The portable solver verifies its exact local witnesses and expands its feasible paths into original occurrences before the runtime formats the evidence.

The first nine fields are the ordinary MAP report. Four more fields describe the paired run. Let \(F\) be the original factor count, \(P\) the allocated original arc positions per trace, and \(G\) the number of groups.

Field QVR carrier
Original start state, final state, and length per factor Int[Fin F, Fin 3]
Original ordered arc occurrence IDs with -1 padding Int[Fin F, Fin P]
Exact original trace scores as signed hexadecimal rational pairs String[Fin F, Fin 2]
Actual product states and arcs per group Int[Fin G, Fin 2]

Trace rows follow original factor order. Each trace's word tuple is given by the common assignment at that factor's ordered variable scope. A feasible limit or gap result can include these traces. A genuine empty trace retains its two boundaries and length zero. Absent traces use -1 integer fields and empty rational pairs. Group rows follow the declared decomposition order, with (-1, -1) for singleton groups. Product sizes can be available on a completed solve with no feasible assignment.

The assignment and length arrays preflight \(V(K+1)\) cells as above. The extra integer arrays preflight \(F(P+3)+2G\) cells. The runtime checks ordinal ranges, actual lengths, and the declared score bit limits before encoding the report. A representational limit returns absent evidence and the available measured search counts. The solver's own pair construction and decoder budgets have a resource_limit outcome. The common certification flags retain their exact local and objective-gap meanings. A checked target without the paired handler reports that missing capability.

PairedAlignmentMapRequest didactic-model

PairedAlignmentMapRequest(*, graph: StringFactorGraphSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), solver: JointAlignmentMapDecomposition = field(opaque=True, extras=OPAQUE_BY_VALUE), word_capacity: int, max_assignment_cells: int, max_ratio_bits: int, arc_capacity: int, max_trace_cells: int, max_trace_ratio_bits: int)

Bases: QiecModel

Request exact native MAP with declared pair joins and original traces.

PARAMETER DESCRIPTION
graph

The authored original graph and live nominal factor owners.

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

solver

The ordered singleton and pair partition, solver policy, and budgets.

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

word_capacity

Allocated token positions per variable's word.

TYPE: int

max_assignment_cells

Combined output cell limit for words and lengths.

TYPE: int

max_ratio_bits

Combined numerator and denominator bit limit for the common evidence.

TYPE: int

arc_capacity

Allocated original occurrence positions per factor trace.

TYPE: int

max_trace_cells

Combined output cell limit for integer trace and product tensors.

TYPE: int

max_trace_ratio_bits

Combined numerator and denominator bit limit for original trace scores.

TYPE: int

objective property

objective: Literal['joint_alignment_map']

Give the objective of the exact paired solver.

RETURNS DESCRIPTION
Literal['joint_alignment_map']

The joint maximum over original factor traces and words.

handler_name property

handler_name: str

Derive the exact paired request's foreign handler identity.

RETURNS DESCRIPTION
str

A canonical name binding the graph, ordered decomposition and layout.

result_type property

result_type: TypeExpr

Give the common report fields followed by exact paired evidence.

RETURNS DESCRIPTION
TypeExpr

The verified search report, original boundaries and lengths, padded original arcs, rational trace scores, and group sizes.

PairedAlignmentMapRuntimeProvider

PairedAlignmentMapRuntimeProvider(request: PairedAlignmentMapRequest, parameters: Mapping[ParameterId, Tensor])

Bases: _MapReportRuntime

Attach the paired exact local solver and its original factor witnesses.

PARAMETER DESCRIPTION
request

The exact graph, pair partition, solver and encoding policy.

TYPE: PairedAlignmentMapRequest

parameters

Original live weights supplying the graph on each call.

TYPE: Mapping of ParameterId to torch.Tensor

Source code in src/quivers/qiec/paired_alignment_map_runtime.py
def __init__(
    self,
    request: PairedAlignmentMapRequest,
    parameters: Mapping[ParameterId, torch.Tensor],
) -> None:
    super().__init__(
        request.graph,
        request.word_capacity,
        request.max_ratio_bits,
        request.handler_name,
        request.result_type,
    )
    self._request = request
    self._parameters = parameters

RegularStringEPConfig didactic-model

RegularStringEPConfig(*, bases: tuple[tuple[str, RationalRelationSpec], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), features: tuple[tuple[str, tuple[tuple[int, ...], ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), penalty: float, max_sweeps: int, max_states: int, max_work: int, max_closure_size: int | None = None, tolerance: float | None = 1e-08, damping: float = 0.0, projection_tolerance: float = 1e-08, projection_max_iterations: int = 512)

Bases: QiecModel

Configure synchronous inclusive-KL projection of regular string messages.

Each variable has a one-tape LogProb reference language and an ordered feature vocabulary. Reference weights enter the target distribution. Unit reference weights give a support restriction of the original factor model. The solver snapshots weights and returns approximate beliefs, without a derivative through the schedule or its fixed point.

PARAMETER DESCRIPTION
bases

Variable names paired with finite regular reference specifications.

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

features

Variable names paired with their candidate n-grams in coefficient order.

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

penalty

Nonnegative strength of the n-gram prefix-group penalty.

TYPE: float

max_sweeps

Maximum accepted synchronous sweeps.

TYPE: int

max_states

State limit per sparse relation operation.

TYPE: int

max_work

Work limit per sparse relation operation.

TYPE: int

max_closure_size

Maximum size of a productive closed component, if permitted.

TYPE: int or None DEFAULT: None

tolerance

Upper bound on the undamped site change, or None for the full budget.

TYPE: float or None DEFAULT: 1e-08

damping

Fraction of the old site retained at each update.

TYPE: float DEFAULT: 0.0

projection_tolerance

Tolerance of the local proximal-gradient solver.

TYPE: float DEFAULT: 1e-08

projection_max_iterations

Accepted iteration limit for each local projection.

TYPE: int DEFAULT: 512

objective property

objective: Literal['regular_string_ep']

Identify the objective selected by this record.

RETURNS DESCRIPTION
Literal['regular_string_ep']

Inclusive-KL projection of regular string messages.

infer

infer(model: StringFactorGraphSpec, parameters: RelationWeightBindings, *, projection_optimizer: _ProjectionOptimizer = 'backtracking', initial_sites: _InitialSites | None = None, max_moment_evaluations: int | None = None, max_prefix_group_cells: int | None = None, projection_frontiers: _FrontierSeeds | None = None) -> RegularStringEPResult

Run projected sum-product on a bound graph and its reference languages.

PARAMETER DESCRIPTION
model

The checked string factors, variables, and observations.

TYPE: StringFactorGraphSpec

parameters

The original scalar tensors used by the graph and its references.

TYPE: RelationWeightBindings

projection_optimizer

The local proximal optimizer's step policy.

TYPE: ('backtracking', 'fixed_lipschitz') DEFAULT: "backtracking"

initial_sites

Finite site guesses in exact factor, tape and feature order. None initializes unit sites.

TYPE: tuple or None DEFAULT: None

max_moment_evaluations

Total moment evaluations allowed across this run.

TYPE: int or None DEFAULT: None

max_prefix_group_cells

Maximum coefficient indices stored for one penalized fit.

TYPE: int or None DEFAULT: None

projection_frontiers

Optional per-variable candidate subsets for fixed-step fits.

TYPE: tuple or None DEFAULT: None

RETURNS DESCRIPTION
RegularStringEPResult

The approximate marginals, site scales, and convergence diagnostics.

RAISES DESCRIPTION
ValueError

The optimizer, initial sites, frontier, or resource caps are invalid.

RelationLimitError

If the run exceeds either declared resource cap.

Source code in src/quivers/qiec/string_solvers.py
def infer(
    self,
    model: StringFactorGraphSpec,
    parameters: RelationWeightBindings,
    *,
    projection_optimizer: _ProjectionOptimizer = "backtracking",
    initial_sites: _InitialSites | None = None,
    max_moment_evaluations: int | None = None,
    max_prefix_group_cells: int | None = None,
    projection_frontiers: _FrontierSeeds | None = None,
) -> RegularStringEPResult:
    """Run projected sum-product on a bound graph and its reference languages.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The checked string factors, variables, and observations.
    parameters : RelationWeightBindings
        The original scalar tensors used by the graph and its references.
    projection_optimizer : {"backtracking", "fixed_lipschitz"}
        The local proximal optimizer's step policy.
    initial_sites : tuple or None
        Finite site guesses in exact factor, tape and feature order.
        None initializes unit sites.
    max_moment_evaluations : int or None
        Total moment evaluations allowed across this run.
    max_prefix_group_cells : int or None
        Maximum coefficient indices stored for one penalized fit.
    projection_frontiers : tuple or None
        Optional per-variable candidate subsets for fixed-step fits.

    Returns
    -------
    RegularStringEPResult
        The approximate marginals, site scales, and convergence diagnostics.

    Raises
    ------
    ValueError
        The optimizer, initial sites, frontier, or resource caps are invalid.
    RelationLimitError
        If the run exceeds either declared resource cap.
    """
    _validate_regular_optimizer(projection_optimizer)
    _validate_projection_resources(max_moment_evaluations, max_prefix_group_cells)
    _validate_initial_values(initial_sites)
    features = dict(self.features)
    _validate_frontier_seeds(projection_frontiers, features, projection_optimizer)
    if initial_sites is not None:
        alphabets = {
            name: (alphabet, size) for name, alphabet, size, _ in model.variables
        }
        if alphabets.keys() != features.keys() or any(
            spec.tapes != (alphabets[name],) for name, spec in self.bases
        ):
            raise ValueError(
                "regular EP initial sites require matching nominal tapes"
            )
        _validate_initial_scope(
            tuple(scope for _, scope in model.factors), features, initial_sites
        )
    graph = model.bind(
        parameters, max_states=self.max_states, max_work=self.max_work
    )
    return regular_string_ep(
        graph,
        {name: spec.bind(parameters) for name, spec in self.bases},
        features,
        penalty=self.penalty,
        max_sweeps=self.max_sweeps,
        max_states=self.max_states,
        max_work=self.max_work,
        max_closure_size=self.max_closure_size,
        tolerance=self.tolerance,
        damping=self.damping,
        projection_tolerance=self.projection_tolerance,
        projection_max_iterations=self.projection_max_iterations,
        projection_optimizer=projection_optimizer,
        initial_sites=initial_sites,
        max_moment_evaluations=max_moment_evaluations,
        max_prefix_group_cells=max_prefix_group_cells,
        projection_frontiers=projection_frontiers,
    )

RegularStringEPPolicy didactic-model

RegularStringEPPolicy(*, config: RegularStringEPConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), projection_optimizer: _ProjectionOptimizer = 'backtracking', initial_sites: _InitialSites | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), gradient_policy: Literal['detached', 'finite_unrolled', 'converged'] = 'detached', error_guarantee: Literal['none', 'certified_global'] = 'none')

Bases: QiecModel

Select regular EP's optimizer, initializer, and supported guarantees.

PARAMETER DESCRIPTION
config

The reference languages, candidate features, penalty, and schedule.

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

projection_optimizer

The majorizing proximal step policy for every tilted fit.

TYPE: ('backtracking', 'fixed_lipschitz') DEFAULT: "backtracking"

initial_sites

Initial factor occurrence, variable, ordered feature tuple, finite float coefficient tuple, and finite float log scale for each site in graph order. None initializes unit sites.

TYPE: tuple or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

gradient_policy

The schedule and its limit have no derivative through the fitted result. Finite unrolled and converged derivative requests refuse.

TYPE: 'detached' DEFAULT: "detached"

error_guarantee

Local residuals carry no certified global posterior error bound. A request for one refuses.

TYPE: 'none' DEFAULT: "none"

objective property

objective: Literal['regular_string_ep']

Identify the projected sum-product objective selected by this policy.

RETURNS DESCRIPTION
Literal['regular_string_ep']

Regular string EP using inclusive-KL local projection.

infer

infer(model: StringFactorGraphSpec, parameters: RelationWeightBindings, *, max_moment_evaluations: int | None = None, max_prefix_group_cells: int | None = None, projection_frontiers: _FrontierSeeds | None = None) -> RegularStringEPResult

Run the checked graph with the declared EP execution policy.

PARAMETER DESCRIPTION
model

The checked string graph with its nominal scopes and observations.

TYPE: StringFactorGraphSpec

parameters

Live original weight owners used in this invocation.

TYPE: RelationWeightBindings

max_moment_evaluations

Total moment evaluations allowed across this run.

TYPE: int or None DEFAULT: None

max_prefix_group_cells

Maximum coefficient indices stored for one penalized fit.

TYPE: int or None DEFAULT: None

projection_frontiers

Optional per-variable candidate subsets for fixed-step fits.

TYPE: tuple or None DEFAULT: None

RETURNS DESCRIPTION
RegularStringEPResult

Approximate beliefs, convergence diagnostics, and measured work.

RAISES DESCRIPTION
ValueError

If the supplied resource caps or frontier are invalid.

RelationLimitError

If the run exceeds either declared resource cap.

Source code in src/quivers/qiec/string_solvers.py
def infer(
    self,
    model: StringFactorGraphSpec,
    parameters: RelationWeightBindings,
    *,
    max_moment_evaluations: int | None = None,
    max_prefix_group_cells: int | None = None,
    projection_frontiers: _FrontierSeeds | None = None,
) -> RegularStringEPResult:
    """Run the checked graph with the declared EP execution policy.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The checked string graph with its nominal scopes and observations.
    parameters : RelationWeightBindings
        Live original weight owners used in this invocation.
    max_moment_evaluations : int or None
        Total moment evaluations allowed across this run.
    max_prefix_group_cells : int or None
        Maximum coefficient indices stored for one penalized fit.
    projection_frontiers : tuple or None
        Optional per-variable candidate subsets for fixed-step fits.

    Returns
    -------
    RegularStringEPResult
        Approximate beliefs, convergence diagnostics, and measured work.

    Raises
    ------
    ValueError
        If the supplied resource caps or frontier are invalid.
    RelationLimitError
        If the run exceeds either declared resource cap.
    """
    return self.config.infer(
        model,
        parameters,
        projection_optimizer=self.projection_optimizer,
        initial_sites=self.initial_sites,
        max_moment_evaluations=max_moment_evaluations,
        max_prefix_group_cells=max_prefix_group_cells,
        projection_frontiers=projection_frontiers,
    )

PrunedStringBPConfig didactic-model

PrunedStringBPConfig(*, supports: tuple[tuple[str, tuple[tuple[int, ...], ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), beam: int, max_sweeps: int, max_entries: int, max_states: int, max_work: int, max_closure_size: int | None = None, tolerance: float | None = 1e-09, damping: float = 0.0)

Bases: QiecModel

Configure a beam-pruned schedule on declared finite string supports.

Supports describe the finite candidate pool and are kept separate from the typed graph. The configuration contains only inputs and limits. A run derives the convergence status and raw, retained and omitted message masses from the current specified graph and weights.

PARAMETER DESCRIPTION
supports

Variable names and their candidate words in result order.

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

beam

Positive limit on the number of retained words per message.

TYPE: int

max_sweeps

Positive number of permitted synchronous updates.

TYPE: int

max_entries

Maximum total entries in the bound finite factor tables.

TYPE: int

max_states

Cumulative observed configuration budget when building the tables.

TYPE: int

max_work

Cumulative arc examination budget when building the tables.

TYPE: int

max_closure_size

Optional size bound for productive cyclic closure components.

TYPE: int or None DEFAULT: None

tolerance

Threshold for undamped pruned residual, or None for fixed sweeps.

TYPE: float or None DEFAULT: 1e-09

damping

Old-message mixing fraction after restriction to the new support.

TYPE: float DEFAULT: 0.0

objective property

objective: Literal['pruned_string_bp']

Identify beam-pruned finite sum-product inference.

RETURNS DESCRIPTION
Literal['pruned_string_bp']

The declared approximate schedule.

infer

Bind the checked graph and evaluate the declared beam schedule.

PARAMETER DESCRIPTION
model

The original typed graph, variable identities, and observations.

TYPE: StringFactorGraphSpec

parameters

Original weight owners and permitted Markov complements.

TYPE: RelationWeightBindings

RETURNS DESCRIPTION
PrunedStringBeliefResult

Derived approximate beliefs and measured diagnostics.

Source code in src/quivers/qiec/string_solvers.py
def infer(
    self,
    model: StringFactorGraphSpec,
    parameters: RelationWeightBindings,
) -> PrunedStringBeliefResult:
    """Bind the checked graph and evaluate the declared beam schedule.

    Parameters
    ----------
    model : StringFactorGraphSpec
        The original typed graph, variable identities, and observations.
    parameters : RelationWeightBindings
        Original weight owners and permitted Markov complements.

    Returns
    -------
    PrunedStringBeliefResult
        Derived approximate beliefs and measured diagnostics.
    """
    return self._plan(model, parameters).run_pruned(
        beam=self.beam,
        max_sweeps=self.max_sweeps,
        tolerance=self.tolerance,
        damping=self.damping,
    )

Checked regular belief queries

RegularStringEPRequest selects one variable and an ordered list of words in a checked graph. The graph, nominal reference tapes, candidate n-grams, variable, and word order determine the foreign handler name. The same declaration can run with different schedules, penalties, and resource limits. An optional RegularStringEPPolicy must wrap the request's exact configuration. The provider derives the immutable handler name and report type once at construction, then binds live weights on each invocation.

The result carries the solver status and diagnostic, accepted sweeps, a Boolean and a value for the measured residual, a Boolean and an ordered tensor of available log probabilities, and the number of local projections attempted on the last sweep. A failed local projection retains the belief from the last accepted update. A resource limit records why the query could not complete and marks the belief unavailable. An observed log-zero normalizer for a belief, cavity, or tilt produces zero_mass and also marks the belief unavailable. This status describes the evaluated normalizer at the runtime precision. It carries no global support or posterior certificate. An available belief assigns log zero to individual words outside its support.

The solver snapshots the original weights on each invocation. The report does not differentiate through the projection or certify a global posterior error. Scoring \(k\) probes adds \(k\) bounded word queries to the work of the regular EP schedule. The request does not enumerate the reference language.

import torch

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    ParameterId, RegularStringEPConfig, RegularStringEPRequest,
    RegularStringEPRuntimeProvider, RuntimeConfiguration, run_named,
)

source = """
object Letter : FinSet 2

relation alternatives [algebra=logprob, states=2]
    output Letter
    initial 0 [weight=unit_weight]
    arc 0 -> 1 [labels=(0), weight=unit_weight]
    arc 0 -> 1 [labels=(1), weight=unit_weight]
    final 1 [weight=unit_weight]

string_graph vocabulary
    variable word : Letter
    factor alternatives(word)
"""
compiler = Compiler(parse(source), module_name="regular-belief")
request = RegularStringEPRequest(
    graph=compiler.string_graph_specs["vocabulary"],
    config=RegularStringEPConfig(
        bases=(("word", compiler.relation_specs["alternatives"]),),
        features=(("word", ((1,),)),),
        penalty=0.0, max_sweeps=2, max_states=128, max_work=256,
    ),
    variable="word", words=((1,), ()),
)
handler = request.handler_name
report = "(String * String * Int * Bool * Real * Bool * LogWeight[Fin 2] * Int)"
source += f"""
instance estimate : Compute[Unit, {report}]
handler {handler} for Compute[Unit, {report}] : {report} -> {report} [coverage=total, forwards=none, implementation=foreign]
    apply resumes 1

define belief : {report} !{{}} =
    handle estimate with {handler} in
        let result <- perform estimate.apply(unit)
        return result
"""
module = Compiler(parse(source), module_name="regular-belief").qiec_module
assert module is not None
owner = ParameterId.derive(module.module, "relation_weights", "unit_weight")
provider = RegularStringEPRuntimeProvider(request, {owner: torch.zeros((), dtype=torch.float64)})
runtime = RuntimeConfiguration(providers=(provider,))
status, _, _, _, _, available, scores, _ = run_named(module, "belief", runtime=runtime).value
assert status == "converged" and available.item()
torch.testing.assert_close(scores.exp(), torch.tensor([0.5, 0.0], dtype=torch.float64))

RegularStringEPRequest didactic-model

RegularStringEPRequest(*, graph: StringFactorGraphSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), config: RegularStringEPConfig = field(opaque=True, extras=OPAQUE_BY_VALUE), variable: str, words: tuple[tuple[int, ...], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Query finitely many words in one variable's fitted regular belief.

PARAMETER DESCRIPTION
graph

The exact typed source graph and original parameter owners.

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

config

The reference languages, feature families, and declared schedule.

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

variable

The variable whose normalized log probabilities are requested.

TYPE: str

words

Distinct probes in their requested order. Words outside finite reference support have zero probability.

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

handler_name property

handler_name: str

Bind the checked graph, reference family, variable, and word order.

RETURNS DESCRIPTION
str

The canonical foreign handler name for those static inputs.

result_type property

result_type: TypeExpr

Give the typed report's result carrier.

RETURNS DESCRIPTION
TypeExpr

Status, reason, accepted sweeps, residual presence and value, belief presence, log probabilities, and fit attempts in the final pass.

RegularStringEPRuntimeProvider

RegularStringEPRuntimeProvider(request: RegularStringEPRequest, parameters: RelationWeightBindings, *, policy: RegularStringEPPolicy | None = None, max_moment_evaluations: int | None = None, max_prefix_group_cells: int | None = None, projection_frontiers: _FrontierSeeds | None = None)

Run an authored report with the existing bounded regular EP executor.

PARAMETER DESCRIPTION
request

The checked graph, references, and solver settings.

TYPE: RegularStringEPRequest

parameters

The original live weight owners. Each execution snapshots their current values. The fitted report has no derivative through EP.

TYPE: RelationWeightBindings

policy

Optional optimizer and initialization policy wrapping the exact request configuration. None uses the ordinary unit initialization and adaptive backtracking.

TYPE: RegularStringEPPolicy or None DEFAULT: None

max_moment_evaluations

Total moment evaluations allowed for each run.

TYPE: int or None DEFAULT: None

max_prefix_group_cells

Maximum coefficient indices stored for one penalized fit.

TYPE: int or None DEFAULT: None

projection_frontiers

Optional initial candidate subsets by variable for a policy that selects the fixed Lipschitz step.

TYPE: tuple or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If the supplied policy wraps a different solver configuration or a supplied resource limit or frontier is invalid.

Source code in src/quivers/qiec/regular_ep_runtime.py
def __init__(
    self,
    request: RegularStringEPRequest,
    parameters: RelationWeightBindings,
    *,
    policy: RegularStringEPPolicy | None = None,
    max_moment_evaluations: int | None = None,
    max_prefix_group_cells: int | None = None,
    projection_frontiers: _FrontierSeeds | None = None,
) -> None:
    if policy is not None and policy.config != request.config:
        raise ValueError("regular EP policy must wrap the exact request config")
    _validate_projection_resources(max_moment_evaluations, max_prefix_group_cells)
    _validate_frontier_seeds(
        projection_frontiers,
        dict(request.config.features),
        policy.projection_optimizer if policy is not None else "backtracking",
    )
    self._projection_frontiers = projection_frontiers
    self._max_moment_evaluations = max_moment_evaluations
    self._max_prefix_group_cells = max_prefix_group_cells
    self._request = request
    self._parameters = parameters
    self._solver = request.config if policy is None else policy
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach only to the exact authored foreign Compute declaration.

PARAMETER DESCRIPTION
module

The checked module declaring the named handler.

TYPE: QiecModule

attachments

Runtime handler bindings for this invocation.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

If the module lacks the graph and word-specific name.

TypeError

If the named handler does not have the checked Compute type.

Source code in src/quivers/qiec/regular_ep_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach only to the exact authored foreign Compute declaration.

    Parameters
    ----------
    module : QiecModule
        The checked module declaring the named handler.
    attachments : RuntimeAttachments
        Runtime handler bindings for this invocation.

    Raises
    ------
    ValueError
        If the module lacks the graph and word-specific name.
    TypeError
        If the named handler does not have the checked Compute type.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Return the built-in validator for the exact report carrier.

PARAMETER DESCRIPTION
type_

The carrier requested by the reference machine.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The canonical product validator for this report.

Source code in src/quivers/qiec/regular_ep_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Return the built-in validator for the exact report carrier.

    Parameters
    ----------
    type_ : TypeExpr
        The carrier requested by the reference machine.

    Returns
    -------
    RuntimeValidator or None
        The canonical product validator for this report.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)

The regular report's final integer counts local fit attempts in the final pass. The Python result separately records moment evaluations across all attempted sweeps. A RegularStringEPRuntimeProvider can set max_moment_evaluations for each invocation and max_prefix_group_cells for each penalized local fit. The first cap counts target, base and trial moments throughout the schedule. The second bounds the stored feature memberships in the prefix groups. Exhaustion yields a resource_limit report with unavailable scores and a reason naming the cap. These runtime settings use the existing checked handler and portable request format.

For a RegularStringEPPolicy with projection_optimizer="fixed_lipschitz", projection_frontiers can select the initial feature subset for each listed variable. The subsets follow their declared candidate order and can be empty. Each staged fit checks its residual over the full dictionary. The native report continues to describe the existing detached regular EP schedule.

Checked finite-unrolled string EP

FiniteStringEPRequest gives an authored string graph an explicit finite word support on each variable and a fixed number of accepted synchronous sweeps. The provider reuses the finite-support EP solver with an unpenalized unigram family and float64 weights. The full tilt must have positive probability at every declared support word in the working precision. Each observed-pair factor query requires an acyclic productive path graph. Observed variables restrict their support to the observed word.

HigherOrderFiniteStringEPRequest pairs the same finite schedule with all contiguous n-gram orders through a declared maximum of at least two. It uses the same report type. Its handler name binds the maximum order as well as the underlying schedule identity. Warm sites use the exact affine basis for that order on the effective support.

Each call evaluates the original live factor tables. The provider reuses the table topology and affine bases. The finite solver forms normalized cavities, fits an inclusive-KL unigram projection by Newton steps, and divides the fitted marginal by the cavity to get its site message. Damping interpolates old and proposed log sites. An optional warm initialization gives finite coefficients in exact factor, variable, and affine-basis order. These are initial sites for the requested computation.

The checked handler identity binds the graph, ordered supports and probes, warm sites, sweep count, damping, and local optimizer settings. The graph and feature resource caps can tighten for the same finite program. A successful report has status completed, its accepted sweep count, the final undamped residual, a score-availability flag, the ordered log probabilities, and Int[Fin 3]. The three cumulative counts cover local fit attempts, accepted Newton steps, and line-search trials, including the final diagnostic pass. An ordered probe off the declared support has log weight negative infinity. A local fit failure makes the requested report unavailable and records its accepted sweep count and work through the failure. Graph and feature exhaustion and unsupported closure have their own statuses.

Autodiff follows the executed finite program, including the accepted Newton and damping updates. Stopping and trial selection are discrete tests in working precision. The derivative applies along the branch selected by those tests. A branch with zero accepted local iterations can give a constant score with respect to its factor. Completion reports the requested number of sweeps. Converged-solution, fixed-point, and certified global error guarantees are outside this report's domain. A target that lacks the native handler reports that capability boundary.

Even an exact zero residual can leave the regular EP fixed point underdetermined. Consider two binary variables connected by two equality factors, with positive reference weights and a unigram feature that distinguishes the two values. Each unpenalized projection then represents its tilted marginal exactly. In log odds, each proposed factor message copies the cavity message across its factor. The simultaneous update permutes the four site log odds, and any common log odds is a fixed point with a different belief. Thus removing additive log scales still leaves an eigenvalue of one in the update Jacobian. An arbitrarily small log bias on one equality factor's (0, 0) entry adds a nonzero increment around a copy cycle, so that cycle has no finite fixed point. A site residual cannot certify a differentiable isolated root in this setting.

Work and storage bounds

Table construction charges cumulative entries, visited states, and candidate arcs over the explicit factor supports. Derived factor construction applies the state and work bounds per transform. For a variable with \(N\) supported words, \(D\) distinct unigrams and affine rank \(r\leq\min(N-1,D)\), the feature cap charges \(ND\) cells after any observation restriction. Unigram counting scans the word tokens, the exact affine-basis selection uses \(O(DN(1+r))\) rational operations on the count matrix, and the fit stores \(O(Nr+r^2+N)\) tensor entries per step, apart from the existing factor table and cavity tensors.

For higher orders, \(D\) counts distinct n-grams through the declared order. A separate max_ngram_work cap charges twice the total token length of the contiguous windows, for preflight and family construction. For a word of length \(L\) and effective order \(K\), this charge is \(2\sum_{n=1}^{K} n(L-n+1)\). The cap also charges the total token length of the nonempty prefixes of each distinct feature. Both charges are summed over effective variable supports. The window charge is checked before slicing the words for a variable. Feature cells and prefix charges are checked as distinct features are encountered, before building the factor tables or affine basis. Sorting the feature and prefix keys has a separate comparison cost of \(O(K(D\log(D+1)+U\log(U+1)))\), where \(U\) is the number of distinct prefixes. The report's three counters retain their local optimization meaning.

A fit forms its dense local covariance in \(O(Nr^2)\) work and solves the Newton system in \(O(r^3)\) work. Each line-search trial costs \(O(N(r+1))\). Factor-to-variable messages reduce the declared dense factor table once per outgoing axis. If the graph has \(A\) factor-argument sites, \(S\) fixed sweeps admit at most \((S+1)A\) local fits. The final pass checks updates at the returned state. With \(P\) accepted-step slots and \(B\) backtracks allowed per step, there are at most \((S+1)AP\) accepted updates and \((S+1)AP(B+1)\) trials. Backward retains the accepted finite trajectory and factor-table evaluation. The domain and these limits bound tensor sizes and operation counts separately from backend memory use and rational integer bit cost.

Measured finite trajectory

Run python -m tools.benchmark_finite_ep_trajectory --repeats 5 from the repository root. The tool calls the checked native EP provider on a unary factor over all \(N=2^n\) binary words of length \(n\). Each position has two parallel arcs for zero and one for one. The two zero arcs share a live log weight \(w\). The arc for one has unit weight. An observed word with \(k\) zeros admits \(n+k\) arcs. The labeled index visits precisely those candidates, giving \(N(n+1)\) visited states and \(3nN/2\) candidate and retained arcs across the factor table.

The cavity is uniform in this single-site graph. The exact tilted probability of zero at any position is \(p=2e^w/(1+2e^w)\). The unigram feature matrix has \(2N\) entries and affine rank one, with variance \(n/4\) at the uniform starting point. A full Newton step gives the coefficient \(a=4(p-1/2)\). On \(0.57<p<0.61\), the initial residual exceeds the tolerance \(0.002n\). The objective curvature along the step is \(n\log\cosh(a/2)\leq na^2/8\), within the line search's allowance. The next residual is \(n|u-\tanh(u)|/2\leq n|u|^3/6<0.002n\), where \(u=a/2\). Thus each fit accepts one full step throughout this neighborhood.

With damping \(d\) and \(S\) accepted sweeps, the returned marginal is the product distribution with zero probability \(\hat p=\operatorname{logistic}((1-d^S)a)\). The tool checks every returned word score against this distribution. It checks the gradient of the all-zero word's log probability against \(4n(1-\hat p)(1-d^S)p(1-p)\). The solver reports \(S+1\) fits, including the diagnostic fit at the returned state. The factor table takes \(O(nN)\) scalar work to evaluate. Each rank-one fit takes \(O(N)\) scalar work. Forward, backward, and the accepted trajectory's saved tensor entries are bounded by \(O(N(n+S))\) on this fixture with one step per fit.

Words Sweeps Fit attempts Forward scalar ops Backward scalar ops Saved bytes Forward peak bytes Backward peak bytes Forward ms Backward ms
2 1 2 345 76 314 887 88 2.87 0.27
2 4 5 855 190 740 1,385 112 4.26 0.58
8 1 2 1,330 456 1,739 3,620 272 4.15 0.89
8 4 5 3,244 894 3,029 4,982 355 5.43 1.22
32 1 2 5,390 3,008 9,383 16,496 1,040 9.00 4.45
32 4 5 12,920 4,742 14,129 21,314 1,552 10.16 4.69

These measurements use CPU float64, one thread, macOS arm64, and PyTorch 2.15. Times are warmed medians of five calls. The tool reports source setup, checked table construction, and the first forward call separately. The first forward call includes affine basis construction. The scalar work counts use the repository's tensor-operation counter. Peak bytes are increases over each phase's opening CPU tensor allocator balance. Saved bytes count unique tensor storages still held for backward when forward returns. The JSON also counts logical elements saved during forward, including transient diagnostic saves and duplicate saves. Python allocations and the retained static plan are outside the allocator columns.

FiniteStringEPRequest didactic-model

FiniteStringEPRequest(*, graph: StringFactorGraphSpec = field(opaque=True, extras=OPAQUE_BY_VALUE), supports: _Supports = field(opaque=True, extras=OPAQUE_BY_VALUE), variable: str, words: tuple[_Word, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), sweeps: int, damping: float, projection_tolerance: float, projection_max_iterations: int, projection_max_backtracks: int, max_entries: int, max_states: int, max_work: int, max_feature_cells: int, max_site_fits: int, initial_sites: _FiniteEPInitialSites | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Request fixed-sweep, unpenalized unigram EP on declared finite supports.

Accepted updates retain their autodiff graph. Branch decisions use the actual working-precision tests. The request concerns a finite program's derivative on its executed branch.

PARAMETER DESCRIPTION
graph

The exact authored factors, observations, and original weight owners.

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

supports

One ordered finite support per graph variable.

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

variable

The selected marginal.

TYPE: str

words

Distinct probe words in result order.

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

sweeps

The exact number of accepted synchronous sweeps required.

TYPE: int

damping

The old site's fraction in log-space damping.

TYPE: float

projection_tolerance

The local infinity-norm moment residual tolerance.

TYPE: float

projection_max_iterations

Bounds for accepted Newton steps and backtracks per step.

TYPE: int

projection_max_backtracks

Bounds for accepted Newton steps and backtracks per step.

TYPE: int

max_entries

Cumulative factor table entries, reached states, and candidate arc examinations for the observed-pair tables. Productive cycles refuse.

TYPE: int

max_states

Cumulative factor table entries, reached states, and candidate arc examinations for the observed-pair tables. Productive cycles refuse.

TYPE: int

max_work

Cumulative factor table entries, reached states, and candidate arc examinations for the observed-pair tables. Productive cycles refuse.

TYPE: int

max_feature_cells

Bound on the summed full unigram matrix sizes after observations.

TYPE: int

max_site_fits

Bound on the number of local site attempts, including diagnostics on the returned state.

TYPE: int

initial_sites

Ordered factor occurrence, variable, affine basis, and finite coefficient vector for each warm initial normalized site.

TYPE: tuple or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

gradient_policy property

gradient_policy: Literal['finite_unrolled']

Give the derivative scope of the requested program.

RETURNS DESCRIPTION
Literal['finite_unrolled']

Autodiff follows the accepted finite sequence of operations.

handler_name property

handler_name: str

Bind the exact requested finite function to its foreign Compute.

RETURNS DESCRIPTION
str

The handler identity, including the solver and initialization choices.

result_type property

result_type: TypeExpr

Give the typed report and aggregate work counters.

RETURNS DESCRIPTION
TypeExpr

Status, diagnostic, sweeps, residual presence and value, belief presence, ordered log scores, and three work counters.

HigherOrderFiniteStringEPRequest didactic-model

HigherOrderFiniteStringEPRequest(*, schedule: FiniteStringEPRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), order: int, max_ngram_work: int)

Bases: QiecModel

Request finite-unrolled EP with a checked higher-order n-gram family.

The schedule retains its graph, finite support, warm-site order, optimizer settings, and result carrier. Feature cells now count all included n-grams, and warm coefficients refer to the resulting affine basis.

PARAMETER DESCRIPTION
schedule

The finite update schedule and its ordered graph interface.

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

order

Include contiguous n-grams from order one through this order, at least two. The declared order is part of the handler identity.

TYPE: int

max_ngram_work

Cap the token slots of two window passes and of nonempty prefixes of distinct features, after restricting observed coordinates.

TYPE: int

gradient_policy property

gradient_policy: Literal['finite_unrolled']

Give the derivative scope of the requested program.

RETURNS DESCRIPTION
Literal['finite_unrolled']

Autodiff follows the accepted finite sequence of operations.

handler_name property

handler_name: str

Bind the order and exact finite schedule to a foreign Compute.

RETURNS DESCRIPTION
str

The higher-order handler identity.

result_type property

result_type: TypeExpr

Give the report type for the schedule's ordered probes.

RETURNS DESCRIPTION
TypeExpr

The finite-unrolled EP report carrier.

FiniteStringEPRuntimeProvider

FiniteStringEPRuntimeProvider(request: FiniteStringEPRequest | HigherOrderFiniteStringEPRequest, parameters: RelationWeightBindings)

Expose the accepted finite EP schedule through checked native Compute.

PARAMETER DESCRIPTION
request

The exact finite program, graph, probes, and resource limits.

TYPE: FiniteStringEPRequest or HigherOrderFiniteStringEPRequest

parameters

Original live scalar owners supplying a new evaluation snapshot.

TYPE: RelationWeightBindings

Source code in src/quivers/qiec/finite_ep_runtime.py
def __init__(
    self,
    request: FiniteStringEPRequest | HigherOrderFiniteStringEPRequest,
    parameters: RelationWeightBindings,
) -> None:
    if isinstance(request, HigherOrderFiniteStringEPRequest):
        self._higher_order = request
        self._request = request.schedule
    else:
        self._higher_order = None
        self._request = request
    self._parameters = parameters
    self._handler_name = request.handler_name
    self._result_type = request.result_type

attach

attach(module: QiecModule, attachments: RuntimeAttachments) -> None

Attach only to the exact declared finite EP program.

PARAMETER DESCRIPTION
module

The module containing the nominal foreign Compute.

TYPE: QiecModule

attachments

The current invocation's handler table.

TYPE: RuntimeAttachments

RAISES DESCRIPTION
ValueError

The named handler is absent or ambiguous.

TypeError

The declaration has an incompatible Compute contract.

Source code in src/quivers/qiec/finite_ep_runtime.py
def attach(self, module: QiecModule, attachments: RuntimeAttachments) -> None:
    """Attach only to the exact declared finite EP program.

    Parameters
    ----------
    module : QiecModule
        The module containing the nominal foreign Compute.
    attachments : RuntimeAttachments
        The current invocation's handler table.

    Raises
    ------
    ValueError
        The named handler is absent or ambiguous.
    TypeError
        The declaration has an incompatible Compute contract.
    """
    definition = _fixed_compute_definition(
        module, self._handler_name, self._result_type
    )
    validator = self.validator_for(self._result_type)
    assert validator is not None
    runtime = compute_handler(
        self._evaluate,
        effect=definition.effect,
        result_validator=validator,
        answer_type=definition.output_type,
        key=definition.name,
    )
    attachments.bind_handler(runtime.with_(definition=definition))

validator_for

validator_for(type_: TypeExpr) -> RuntimeValidator | None

Supply the exact checked report carrier validator.

PARAMETER DESCRIPTION
type_

The runtime type to validate.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeValidator or None

The canonical product validator when the carrier matches.

Source code in src/quivers/qiec/finite_ep_runtime.py
def validator_for(self, type_: TypeExpr) -> RuntimeValidator | None:
    """Supply the exact checked report carrier validator.

    Parameters
    ----------
    type_ : TypeExpr
        The runtime type to validate.

    Returns
    -------
    RuntimeValidator or None
        The canonical product validator when the carrier matches.
    """
    if type_ != self._result_type:
        return None
    return CoreRuntimeProvider().validator_for(type_)