Skip to content

Morphisms

A finite morphism stores one weight for each pair of an input and an output, as a tensor. Composing a table from users to features with a table from features to items sums out the feature axis under the chosen Algebra and gives weights from users to items. An ObservedMorphism holds given values, and a LatentMorphism holds learnable parameters. The module defines the base morphism classes, their composition, and shared morphism utilities.

morphisms

Typed V-enriched morphisms and their finite tensor representation.

A finite tensor morphism from domain D to codomain C has shape (*D.shape, *C.shape) with entries in the carrier of an algebra. Finite tensor composition joins over the product of these entries.

The finite hierarchy:

Morphism
└── FiniteMorphism (abstract)
    ├── ObservedMorphism    — fixed tensor (not learned)
    ├── LatentMorphism      — nn.Parameter with sigmoid constraint
    ├── ComposedMorphism    — f >> g (V-enriched composition)
    ├── ProductMorphism     — f @ g (tensor / parallel product)
    ├── MarginalizedMorphism — contract codomain dims via join
    ├── FunctorMorphism     — lazy image of a morphism under a functor
    └── RepeatMorphism      — runtime-variable iterated composition (T^n)

PyTorch boundary

The categorical hierarchy is intentionally not a subclass of torch.nn.Module: a Morphism is a categorical object and a Module is a PyTorch parameter container. When a Morphism needs to be bound into a parameter-tracking context (a MonadicProgram, a FanMorphism, a parametric-program parameter slot), the adapter as_torch_module produces a backend-agnostic nn.Module wrapping the morphism's parameters. Every binding site funnels through this adapter so the categorical / PyTorch boundary stays explicit and a JAX or numpy backend can replace as_torch_module without touching the morphism hierarchy itself.

Morphism

Morphism(domain: SetObject, codomain: SetObject, algebra: Algebra | None = None)

Bases: ABC

Typed morphism with an enrichment algebra and parameter module.

Subclasses supply a representation of the morphism. Finite tensor operations require the capability provided by FiniteMorphism.

PARAMETER DESCRIPTION
domain

Source object.

TYPE: SetObject

codomain

Target object.

TYPE: SetObject

algebra

The enrichment algebra. Defaults to PRODUCT_FUZZY.

TYPE: Algebra or None DEFAULT: None

Source code in src/quivers/core/morphisms.py
def __init__(
    self, domain: SetObject, codomain: SetObject, algebra: Algebra | None = None
) -> None:
    self._domain = domain
    self._codomain = codomain
    self._algebra = algebra if algebra is not None else PRODUCT_FUZZY

domain property

domain: SetObject

Source object.

codomain property

codomain: SetObject

Target object.

algebra property

algebra: Algebra

The enrichment algebra for this morphism.

tensor_shape property

tensor_shape: tuple[int, ...]

Expected shape for a morphism with a finite tensor.

dagger property

dagger: 'TransformedMorphism'

Transpose (relational converse) of self : A → B.

Returns the morphism B → A whose tensor has the domain and codomain axes swapped, f^†(b, a) = f(a, b), under every algebra: for Boolean relations it is the converse relation, and for a Markov kernel it is the transposed matrix, which is not a Bayesian inversion and is not row-stochastic in general. When the algebra is a commutative Semiring, V-matrices are compact closed with every object self-dual, the transpose is the dagger of that dagger-compact structure, and it equals (ε_B ⊗ id_A) ∘ (id_B ⊗ f ⊗ id_A) ∘ (id_B ⊗ η_A) with the identity matrices as cup and cap.

RETURNS DESCRIPTION
ObservedMorphism

Morphism B → A whose tensor is the axis-swapped tensor of self. Gradients propagate to the original morphism's parameters through the transpose.

module abstractmethod

module() -> Module

Return an nn.Module wrapping all learnable parameters.

Source code in src/quivers/core/morphisms.py
@abstractmethod
def module(self) -> nn.Module:
    """Return an nn.Module wrapping all learnable parameters."""
    ...

__rshift__

__rshift__(other: Morphism) -> ComposedMorphism

V-enriched composition: self >> other.

Composes self: A -> B with other: B -> C to yield a morphism A -> C, contracting over B using the algebra.

PARAMETER DESCRIPTION
other

Right morphism whose domain must match self's codomain.

TYPE: Morphism

RETURNS DESCRIPTION
ComposedMorphism

The composed morphism.

Source code in src/quivers/core/morphisms.py
def __rshift__(self, other: Morphism) -> ComposedMorphism:
    """V-enriched composition: self >> other.

    Composes self: A -> B with other: B -> C to yield
    a morphism A -> C, contracting over B using the algebra.

    Parameters
    ----------
    other : Morphism
        Right morphism whose domain must match self's codomain.

    Returns
    -------
    ComposedMorphism
        The composed morphism.
    """
    if not isinstance(other, Morphism):
        return NotImplemented
    if self.codomain != other.domain:
        raise TypeError(
            f"cannot compose: codomain {self.codomain!r} != domain {other.domain!r}"
        )
    if not self._algebra.is_compatible(other._algebra):
        raise TypeError(
            f"incompatible algebras: {self._algebra!r} and {other._algebra!r}"
        )
    return ComposedMorphism(self, other)

__matmul__

__matmul__(other: Morphism) -> ProductMorphism

Tensor (parallel) product: self @ other.

Given self: A -> B and other: C -> D, produces a morphism A×C -> B×D whose tensor is the outer product via the algebra's tensor_op.

PARAMETER DESCRIPTION
other

Right morphism.

TYPE: Morphism

RETURNS DESCRIPTION
ProductMorphism

The product morphism.

Source code in src/quivers/core/morphisms.py
def __matmul__(self, other: Morphism) -> ProductMorphism:
    """Tensor (parallel) product: self @ other.

    Given self: A -> B and other: C -> D, produces
    a morphism A×C -> B×D whose tensor is the outer product
    via the algebra's tensor_op.

    Parameters
    ----------
    other : Morphism
        Right morphism.

    Returns
    -------
    ProductMorphism
        The product morphism.
    """
    if not isinstance(other, Morphism):
        return NotImplemented
    return ProductMorphism(self, other)

change_base

change_base(phi) -> 'TransformedMorphism'

Transport this morphism along a change-of-base functor.

phi may be either a quivers.core.algebra_morphisms.CarrierMap (pointwise: the action factors entry-by-entry through phi.apply) or a quivers.core.morphism_transformations.MorphismTransformation (shape-aware: the action consumes the whole tensor plus the morphism for axis resolution).

The result is a TransformedMorphism whose tensor is recomputed on each access by applying phi to the source's current tensor. The source's learnable parameters are exposed through .module() so torch.nn.Module.parameters walks reach them, and each backward through a fresh .tensor access rebuilds a graph rooted at those parameters; multi-step optimisation through change-of-base is supported.

PARAMETER DESCRIPTION
phi

The change-of-base functor. Its source must match self.algebra.

TYPE: CarrierMap or MorphismTransformation

RETURNS DESCRIPTION
TransformedMorphism

A morphism over phi.target whose tensor is the transported tensor of self. For pointwise transformations the domain and codomain are preserved; for shape-aware ones (e.g. BayesInvert) the transformation may swap them.

Source code in src/quivers/core/morphisms.py
def change_base(self, phi) -> "TransformedMorphism":
    """Transport this morphism along a change-of-base functor.

    ``phi`` may be either a
    `quivers.core.algebra_morphisms.CarrierMap`
    (pointwise: the action factors entry-by-entry through
    ``phi.apply``) or a
    `quivers.core.morphism_transformations.MorphismTransformation`
    (shape-aware: the action consumes the whole tensor plus
    the morphism for axis resolution).

    The result is a `TransformedMorphism` whose
    `tensor` is recomputed on each access by applying
    ``phi`` to the source's current tensor. The source's
    learnable parameters are exposed through ``.module()`` so
    `torch.nn.Module.parameters` walks reach them, and
    each backward through a fresh ``.tensor`` access rebuilds
    a graph rooted at those parameters; multi-step optimisation
    through change-of-base is supported.

    Parameters
    ----------
    phi : CarrierMap or MorphismTransformation
        The change-of-base functor. Its ``source`` must match
        ``self.algebra``.

    Returns
    -------
    TransformedMorphism
        A morphism over ``phi.target`` whose tensor is the
        transported tensor of ``self``. For pointwise
        transformations the domain and codomain are preserved;
        for shape-aware ones (e.g. ``BayesInvert``) the
        transformation may swap them.
    """
    _require_finite(self)
    if isinstance(phi, TransSeq):
        # Apply the steps in order; each step's change_base
        # type-checks its own source against the current
        # algebra, so a malformed seam surfaces with the
        # same error a hand-written sequence would produce.
        current: Morphism = self
        for step in phi.steps:
            current = current.change_base(step)
        return cast(TransformedMorphism, current)
    if not isinstance(phi, (CarrierMap, MorphismTransformation)):
        raise TypeError(
            f"change_base: expected CarrierMap, "
            f"MorphismTransformation, or TransSeq; got "
            f"{type(phi).__name__}"
        )
    if type(phi.source) is not type(self._algebra):
        raise TypeError(
            f"change_base: source algebra "
            f"{phi.source.name!r} does not match this morphism's "
            f"algebra {self._algebra.name!r}"
        )
    if isinstance(phi, CarrierMap):
        transform = _build_carrier_map_transform(phi)
        new_domain = self._domain
        new_codomain = self._codomain
    else:
        transform = _build_morphism_transformation_transform(phi, self)
        new_domain = phi.new_domain(self)
        new_codomain = phi.new_codomain(self)
    return TransformedMorphism(
        self,
        transform,
        new_domain,
        new_codomain,
        algebra=phi.target,
    )

refactor

refactor(*, domain=None, codomain=None) -> 'TransformedMorphism'

Switch between flat and product views of this morphism.

Given a morphism f : A -> B whose tensor storage has total numel matching the requested domain / codomain objects, return an equivalent morphism f' : A' -> B' whose tensor is the same data reshaped to the new factored layout. A' and B' must be isomorphic to A and B as objects — same cardinality, possibly different product structure.

Categorically this is the action of an object iso B ≅ B' on the morphism's tensor. Semantically it is a no-op; presentation only.

PARAMETER DESCRIPTION
domain

New domain. Must have prod(shape) == prod(self.domain.shape).

TYPE: SetObject DEFAULT: None

codomain

New codomain. Same numel constraint.

TYPE: SetObject DEFAULT: None

RETURNS DESCRIPTION
ObservedMorphism

The reshape of self into the requested type.

Source code in src/quivers/core/morphisms.py
def refactor(self, *, domain=None, codomain=None) -> "TransformedMorphism":
    """Switch between flat and product views of this morphism.

    Given a morphism ``f : A -> B`` whose tensor storage has
    total numel matching the requested ``domain`` / ``codomain``
    objects, return an equivalent morphism ``f' : A' -> B'``
    whose tensor is the same data reshaped to the new factored
    layout. ``A'`` and ``B'`` must be isomorphic to ``A`` and
    ``B`` as objects — same cardinality, possibly different
    product structure.

    Categorically this is the action of an object iso
    ``B ≅ B'`` on the morphism's tensor. Semantically it is
    a no-op; presentation only.

    Parameters
    ----------
    domain : SetObject, optional
        New domain. Must have ``prod(shape) == prod(self.domain.shape)``.
    codomain : SetObject, optional
        New codomain. Same numel constraint.

    Returns
    -------
    ObservedMorphism
        The reshape of ``self`` into the requested type.
    """
    _require_finite(self)
    new_domain = domain if domain is not None else self._domain
    new_codomain = codomain if codomain is not None else self._codomain

    def _numel(shape) -> int:
        n = 1
        for s in shape:
            n *= int(s)
        return n

    if _numel(new_domain.shape) != _numel(self._domain.shape):
        raise ValueError(
            f"refactor: domain numel {_numel(new_domain.shape)} "
            f"does not match {_numel(self._domain.shape)} for "
            f"{self._domain!r} -> {new_domain!r}"
        )
    if _numel(new_codomain.shape) != _numel(self._codomain.shape):
        raise ValueError(
            f"refactor: codomain numel "
            f"{_numel(new_codomain.shape)} does not match "
            f"{_numel(self._codomain.shape)} for "
            f"{self._codomain!r} -> {new_codomain!r}"
        )
    target_shape = tuple(new_domain.shape) + tuple(new_codomain.shape)

    def _transform(t: torch.Tensor, _shape=target_shape) -> torch.Tensor:
        return t.reshape(_shape)

    return TransformedMorphism(
        self,
        _transform,
        new_domain,
        new_codomain,
        algebra=self._algebra,
    )

marginalize

marginalize(*sets: SetObject) -> MarginalizedMorphism

Marginalize (join-reduce) over codomain components.

The codomain must be a ProductSet containing the sets to marginalize over. The result has a codomain with those components removed. Uses the algebra's join operation.

PARAMETER DESCRIPTION
*sets

Codomain components to marginalize over.

TYPE: SetObject DEFAULT: ()

RETURNS DESCRIPTION
MarginalizedMorphism

The marginalized morphism.

Source code in src/quivers/core/morphisms.py
def marginalize(self, *sets: SetObject) -> MarginalizedMorphism:
    """Marginalize (join-reduce) over codomain components.

    The codomain must be a ProductSet containing the sets to
    marginalize over. The result has a codomain with those
    components removed. Uses the algebra's join operation.

    Parameters
    ----------
    *sets : SetObject
        Codomain components to marginalize over.

    Returns
    -------
    MarginalizedMorphism
        The marginalized morphism.
    """
    return MarginalizedMorphism(self, sets)

trace

trace(obj: SetObject) -> 'TransformedMorphism'

Trace of self : X ⊗ A → A ⊗ Y along obj = A, producing a morphism X → Y.

Concretely the trace contracts the A axis on the domain side with the A axis on the codomain side via the algebra's tensor_op and then joins (self._algebra.join) over the contracted axis. This is the categorical trace tr_A(f) : X → Y = (ε_A ⊗ id_Y) ∘ (id_A ⊗ f) ∘ (η_A ⊗ id_X).

The morphism's domain must be a product set whose first component is obj; the codomain must be a product set whose first component is obj. If this is not the case a TypeError is raised — the user should call ProductSet.swap style helpers (not yet exposed) to reorder axes before tracing.

PARAMETER DESCRIPTION
obj

The object to contract over. Must appear at the start of both the domain and codomain product sets.

TYPE: SetObject

RETURNS DESCRIPTION
ObservedMorphism

Morphism X → Y (the trace).

Source code in src/quivers/core/morphisms.py
def trace(self, obj: SetObject) -> "TransformedMorphism":
    """Trace of ``self : X ⊗ A → A ⊗ Y`` along ``obj = A``,
    producing a morphism ``X → Y``.

    Concretely the trace contracts the A axis on the domain
    side with the A axis on the codomain side via the algebra's
    ``tensor_op`` and then joins (``self._algebra.join``) over
    the contracted axis. This is the categorical trace
    ``tr_A(f) : X → Y = (ε_A ⊗ id_Y) ∘ (id_A ⊗ f) ∘ (η_A ⊗ id_X)``.

    The morphism's domain must be a product set whose first
    component is ``obj``; the codomain must be a product set
    whose first component is ``obj``. If this is not the case
    a TypeError is raised — the user should call
    `ProductSet.swap` style helpers (not yet exposed) to
    reorder axes before tracing.

    Parameters
    ----------
    obj : SetObject
        The object to contract over. Must appear at the start
        of both the domain and codomain product sets.

    Returns
    -------
    ObservedMorphism
        Morphism ``X → Y`` (the trace).
    """
    _require_finite(self)
    if not isinstance(self._domain, ProductSet) or not isinstance(
        self._codomain, ProductSet
    ):
        raise TypeError(
            "trace: requires the morphism's domain and codomain "
            "to both be ProductSets with the contracted object "
            f"at the front; got domain={self._domain!r}, "
            f"codomain={self._codomain!r}"
        )
    if self._domain.components[0] != obj:
        raise TypeError(
            f"trace: domain's first component {self._domain.components[0]!r} "
            f"!= contraction object {obj!r}"
        )
    if self._codomain.components[0] != obj:
        raise TypeError(
            f"trace: codomain's first component {self._codomain.components[0]!r} "
            f"!= contraction object {obj!r}"
        )
    d_ndim = len(self._domain.shape)
    a_ndim = len(obj.shape)
    algebra = self._algebra

    def _transform(
        t: torch.Tensor, _d_ndim=d_ndim, _a_ndim=a_ndim, _q=algebra
    ) -> torch.Tensor:
        # Domain axes: 0..d_ndim-1 with A at 0..a_ndim-1.
        # Codomain axes: d_ndim..d_ndim+c_ndim-1 with A at
        # d_ndim..d_ndim+a_ndim-1.  Take diagonals pairing each
        # A axis on the domain side with the corresponding one
        # on the codomain side, then join along the surviving
        # diagonal axes.
        out = t
        for k in range(_a_ndim):
            out = torch.diagonal(out, dim1=0, dim2=_d_ndim - k)
        trailing = tuple(range(out.dim() - _a_ndim, out.dim()))
        return _q.join(out, dim=trailing)

    # Recover the X and Y product sets.
    x_components = tuple(self._domain.components[1:])
    y_components = tuple(self._codomain.components[1:])
    if len(x_components) == 1:
        new_domain = x_components[0]
    else:
        new_domain = ProductSet(components=x_components)
    if len(y_components) == 1:
        new_codomain = y_components[0]
    else:
        new_codomain = ProductSet(components=y_components)
    return TransformedMorphism(
        self, _transform, new_domain, new_codomain, algebra=self._algebra
    )

FiniteMorphism

FiniteMorphism(domain: SetObject, codomain: SetObject, algebra: Algebra | None = None)

Bases: Morphism

Morphism with a finite tensor in the carrier of its algebra.

Source code in src/quivers/core/morphisms.py
def __init__(
    self, domain: SetObject, codomain: SetObject, algebra: Algebra | None = None
) -> None:
    self._domain = domain
    self._codomain = codomain
    self._algebra = algebra if algebra is not None else PRODUCT_FUZZY

tensor abstractmethod property

tensor: Tensor

Materialize the morphism as a tensor in the algebra's carrier.

TransformedMorphism

TransformedMorphism(source: 'Morphism', transform, domain: SetObject, codomain: SetObject, algebra: Algebra | None = None)

Bases: FiniteMorphism

A morphism whose tensor is a transformation of a source morphism's tensor, recomputed on each tensor access.

The source morphism is registered as a submodule so self.module().parameters() includes the source's learnable parameters; the transform is applied lazily, so each backward through a fresh .tensor access gets its own autograd graph and multi-step optimisation propagates gradients correctly.

PARAMETER DESCRIPTION
source

Underlying morphism whose tensor feeds the transform.

TYPE: Morphism

transform

Pure function applied to source.tensor to produce the new tensor. Must depend on source only through the tensor; any additional context (e.g. the source morphism for shape resolution) must be captured by closure.

TYPE: Callable[[Tensor], Tensor]

domain

Target domain (may differ from source.domain for shape-aware transformations like the dagger or BayesInvert).

TYPE: SetObject

codomain

Target codomain.

TYPE: SetObject

algebra

Target algebra. Defaults to the source's algebra.

TYPE: Algebra or None DEFAULT: None

Source code in src/quivers/core/morphisms.py
def __init__(
    self,
    source: "Morphism",
    transform,  # Callable[[torch.Tensor], torch.Tensor]
    domain: SetObject,
    codomain: SetObject,
    algebra: Algebra | None = None,
) -> None:
    source = _require_finite(source)
    super().__init__(
        domain,
        codomain,
        algebra=algebra if algebra is not None else source.algebra,
    )
    self._source = source
    self._transform = transform
    self._module = _SourcedModule(source.module())

source property

source: 'Morphism'

The underlying morphism feeding this transform.

ObservedMorphism

ObservedMorphism(domain: SetObject, codomain: SetObject, data: Tensor, algebra: Algebra | None = None)

Bases: FiniteMorphism

A morphism with a fixed (non-learnable) tensor.

PARAMETER DESCRIPTION
domain

Source object.

TYPE: SetObject

codomain

Target object.

TYPE: SetObject

data

Fixed tensor of shape (*domain.shape, *codomain.shape).

TYPE: Tensor

algebra

The enrichment algebra. Defaults to PRODUCT_FUZZY.

TYPE: Algebra or None DEFAULT: None

Source code in src/quivers/core/morphisms.py
def __init__(
    self,
    domain: SetObject,
    codomain: SetObject,
    data: torch.Tensor,
    algebra: Algebra | None = None,
) -> None:
    super().__init__(domain, codomain, algebra=algebra)
    expected = self.tensor_shape
    if data.shape != expected:
        raise ValueError(
            f"data shape {data.shape} does not match expected {expected}"
        )
    self._module = _MorphismModule()
    self._module.register_buffer("data", data)

LatentMorphism

LatentMorphism(domain: SetObject, codomain: SetObject, init_scale: float = 0.5, algebra: Algebra | None = None)

Bases: FiniteMorphism

A learnable morphism backed by an nn.Parameter.

Stores unconstrained real-valued parameters and applies sigmoid to produce [0,1]-valued fuzzy relation entries.

PARAMETER DESCRIPTION
domain

Source object.

TYPE: SetObject

codomain

Target object.

TYPE: SetObject

init_scale

Standard deviation of the normal initialization for the unconstrained parameters. Default 0.5 (sigmoid maps this to roughly uniform over [0.3, 0.7]).

TYPE: float DEFAULT: 0.5

algebra

The enrichment algebra. Defaults to PRODUCT_FUZZY.

TYPE: Algebra or None DEFAULT: None

Source code in src/quivers/core/morphisms.py
def __init__(
    self,
    domain: SetObject,
    codomain: SetObject,
    init_scale: float = 0.5,
    algebra: Algebra | None = None,
) -> None:
    super().__init__(domain, codomain, algebra=algebra)
    shape = self.tensor_shape
    self._module = _MorphismModule()
    raw = nn.Parameter(torch.randn(shape) * init_scale)
    self._module.register_parameter("raw", raw)

raw property

raw: Parameter

Unconstrained parameter tensor.

tensor property

tensor: Tensor

Sigmoid-constrained tensor with values in (0, 1).

ComposedMorphism

ComposedMorphism(left: Morphism, right: Morphism)

Bases: FiniteMorphism

V-enriched composition of two morphisms.

Given left: A -> B and right: B -> C, produces A -> C by contracting over B using the algebra's compose method.

PARAMETER DESCRIPTION
left

Left morphism (applied first).

TYPE: Morphism

right

Right morphism (applied second).

TYPE: Morphism

Source code in src/quivers/core/morphisms.py
def __init__(self, left: Morphism, right: Morphism) -> None:
    left = _require_finite(left)
    right = _require_finite(right)
    n_contract = left.codomain.ndim
    super().__init__(left.domain, right.codomain, algebra=left._algebra)
    self._left = left
    self._right = right
    self._n_contract = n_contract

left property

left: Morphism

Left (first) morphism.

right property

right: Morphism

Right (second) morphism.

ProductMorphism

ProductMorphism(left: Morphism, right: Morphism)

Bases: FiniteMorphism

Tensor (parallel) product of two morphisms.

Given left: A -> B and right: C -> D, produces A×C -> B×D. The tensor is the outer product of the two component tensors via the algebra's tensor_op.

PARAMETER DESCRIPTION
left

Left morphism.

TYPE: Morphism

right

Right morphism.

TYPE: Morphism

Source code in src/quivers/core/morphisms.py
def __init__(self, left: Morphism, right: Morphism) -> None:
    left = _require_finite(left)
    right = _require_finite(right)
    domain = ProductSet(components=(left.domain, right.domain))
    codomain = ProductSet(components=(left.codomain, right.codomain))
    super().__init__(domain, codomain, algebra=left._algebra)
    self._left = left
    self._right = right

MarginalizedMorphism

MarginalizedMorphism(inner: Morphism, sets_to_marginalize: tuple[SetObject, ...] | list[SetObject])

Bases: FiniteMorphism

Morphism with codomain dimensions marginalized via the algebra's join.

Given an inner morphism A -> B × C and a set B to marginalize, produces A -> C by join-reduction over B's dimensions.

PARAMETER DESCRIPTION
inner

The morphism to marginalize.

TYPE: Morphism

sets_to_marginalize

Codomain components to marginalize over.

TYPE: tuple of SetObject

Source code in src/quivers/core/morphisms.py
def __init__(
    self,
    inner: Morphism,
    sets_to_marginalize: tuple[SetObject, ...] | list[SetObject],
) -> None:
    inner = _require_finite(inner)
    codomain = inner.codomain
    sets_to_marginalize = tuple(sets_to_marginalize)
    if not isinstance(codomain, ProductSet):
        raise TypeError(
            f"can only marginalize over ProductSet codomain, got {type(codomain).__name__}"
        )
    n_domain = inner.domain.ndim
    remaining_components: list[SetObject] = []
    dims_to_reduce: list[int] = []
    offset = n_domain
    for component in codomain.components:
        if component in sets_to_marginalize:
            for d in range(component.ndim):
                dims_to_reduce.append(offset + d)
        else:
            remaining_components.append(component)
        offset += component.ndim
    if not dims_to_reduce:
        raise ValueError("none of the specified sets found in codomain components")
    if len(remaining_components) == 0:
        raise ValueError("cannot marginalize all codomain components")
    elif len(remaining_components) == 1:
        new_codomain = remaining_components[0]
    else:
        new_codomain = ProductSet(components=tuple(remaining_components))
    super().__init__(inner.domain, new_codomain, algebra=inner._algebra)
    self._inner = inner
    self._dims_to_reduce = tuple(dims_to_reduce)

FunctorMorphism

FunctorMorphism(functor: Functor, inner: Morphism, domain: SetObject, codomain: SetObject)

Bases: FiniteMorphism

Lazy image of a morphism under a functor.

Recomputes the tensor on each access from the inner morphism, preserving gradient flow through the functor's map_tensor method. No additional parameters beyond those of the inner morphism.

PARAMETER DESCRIPTION
functor

The functor that produced this morphism.

TYPE: Functor

inner

The original morphism being mapped.

TYPE: Morphism

domain

The image of the inner morphism's domain under the functor.

TYPE: SetObject

codomain

The image of the inner morphism's codomain under the functor.

TYPE: SetObject

Source code in src/quivers/core/morphisms.py
def __init__(
    self, functor: Functor, inner: Morphism, domain: SetObject, codomain: SetObject
) -> None:
    inner = _require_finite(inner)
    super().__init__(domain, codomain, algebra=inner._algebra)
    self._functor = functor
    self._inner = inner

inner property

inner: Morphism

The original morphism being mapped.

RepeatMorphism

RepeatMorphism(inner: Morphism, n: int = 1)

Bases: FiniteMorphism

Runtime-variable iterated composition (matrix power).

Wraps an endomorphism f : X -> X and computes f^n at runtime, where n can be changed between calls. Uses repeated squaring for O(log n) algebra compositions.

For an endomorphism T : S -> S under an algebra, T^n is the n-fold Kleisli composition. Under the product_fuzzy algebra with stochastic matrices, this is standard matrix power.

PARAMETER DESCRIPTION
inner

An endomorphism (domain must equal codomain).

TYPE: Morphism

n

Initial number of repetitions (default 1). Can be changed later via the n_steps property.

TYPE: int DEFAULT: 1

RAISES DESCRIPTION
TypeError

If the inner morphism is not an endomorphism.

ValueError

If n < 1.

Examples:

>>> T = morphism(S, S)
>>> rep = RepeatMorphism(T, n=5)
>>> rep.tensor  # computes T^5
>>> rep.n_steps = 10
>>> rep.tensor  # now computes T^10
Source code in src/quivers/core/morphisms.py
def __init__(self, inner: Morphism, n: int = 1) -> None:
    inner = _require_finite(inner)
    if inner.domain != inner.codomain:
        raise TypeError(
            f"repeat requires an endomorphism, got {inner.domain!r} -> {inner.codomain!r}"
        )
    if n < 1:
        raise ValueError(f"n must be >= 1, got {n}")
    super().__init__(inner.domain, inner.codomain, algebra=inner._algebra)
    self._inner = inner
    self._n = n
    self._n_contract = inner.codomain.ndim

inner property

inner: Morphism

The base endomorphism.

n_steps property writable

n_steps: int

Number of iterated compositions.

tensor property

tensor: Tensor

Compute the n-fold composition via repeated squaring.

RETURNS DESCRIPTION
Tensor

The tensor for f^n, same shape as the inner morphism.

CurriedMorphism

CurriedMorphism(inner: Morphism, direction: str = 'right')

Bases: FiniteMorphism

The curry of a morphism out of a product.

V-matrices form a compact closed category under the cartesian product of sets, whose internal hom [Y, Z] is the product set Y × Z. Currying is the bijection

Hom(X × Y, Z) ≅ Hom(X, [Y, Z])          (``direction='right'``)
Hom(X × Y, Z) ≅ Hom(Y, [X, Z])          (``direction='left'``)

of the closed structure [Mac Lane (1998), §IV.6]: the curried morphism has the same entries as f, re-indexed so that curry(f)[x, (y, z)] = f[(x, y), z] (right) or curry(f)[y, (x, z)] = f[(x, y), z] (left). Its declared domain and codomain match its tensor, and UncurriedMorphism inverts it.

PARAMETER DESCRIPTION
inner

The morphism f : X × Y → Z. With more than two domain factors, right moves the last factor into the codomain and left the first.

TYPE: Morphism

direction

Which factor is kept as the domain.

TYPE: Literal['right', 'left'] DEFAULT: 'right'

RAISES DESCRIPTION
ValueError

If direction is neither 'right' nor 'left'.

TypeError

If inner.domain does not factor as a product.

References

Mac Lane, S. (1998). Categories for the Working Mathematician (2nd ed.). Springer. doi:10.1007/978-1-4757-4721-8

Source code in src/quivers/core/morphisms.py
def __init__(self, inner: Morphism, direction: str = "right") -> None:
    inner = _require_finite(inner)
    if direction not in ("right", "left"):
        raise ValueError(f"direction must be 'right' or 'left', got {direction!r}")
    if not isinstance(inner.domain, ProductSet) or len(inner.domain.components) < 2:
        raise TypeError(
            f"curry requires inner morphism with product domain, "
            f"got {type(inner.domain).__name__}"
        )
    components = inner.domain.components
    if direction == "right":
        kept = components[:-1]
        absorbed = components[-1]
    else:
        kept = components[1:]
        absorbed = components[0]
    new_domain = kept[0] if len(kept) == 1 else ProductSet(components=kept)
    new_codomain = ProductSet(components=(absorbed, inner.codomain))
    super().__init__(new_domain, new_codomain, algebra=inner._algebra)
    self._inner = inner
    self._direction = direction
    # Axis permutation from the inner tensor (dom..., cod...) to
    # (kept..., absorbed..., cod...).
    n_absorbed = absorbed.ndim
    n_dom = inner.domain.ndim
    n_cod = inner.codomain.ndim
    if direction == "right":
        self._perm = list(range(n_dom + n_cod))
    else:
        self._perm = (
            list(range(n_absorbed, n_dom))
            + list(range(n_absorbed))
            + list(range(n_dom, n_dom + n_cod))
        )

inner property

inner: Morphism

The uncurried morphism f.

direction property

direction: str

'right' or 'left'.

tensor property

tensor: Tensor

The inner tensor re-indexed to (domain..., codomain...).

UncurriedMorphism

UncurriedMorphism(inner: Morphism, direction: str = 'right')

Bases: FiniteMorphism

The uncurry of a morphism into a product, inverse to CurriedMorphism.

For g : X → [Y, Z] = Y × Z, direction='right' gives X × Y → Z with uncurry(g)[(x, y), z] = g[x, (y, z)], and direction='left' gives Y × X → Z with uncurry(g)[(y, x), z] = g[x, (y, z)]. Hence UncurriedMorphism(CurriedMorphism(f, d), d) has the domain, codomain and tensor of f in both directions.

PARAMETER DESCRIPTION
inner

The morphism g : X → Y × Z whose codomain is a binary product.

TYPE: Morphism

direction

Where the first codomain factor is placed in the new domain: last (right) or first (left).

TYPE: Literal['right', 'left'] DEFAULT: 'right'

RAISES DESCRIPTION
ValueError

If direction is neither 'right' nor 'left'.

TypeError

If inner.codomain is not a binary product.

Source code in src/quivers/core/morphisms.py
def __init__(self, inner: Morphism, direction: str = "right") -> None:
    inner = _require_finite(inner)
    if direction not in ("right", "left"):
        raise ValueError(f"direction must be 'right' or 'left', got {direction!r}")
    cod = inner.codomain
    if not isinstance(cod, ProductSet) or len(cod.components) != 2:
        raise TypeError(
            "uncurry requires a morphism into a binary product [Y, Z], got "
            f"{type(cod).__name__}"
        )
    absorbed, result = cod.components
    dom = inner.domain
    dom_parts = dom.components if isinstance(dom, ProductSet) else (dom,)
    if direction == "right":
        new_domain = ProductSet(components=(*dom_parts, absorbed))
    else:
        new_domain = ProductSet(components=(absorbed, *dom_parts))
    super().__init__(new_domain, result, algebra=inner._algebra)
    self._inner = inner
    self._direction = direction
    n_dom = dom.ndim
    n_abs = absorbed.ndim
    n_res = result.ndim
    if direction == "right":
        self._perm = list(range(n_dom + n_abs + n_res))
    else:
        self._perm = (
            list(range(n_dom, n_dom + n_abs))
            + list(range(n_dom))
            + list(range(n_dom + n_abs, n_dom + n_abs + n_res))
        )

inner property

inner: Morphism

The curried morphism g.

direction property

direction: str

'right' or 'left'.

tensor property

tensor: Tensor

The inner tensor re-indexed to (domain..., codomain...).

morphism

morphism(domain: SetObject, codomain: SetObject, init_scale: float = 0.5, algebra: Algebra | None = None) -> LatentMorphism

Create a latent (learnable) morphism.

PARAMETER DESCRIPTION
domain

Source object.

TYPE: SetObject

codomain

Target object.

TYPE: SetObject

init_scale

Initialization scale for unconstrained parameters.

TYPE: float DEFAULT: 0.5

algebra

The enrichment algebra. Defaults to PRODUCT_FUZZY.

TYPE: Algebra or None DEFAULT: None

RETURNS DESCRIPTION
LatentMorphism

A learnable morphism.

Source code in src/quivers/core/morphisms.py
def morphism(
    domain: SetObject,
    codomain: SetObject,
    init_scale: float = 0.5,
    algebra: Algebra | None = None,
) -> LatentMorphism:
    """Create a latent (learnable) morphism.

    Parameters
    ----------
    domain : SetObject
        Source object.
    codomain : SetObject
        Target object.
    init_scale : float
        Initialization scale for unconstrained parameters.
    algebra : Algebra or None
        The enrichment algebra. Defaults to PRODUCT_FUZZY.

    Returns
    -------
    LatentMorphism
        A learnable morphism.
    """
    return LatentMorphism(domain, codomain, init_scale=init_scale, algebra=algebra)

observed

observed(domain: SetObject, codomain: SetObject, data: Tensor, algebra: Algebra | None = None) -> ObservedMorphism

Create an observed (fixed) morphism.

PARAMETER DESCRIPTION
domain

Source object.

TYPE: SetObject

codomain

Target object.

TYPE: SetObject

data

Fixed tensor.

TYPE: Tensor

algebra

The enrichment algebra. Defaults to PRODUCT_FUZZY.

TYPE: Algebra or None DEFAULT: None

RETURNS DESCRIPTION
ObservedMorphism

A fixed morphism.

Source code in src/quivers/core/morphisms.py
def observed(
    domain: SetObject,
    codomain: SetObject,
    data: torch.Tensor,
    algebra: Algebra | None = None,
) -> ObservedMorphism:
    """Create an observed (fixed) morphism.

    Parameters
    ----------
    domain : SetObject
        Source object.
    codomain : SetObject
        Target object.
    data : torch.Tensor
        Fixed tensor.
    algebra : Algebra or None
        The enrichment algebra. Defaults to PRODUCT_FUZZY.

    Returns
    -------
    ObservedMorphism
        A fixed morphism.
    """
    return ObservedMorphism(domain, codomain, data, algebra=algebra)

identity

identity(obj: SetObject, algebra: Algebra | None = None) -> ObservedMorphism

Create the identity morphism on an object.

Returns an observed morphism obj -> obj whose tensor is the identity: unit on the diagonal, zero elsewhere.

PARAMETER DESCRIPTION
obj

The object to create an identity for.

TYPE: SetObject

algebra

The enrichment algebra. Defaults to PRODUCT_FUZZY.

TYPE: Algebra or None DEFAULT: None

RETURNS DESCRIPTION
ObservedMorphism

The identity morphism.

Source code in src/quivers/core/morphisms.py
def identity(obj: SetObject, algebra: Algebra | None = None) -> ObservedMorphism:
    """Create the identity morphism on an object.

    Returns an observed morphism obj -> obj whose tensor is the
    identity: unit on the diagonal, zero elsewhere.

    Parameters
    ----------
    obj : SetObject
        The object to create an identity for.
    algebra : Algebra or None
        The enrichment algebra. Defaults to PRODUCT_FUZZY.

    Returns
    -------
    ObservedMorphism
        The identity morphism.
    """
    q = algebra if algebra is not None else PRODUCT_FUZZY
    data = q.identity_tensor(obj.shape)
    return ObservedMorphism(obj, obj, data, algebra=q)

as_torch_module

as_torch_module(m: object) -> Module

Coerce a Morphism into an nn.Module for parameter tracking at a binding site.

The adapter draws the line between the categorical morphism hierarchy (backend-agnostic; lives in quivers.core) and PyTorch's parameter-container infrastructure. Every site that needs to register a morphism's parameters with a parent nn.Module (the MonadicProgram step list, the submodule list of a FanMorphism / StackMorphism composite, a parametric-program parameter slot bound to a morphism) calls this function once and stores the result.

PARAMETER DESCRIPTION
m

The morphism (or other object) to wrap. Accepted forms:

  • Already an nn.Module — returned unchanged so a continuous MonadicProgram step can pass its ContinuousMorphism straight through.
  • A Morphism with a .module() method (every subclass of Morphism defined in this file implements it) — the result of m.module() is returned. The morphism object itself is attached to the wrapper under the synthetic attribute _morphism so downstream code that needs the categorical object (e.g. to compute tensor or apply a Functor) can recover it without rebuilding.

TYPE: object

RETURNS DESCRIPTION
Module

A module whose parameters / buffers are exactly the morphism's, suitable for add_module on a parent.

RAISES DESCRIPTION
TypeError

m is neither an nn.Module nor a Morphism-shaped object with a .module() method.

Source code in src/quivers/core/morphisms.py
def as_torch_module(m: object) -> nn.Module:
    """Coerce a Morphism into an `nn.Module` for parameter
    tracking at a binding site.

    The adapter draws the line between the categorical morphism
    hierarchy (backend-agnostic; lives in `quivers.core`) and
    PyTorch's parameter-container infrastructure. Every site that
    needs to register a morphism's parameters with a parent
    `nn.Module` (the `MonadicProgram` step list, the
    submodule list of a `FanMorphism` / `StackMorphism`
    composite, a parametric-program parameter slot bound to a
    morphism) calls this function once and stores the result.

    Parameters
    ----------
    m : object
        The morphism (or other object) to wrap. Accepted forms:

        * Already an `nn.Module` — returned unchanged so a
          continuous `MonadicProgram` step can pass its
          `ContinuousMorphism` straight through.
        * A `Morphism` with a ``.module()`` method (every
          subclass of `Morphism` defined in this file
          implements it) — the result of ``m.module()`` is
          returned. The morphism object itself is attached to the
          wrapper under the synthetic attribute ``_morphism`` so
          downstream code that needs the categorical object (e.g.
          to compute ``tensor`` or apply a ``Functor``) can recover
          it without rebuilding.

    Returns
    -------
    nn.Module
        A module whose parameters / buffers are exactly the
        morphism's, suitable for ``add_module`` on a parent.

    Raises
    ------
    TypeError
        ``m`` is neither an `nn.Module` nor a
        `Morphism`-shaped object with a ``.module()`` method.
    """
    if isinstance(m, nn.Module):
        return m
    if isinstance(m, Morphism):
        wrapper = m.module()
        if not isinstance(wrapper, nn.Module):
            raise TypeError(
                f"{type(m).__name__}.module() returned "
                f"{type(wrapper).__name__}; expected nn.Module"
            )
        # Attach the original morphism on the wrapper so downstream
        # code that needs the categorical object can recover it
        # without rebuilding from the wrapped parameters.
        wrapper._morphism = m  # type: ignore[attr-defined]
        return wrapper
    raise TypeError(
        f"as_torch_module: cannot adapt {type(m).__name__} to "
        f"nn.Module; expected an nn.Module or a Morphism with a "
        f".module() method"
    )

extract_morphism

extract_morphism(module: Module) -> Morphism | None

Recover the Morphism previously bound through as_torch_module.

Returns the categorical morphism stored on the wrapper, or None if the module was registered directly (i.e. was already an nn.Module subclass) and thus has no separate categorical object attached.

PARAMETER DESCRIPTION
module

A module bound into a parameter-tracking context.

TYPE: Module

RETURNS DESCRIPTION
Morphism or None

The wrapped morphism, or None when module wraps none.

Source code in src/quivers/core/morphisms.py
def extract_morphism(module: nn.Module) -> Morphism | None:
    """Recover the `Morphism` previously bound through
    `as_torch_module`.

    Returns the categorical morphism stored on the wrapper, or
    ``None`` if the module was registered directly (i.e. was
    already an `nn.Module` subclass) and thus has no
    separate categorical object attached.

    Parameters
    ----------
    module : nn.Module
        A module bound into a parameter-tracking context.

    Returns
    -------
    Morphism or None
        The wrapped morphism, or ``None`` when ``module`` wraps none.
    """
    return getattr(module, "_morphism", None)

cup

cup(obj: SetObject, algebra: Algebra | None = None) -> ObservedMorphism

The compact-closed unit η_A : I → A ⊗ A.

For finite-set objects with their natural product, η_A is the diagonal: every entry (a, a) carries the algebra's monoidal unit and the off-diagonal entries carry the join unit (zero). The Kronecker-like tensor produced is the identity morphism's tensor reshaped from (*A.shape, *A.shape) to (1, *A.shape, *A.shape) so that the leading axis is the singleton input I.

Categorically the cup and the trivial-domain identity satisfy ε ∘ (id ⊗ η) = id; the snake equation that makes V-Cat compact-closed.

PARAMETER DESCRIPTION
obj

The object whose dual is being introduced. Every algebra ships an identity tensor; this morphism reshapes it as a Kleisli arrow from the singleton domain.

TYPE: SetObject

algebra

Override the default (ProductFuzzyAlgebra) algebra.

TYPE: Algebra DEFAULT: None

RETURNS DESCRIPTION
ObservedMorphism

Morphism I → A ⊗ A whose tensor is the diagonal of the target.

Source code in src/quivers/core/morphisms.py
def cup(obj: SetObject, algebra: Algebra | None = None) -> ObservedMorphism:
    """The compact-closed unit ``η_A : I → A ⊗ A``.

    For finite-set objects with their natural product, ``η_A`` is
    the *diagonal*: every entry ``(a, a)`` carries the algebra's
    monoidal unit and the off-diagonal entries carry the join unit
    (``zero``). The Kronecker-like tensor produced is the identity
    morphism's tensor reshaped from ``(*A.shape, *A.shape)`` to
    ``(1, *A.shape, *A.shape)`` so that the leading axis is the
    singleton input ``I``.

    Categorically the cup and the trivial-domain identity satisfy
    ``ε ∘ (id ⊗ η) = id``; the snake equation that makes V-Cat
    compact-closed.

    Parameters
    ----------
    obj : SetObject
        The object whose dual is being introduced. Every algebra
        ships an identity tensor; this morphism reshapes it as a
        Kleisli arrow from the singleton domain.
    algebra : Algebra, optional
        Override the default (ProductFuzzyAlgebra) algebra.

    Returns
    -------
    ObservedMorphism
        Morphism ``I → A ⊗ A`` whose tensor is the diagonal of the
        target.
    """
    q = algebra if algebra is not None else PRODUCT_FUZZY
    diag = q.identity_tensor(obj.shape)
    # Wrap in a leading singleton axis so the morphism's domain is
    # the unit object I (the singleton finite set).
    I = FinSet(name="1", cardinality=1)
    cod = ProductSet(components=(obj, obj))
    return ObservedMorphism(I, cod, diag.unsqueeze(0), algebra=q)

cap

cap(obj: SetObject, algebra: Algebra | None = None) -> ObservedMorphism

The compact-closed counit ε_A : A ⊗ A → I.

The dual of cup. The tensor is the diagonal flattened into (*A.shape, *A.shape, 1) so the trailing axis is the unit codomain I.

PARAMETER DESCRIPTION
obj

The object A.

TYPE: SetObject

algebra

Override the default (ProductFuzzyAlgebra) algebra.

TYPE: Algebra DEFAULT: None

RETURNS DESCRIPTION
ObservedMorphism

Morphism A ⊗ A → I whose tensor is the diagonal of the source.

Source code in src/quivers/core/morphisms.py
def cap(obj: SetObject, algebra: Algebra | None = None) -> ObservedMorphism:
    """The compact-closed counit ``ε_A : A ⊗ A → I``.

    The dual of `cup`. The tensor is the diagonal flattened
    into ``(*A.shape, *A.shape, 1)`` so the trailing axis is the
    unit codomain ``I``.

    Parameters
    ----------
    obj : SetObject
        The object ``A``.
    algebra : Algebra, optional
        Override the default (ProductFuzzyAlgebra) algebra.

    Returns
    -------
    ObservedMorphism
        Morphism ``A ⊗ A → I`` whose tensor is the diagonal of the
        source.
    """
    q = algebra if algebra is not None else PRODUCT_FUZZY
    diag = q.identity_tensor(obj.shape)
    I = FinSet(name="1", cardinality=1)
    dom = ProductSet(components=(obj, obj))
    return ObservedMorphism(dom, I, diag.unsqueeze(-1), algebra=q)

Sparse string relations

A RationalRelation assigns a weight to each tuple of words on its ordered tapes. Its topology identifies arcs by position in the arc table, so parallel arcs contribute separately, even when they read the same symbols and use the same weight slot. Initial and final states have explicit weights. Every slot must belong to the declared semiring carrier. The relation checks the current weight vector each time it reads the vector for evaluation. The QIEC codec records the topology and weight identities for later runtime binding.

For a fixed tuple of \(k\) words, a query state consists of a machine state and \(k\) positions in the observed words. An arc labeled with a symbol on a tape advances that tape only if the symbol matches. An epsilon label leaves the position unchanged. Every accepted original walk has a unique lift to this graph because its arc sequence determines all positions. Every accepting walk in the graph likewise projects to an original walk that realizes the observed tuple.

The plan keeps only states on a walk from a weighted initial state to a weighted final state that has consumed every word. The level of a state is the length of the longest path to it in this graph. All predecessors of a state lie in earlier levels. In each level, the weight of reaching a state is the sum of its initial weight, if present, and one product per incoming arc. Each product multiplies the weight of reaching the source by the arc weight. By induction on the levels and distributivity, these terms account for every accepting walk when the final sum multiplies each completed state's weight by its final weight. A cycle in this graph would have to leave every position unchanged. By default, a cycle in the surviving graph raises ProductiveEpsilonCycleError.

An index assigns each arc to its first non-epsilon label or to the all-epsilon group for its source state. With \(E\) arcs on \(k\) tapes, validating and sorting the indexed arc labels takes at most \(O(k E \log(E+1))\) operations, in addition to reading the boundary records and weight-slot names. For \(S\) reached configurations and \(A\) candidate arcs inspected, building a query takes \(O(k(S + A))\) operations after reading the words and the initial states, with \(O(kS + A)\) space. Within a level, incoming rows are grouped by their length rounded up to a power of two. Each padded row has fewer than twice as many entries as its unpadded row. The evaluator forms one vector of outgoing products per level and splits it into chunks by destination level. Thus the forward pass uses time and space linear in the active state and arc counts and in the number of initial and final marks. It uses one semiring join for each width greater than one present in a level. These bounds count scalar semiring operations and entries. Computing the weight vector has a separate cost, and validation tests membership once per weight slot. A bounded tensor restriction reads and validates the vector once for the whole table. It repeats construction for each entry, subject to the explicit tensor size limit and optional state and arc budgets.

Productive cyclic components

RationalRelation.query(words, max_closure_size=n) admits productive cyclic components. Every accepting walk visits a sequence of strongly connected components in topological order. For each visit, its first state, its last state and the walk between them determine its contribution within that component. A local star sums those internal walks for each entry and exit pair, including the empty walk at each state. The packed pass multiplies these weights with the weights of edges between components and of the boundary marks.

Each component uses a matrix with one direct arc per ordered state pair. Each additional parallel occurrence passes through its own auxiliary vertex, with the original weight on the first edge and the unit on the second. This preserves the individual weights through the solver's convergence check. max_closure_size bounds the order of every matrix, including its auxiliary vertices, and QueryWork.closure_sizes reports the orders the plan will use. For component matrix orders \(m_i\), splitting and packing adds at most \(O(\sum_i m_i^2)\) work and storage to the observation graph. The shipped closures take \(O(\sum_i m_i^3)\) algebra operations, plus any exact or enclosed numerical decisions made by Star.

Scoring uses floating-point tensors and requires established semiring laws and the least-solution law of Star. Divergence and numerical uncertainty in a local matrix raise DivergentClosureError and UndecidedClosureError, respectively. An unusable closure weight also raises UndecidedClosureError. The structural plan retains zero-weight occurrences and rechecks the current weights each time it scores a query.

Binary composition at fixed words

ComposedRelation(left, right) joins the output tape of the left relation to the input tape of the right relation. Each operand has one input and one output tape, and the joined tape types and scalar semiring must agree. For outer words \(x\) and \(z\), the score is \(\bigoplus_y R(x,y)\otimes S(y,z)\). The shared semiring must establish commutative multiplication so that interleaved products preserve the product of the two path weights.

The query aligns the corresponding non-epsilon occurrences on the joined tape. Between two such matches, including the leading and trailing intervals, the filter pairs epsilon occurrences until one side has finished its run. The remaining occurrences advance their own side. A match of a non-epsilon symbol resets the filter. This gives exactly one filtered path per compatible pair of original paths, including parallel paths and paths with no arc. Current weights leave this correspondence unchanged.

The constructor indexes arcs by state, outer label, and shared label in time and space linear in the total number of operand arcs. A query explores only configurations reachable at the supplied words. For \(P\) reached configurations, \(H\) shared-label probes and \(A\) candidate arc occurrences, planning after word validation takes \(O(P+H+A)\) time and \(O(P+A)\) space. At each configuration a probe examines one label from the smaller of two allowed shared-label groups. The arc count includes every admitted occurrence of a matched arc pair or one-sided epsilon arc. max_states bounds \(P\) and max_work bounds \(H+A\). Evaluation reads both original weight sources and uses the packed acyclic plan for the productive part. The weight vectors must have a common dtype and device. Evaluation work is linear in the operand slot counts and the productive graph, apart from computing the operand weights. A productive cycle on the fixed outer words requires closure, even when it emits symbols on the shared tape or its current weight is zero.

Reusable topologies and tape operations

ComposedRelation.materialize(max_states=..., max_work=...) builds a sparse product topology with the same epsilon filter. The result is a RationalRelation that can be used in a cascade, queried with bounded cyclic closure, or projected onto selected tapes. The limits cover reachable product and intermediate states, shared-label probes and constructed arc occurrences. Once discovery finishes, a reverse pass from the reached final states finds the states that can finish. Every constructed arc has a source reachable from an initial state. Its target's ability to finish is thus equivalent to that arc belonging to an accepting path. The returned topology keeps these arcs and the initial and final marks of accepting paths. State IDs and the state extent retain their discovery values. Surviving arc records keep their relative order and, when recorded, their operand origins. Their ordinals in the returned arc table follow the retained order.

This pass depends only on the topology. It retains a currently zero-weight arc on an accepting path, which may have a nonzero derivative in a linear carrier or become positive on a refit. It preserves the existing bijection between filtered product paths and pairs of source paths.

Each composed relation retains its latest materialized topology and weight-slot mapping. Repeating the same two construction limits reuses that structure. Every result reads the original live operand weights.

Each matched pair becomes two consecutive arcs. The first writes the two outer labels and takes the left weight. The other advances with epsilon labels and takes the right weight. The intermediate state has that one continuation, so expansion preserves each path and its weight. With cyclic composition the local star receives the two primitive factors as separate matrix entries, preserving the information needed to check convergence. Both operands' original parameter sources are live.

For \(P\) constructed states, \(A\) constructed arcs, and \(B\) boundary records, the reverse pass takes \(O(P+A+B)\) additional time and \(O(P+A)\) scratch space. Index construction and the retained arc-label storage scale with the surviving records and the number of tapes. The result retains the original weight-slot mapping. These are structure costs. Scorer work and its reverse tape depend on the attached weights. The product scaling test counts constructed arcs and retained records, and reports peak and post-construction Python allocations with the input machines already built. Tensor allocations and process memory have separate lifetimes.

invert exchanges input and output tapes. project retains the supplied original tape positions in increasing order, summing over the words on erased tapes. trim keeps the arcs and boundary marks on structurally accepting walks, including zero-weight occurrences. These operations reuse the relation's weight source.

condition fixes one tape to a word and erases that tape. After indexing the source arcs by their selected label, it visits the reachable pairs of source state and consumed word length. The remaining relation assigns the joint weight at the fixed word, so it can be used to compute a normalizer. Building the label index takes time and space linear in the source arc count. max_states bounds the visited pairs and max_work bounds the matching arc occurrences. Each output arc copies the labels on the retained tapes.

join synchronizes a single pair of tapes of the same type, one from each operand. The remaining input tapes precede the remaining output tapes. Each path pair with the same word on the two selected tapes contributes once by the epsilon filter. The joined tape can be kept once. For one-tape operands with the same tape orientation this gives intersect, the product of their weighted languages. A joined transition writes at most one label per retained tape. The construction limits apply to reached states, shared-label probes and constructed arcs after indexing the source arcs.

total_weight sums all accepting walks by erasing their labels before running the same fixed-word query. Each path realizes one word tuple, so this is the sum over the weighted relation's entire support. If erasing the labels exposes a productive cycle, the caller supplies a closure limit and the algebra checks convergence in its domain.

auto_intersect keeps paths whose words agree on two tapes of the same type. After trimming, it checks whether any accepting path can encounter both a positive and a negative cycle in the signed tape-length difference. A state-potential check recognizes zero-drift strongly connected components in linear time. For other components, signed relaxations detect positive and negative cycles. Their signs propagate along the component graph. Opposite signs on separate accepting branches are allowed.

Consider a prefix of an accepting path whose tape lengths agree at the end. Remove cycles independently from that prefix and its suffix. Their simple remainders each have length at most the number of productive states minus one. Since all removed cycles have one common sign or zero delay, each remainder bounds the original delay from one side. The prefix and suffix delays sum to zero, so the prefix's absolute delay is bounded by that same state count minus one.

The checked graph records the unmatched suffix on the tape ahead. Each transition appends the original labels, cancels their common prefix, and rejects a mismatch or delay beyond the certified bound. An accepting path has no unmatched suffix. Projection to the original arcs is bijective on paths with identical selected words, preserving shared weights and derivatives. The work limit includes signed relaxations and examined product arcs. The state-bound certificate is independent of the current weights.

RationalRelation.conditional fixes all input tapes and compiles a normalizer over every output word tuple. ConditionalStringQuery.log_prob compares the score of a supplied output to that normalizer. The denominator includes every alignment and output permitted by the relation. A productive insertion cycle uses the usual closure check and size bound. Each call uses the same live weights in both sums. A finite LogProb score whose normalized log ratio overflows the evaluation dtype raises OverflowError. An impossible output retains log zero. Exact tree marginals apply the same precision check.

union adds relations with identical tape types by taking the disjoint union of their topologies. concatenate uses a connecting state, so each accepting path contains one path from each operand. Its two connecting arcs carry the original boundary weights. It adds all ways to split a tuple of words into such a pair.

closure uses a new initial and final state to mark the end of each repetition. Every visit to this state after leaving it ends one accepting path of the operand. The empty path contributes one. If the operand accepts the empty word tuple, a query may have to sum infinitely many paths. The local star checks decide whether the sum can be used. Construction of these three topologies uses linear space in the original records and introduces one arc per connecting boundary.

A fixed-word query with an acyclic productive graph supports best_path and k_best_paths for Markov and LogProb weights. Ranking compares the exact values of the stored binary weights and reports path occurrence IDs in the original topology. Several paths can realize the same strings. Each outgoing arc gives one ordered stream of suffixes, since multiplying by a positive weight preserves their order. The query merges the stream heads. With \(d_q\) streams at state \(q\) and \(K_q\) retained suffixes, the work is \(O(d_q + K_q \log(d_q+1))\) arithmetic operations per state, and an analogous merge chooses the initial marks. Reading weight slots, the bit lengths of the exact rational scores, and materializing the selected arc sequences contribute additional costs. A checked native path rank request exposes the same ranked traces and separates the observation, rank, and result storage limits.

To sample from these paths, sample_path chooses an initial state by its weighted suffix mass, then chooses an arc or a stop with probability proportional to the weight of an accepting continuation, evaluated in float64 log space. The observations enter through the query, and a positive normalizer is required. In an acyclic observation every path has finitely many steps.

For expected counts, expected_arc_counts uses one packed pass in each direction and gathers the corresponding prefix and suffix at every active arc occurrence. An occurrence contributes its prefix times its arc weight times its suffix, divided by the normalizer. Summing these contributions gives the expected number of traversals of each original arc. In acyclic graphs this takes linear arithmetic work and storage in the active graph, in addition to the source weight evaluation and construction of the graph. Queries reuse the graph structure across evaluations. For a differentiable weight, weight(recompute_backward=True) lets PyTorch discard the intermediate tensors of the path pass and compute them again during backward. The source weight evaluation and its saved tensors are outside the path checkpoint.

Certifying numerical accuracy of Markov path weights

certify_markov_path_weight checks an absolute or relative forward-error tolerance for the ordinary packed score. Its mathematical input is the evaluated binary64 Markov weight vector from the same call. The verifier reads that vector as exact binary rationals. This scopes the guarantee to the path evaluation, including for a vector produced by a rounded source weight expression. The returned tensor keeps its ordinary derivative. The certificate concerns only its scalar value.

The verifier computes rational suffix intervals on the productive graph. At an acyclic state it sums the final weight and weighted successor intervals. Within a cyclic component, let \(A\) be the matrix of internal arc weights, with a contribution from every original occurrence. The right-hand side \(b\) includes final and outgoing weights and has a known interval \([b_-,b_+]\). The ordinary local star proposes a suffix vector \(y\) and a positive direction \(v\). The verifier checks \(d=(I-A)v>0\) over the original sparse rows. The resulting inequality \(Av<v\) gives \(\rho(A)<1\), and \((I-A)^{-1}\) is entrywise nonnegative.

For either endpoint of the right-hand side, the residual is \(r_\pm=b_\pm-(I-A)y\). Set \(c=\max_i\max(|r_{-,i}|,|r_{+,i}|)/d_i\). Every admitted residual lies between \(-cd\) and \(cd\). Applying the nonnegative inverse bounds the suffix by \(y-cv\) and \(y+cv\). The lower endpoint may be clipped at zero. Thus a small residual with very small \(d\) can still give a wide interval. The verifier propagates the suffix intervals to the initial marks and tests the returned scalar against both endpoints. The relative check requires a positive lower endpoint or a zero-width interval and a score both equal to zero.

Observation construction has the same state and arc budgets as a fixed query. Each declared local star order \(m_i\) includes auxiliary states for parallel transitions. The compiler checks the aggregate \(\sum_i m_i^2\) before allocating the associated packed expansions or dense star matrices. Ordinary closure uses \(O(\sum_i m_i^3)\) scalar work. The matrix-vector proposals add \(O(\sum_i m_i^2)\) floating-point work, and the verifier adds \(O(V+E+W)\) exact operations for active states \(V\), arc occurrences \(E\), and original weight slots \(W\). Its bit budget is checked conservatively before producing exact integer intermediates. The arithmetic cost per rational operation includes bounded integer products and gcds. Saved tensors for differentiating the packed score follow the usual evaluation contract and can retain quadratic arrays at each of the \(m_i\) elimination pivots. The certificate verifier keeps one pair of rational endpoints per active state and one exact value per weight slot, in addition to the sparse observation and closed matrices.

When the reachable graph, star order, closure cells, or exact arithmetic exceeds a limit, the call raises the corresponding resource error. Unsupported algebra or precision, divergence, an unverified contraction, and an interval that misses the requested tolerance have distinct diagnostics. The acyclic LogProb guarantee uses directed transcendental enclosures.

Certifying numerical accuracy of acyclic LogProb path weights

certify_logprob_path_weight checks an absolute tolerance in log units for a fixed-word observation whose productive graph is acyclic. The ordinary packed score and the verifier read the same evaluated binary64 slot snapshot. The returned tensor keeps its ordinary derivative, and the certificate concerns its value.

The verifier converts each used binary64 log weight to Decimal exactly. It treats negative infinity as exact zero mass and a zero log weight as exact unit mass. For each other weight, it encloses the exponential by the two neighbors of the correctly rounded nearest-even result. Python's Decimal operations

Let \(B_q\) be the final weight at configuration \(q\). In reverse topological order the verifier bounds \(S_q=B_q+\sum_{e:q\to r}w_e S_r\). All weights and suffix masses are nonnegative, so each lower-bound operation may use the lower endpoints of its operands and round down. The upper-bound operations use upper endpoints and round up. Each sparse update uses a directed fused multiply-add with one final rounding. Summing over the initial marks in the same way encloses the exact mass \(Z\). General Decimal Arithmetic Specification

Monotonicity of the logarithm and the neighboring decimals around its nearest-even result give rational bounds \(L\leq\log Z\leq U\) when the mass interval is positive. The verifier tests the larger distance from the packed score to \(L\) and \(U\) in exact rational arithmetic. Both mass endpoints equal to zero and a packed score of negative infinity give a verified zero mass. Its log endpoints are absent and its error is zero by convention.

The declared adjusted exponent limit \(E\) is symmetric. Each exponentiated input must satisfy \(|\ell|\leq 2E\), which keeps its exact mass in range because \(e^2<10\). Later arithmetic, including the two logarithms and their needed neighbors, must also stay in normal Decimal range. A path with a finite log weight of \(-1000\) can pass these checks even though its mass would underflow in binary64. Exponent exhaustion and subnormal or unavailable endpoints yield resource refusals. A productive epsilon cycle is outside the certified domain. An unsupported dtype, a nonfinite packed score on positive support, and an interval too wide for the requested tolerance have distinct diagnostics.

The verifier uses \(O(V+E_a+W)\) graph work for \(V\) active configurations, \(E_a\) arc occurrences, and \(W\) weight slots. The Decimal work budget counts at most four operations per exponentiated slot, two per used arc or initial mark, and four for the terminal logarithm bounds. This counts calls to the arithmetic library. Decimal precision and exponent range bound the stored operand sizes. The verifier checks the integer bit bound before converting a Decimal endpoint to a rational and charges the exact operations in the final error test separately.

Certifying numerical accuracy of cyclic LogProb path weights

certify_cyclic_logprob_path_weight admits productive epsilon cycles under explicit local star order and aggregate cell limits. The ordinary score and verifier read one evaluated float64 snapshot. The result remains the ordinary LogProb tensor and the certificate covers its value in log units.

For each productive strongly connected component, let \(A_{ij}=\sum_{e:i\to j} \exp(\ell_e)\) sum the weights of its internal arc occurrences. The right side \(b\) contains final weights and weighted suffixes from downstream components. Directed exponential endpoints bound every arc weight, so the lower and upper systems preserve the ordering of each finite partial path sum. Within each local system the endpoint coefficients are exact rationals, with every parallel occurrence included.

Eliminating state \(k\) replaces its contribution by

\[ x_k=\frac{b_k+\sum_{j>k} A_{kj}x_j}{1-A_{kk}}. \]

At this step \(A_{kk}\) sums the nonempty return walks through previously eliminated states. Every segment through \(k\) consists of an entrance, zero or more such return walks, and an exit. Thus a strictly positive pivot \(1-A_{kk}\) permits the exact geometric sum and the corresponding nonnegative substitution into the remaining equations. Positive pivots at all upper-system steps establish a finite upper star for the component because these checks apply to every unit right side. Back substitution then gives its upper suffix sums. Coefficientwise comparison of finite partial walk sums and their increasing limits justifies the lower and upper results.

The verifier transfers the two exact rational solutions outward into Decimal. Directed sparse updates connect the components and the terminal logarithm yields the log endpoints. The verifier preserves masses such as \(\exp(-1000)\) when they fall below the binary64 range. If an upper pivot is nonpositive, the verifier checks whether the lower endpoint system proves divergence. A nonpositive lower pivot gives return mass at least one, so its geometric series diverges. If all lower pivots remain positive, the available bounds give an unverified accuracy outcome. This may occur when the true mass is finite. The verifier checks every structurally productive component, including those with zero current boundary mass, so a divergence diagnostic concerns that local star. The requested score accuracy and the numerical star evaluator must also pass their respective checks.

The rational elimination uses \(O(n^2)\) cells and \(O(n^3)\) exact operations per component of \(n\) original observation states, in addition to processing its arc occurrences. The order and aggregate cell limits include auxiliary states used by the ordinary closure for parallel arcs. Lower and upper rational systems are solved in sequence. The exact integer bit and operation budgets apply throughout the proof, and the Decimal range and work budgets also cover the directed transfers. The acyclic core entry point and checked native certificate retain their acyclic domains.

Exact string factor trees

A StringVariable names a string type and may specify an observed word. A StringFactor assigns a distinct variable to each tape of a weighted relation. A StringFactorGraph checks these assignments and supports exact tree inference with the Markov and LogProb algebras.

To compile a marginal, the tree schedule sends one message toward the root of each connected component on every edge. A variable multiplies the incoming unary messages and its observation indicator, if present. A factor synchronizes each incoming unary message with its assigned tape and sums over the shared word. If that variable has no incoming weight, projection sums directly over its tape. Subtrees below a factor share only the variables on these separating tapes. Induction from the leaves gives the product of the factors summed over all variables other than the root. An independent component contributes its own total weight to the partition.

Messages retain their unnormalized weight. TreeStringMarginal.partition returns the total weight across components. log_prob divides the weight at a word by the mass of its component and requires every component to have positive finite mass. It evaluates each original weight source once across the numerator and denominator within a call. A cyclic factor graph is refused by the tree schedule. Cycles within a single relation use the ordinary productive closure checks.

Centered acyclic string likelihoods

ConditionalStringQuery.centered_query and TreeStringMarginal.centered_query compile an opt-in binary64 LogProb likelihood. The fixed-word numerator and its all-word denominator use the same evaluated weight vector. Both productive observation graphs must be acyclic. Disconnected tree components retain their existing normalizer requirements.

For each graph, let \(h_q\) be the maximum log weight of a positive suffix from state \(q\), including its final mark. Compute these maxima by a reverse topological pass over the exact dyadic input weights. For an arc \(q\to r\), replace its log weight \(w\) by \(w+h_r-h_q\). Subtract \(h_q\) from a final mark at \(q\). An initial mark at \(q\) receives \(h_q-M\), where \(M\) is the maximum log weight of a full path. The total shift is \(-M\) on every accepting path, for any path length. At each productive positive state, at least one suffix attains its maximum and thus has reduced log weight zero. A reverse packed sum operates on these centered suffixes.

The evaluator combines the exact difference of the two maxima with the two rounded packed log sums before rounding the scalar result. Every included occurrence retains the derivative of its original live log weight, with the chosen gauge held fixed. The gauge cancels from each full path, even when distinct arcs use the same parameter. A zero-weight prefix or suffix contributes no positive path. A zero numerator returns log zero. A zero denominator is undefined. A reduced factor or resulting log probability outside binary64 precision raises OverflowError. The packed sums and their derivatives still use binary64 arithmetic. This method gives no requested-error certificate.

The state and candidate-arc budgets apply to each observation as usual. The combined productive charts contain \(V\) states and \(A\) occurrences, counting both boundary marks and arcs. With \(W\) weight slots, the exact pass preflights \(W+2V+5A\) visits before building the lifted charts. Together the observations must fit within the combined occurrence cap. The reported work counts visits actually made. A pass uses a linear number of dyadic operations. Once scaled by \(2^{1074}\), its exact integers have \(O(2098+\log(V+1))\) bits. The packed charts and their backward tape have linear storage in the two active graphs, apart from the source weights and observation construction.

Certifying the centered log ratio

The checked centered certificate compares the delivered binary64 score with an interval for the original evaluated weight vector. Each finite reduced occurrence has an exact dyadic value \(d\) and a binary64 value \(\widehat d\) used by the packed evaluator. The verifier uses their exact difference as a log perturbation. In each chart a reverse DAG pass finds the minimum and maximum sum of these perturbations over positive paths, including initial and final marks. Multiplying the rounded path masses by the exponentials of the two extreme sums bounds the exact path masses. In log space, the verifier can thus add the two extremes to the existing rounded-factor residual interval.

Let \([L_N,U_N]\) and \([L_D,U_D]\) enclose the resulting numerator and denominator log residuals. Let \(\Delta\) be the exact difference of their path maxima. The exact original log ratio lies in \([\Delta+L_N-U_D,\Delta+U_N-L_D]\). The larger distance from the delivered value to either rational endpoint bounds its absolute log error. The certificate covers the value on the single evaluated snapshot. The log-zero convention applies when the numerator has no positive path and the denominator has a verified positive mass.

The two charts share Decimal exponent, precision and operation limits, and exact-arithmetic bit and operation caps. Each used arc or initial mark requires two directed fused multiply-adds. The exact min/max pass visits each state and lifted occurrence a bounded number of times. It stores each occurrence perturbation and two additional rationals per productive state. The bound on each dyadic factor follows from the original gauge and chart length. Conversion of Decimal log endpoints and the final comparison have their own charged bit bounds. The centering work and occurrence caps continue to preflight the two sparse charts before their lifted factors are built.

Centered likelihoods with productive cycles

certify_centered_cyclic_log_ratio admits a bounded fixed-input conditional query. Each structurally productive strongly connected component uses one constant exact dyadic potential. A reverse pass maximizes the final marks and the cross-component exit scores plus their successor potentials on the condensation DAG. The initial marks give one chart offset. The difference of the two chart offsets enters the final log ratio in exact rational arithmetic.

The potential cancels on every internal arc. Its original binary64 log factor and occurrence identity therefore reach the same local star, including parallel arcs and repeat visits. The remaining reduced factors lie on boundaries and condensation edges. Every positive original path has an acyclic component itinerary, so its rounding perturbation is bounded by the minimum and maximum sums on that DAG. Zero internal weights can make the structural DAG's bounds more conservative. The original sparse verifier still checks the supported path sum and finite stars inside each productive component. It distinguishes proved lower-star divergence from a failure to establish a finite upper star.

The local order cap and combined matrix-cell limit cover both numerical charts, including auxiliary states for parallel arcs. If the local expanded orders are \(m_i\), elimination uses \(O(\sum_i m_i^3)\) scalar operations, with separate convergence checks. The forward matrix cap is \(O(\sum_i m_i^2)\) cells. Host autograd can also retain intermediate pivot tensors. Exact directed endpoint elimination uses original component orders under the same cell cap and separate shared bit and arithmetic budgets. Gauging and the perturbation pass use linear work in the active observations. Large original factors inside a component still have to fit the directed exponent range. The host score retains ordinary autograd through the admitted numerical stars. Its proof certifies the value on one snapshot.

Certified finite string MAP

A FiniteStringScore lists the feasible tuples of words for a factor and assigns each tuple a rational additive score. dual_string_map uses the same typed variables and observations as a string factor graph. Bindings are full words in the declared finite supports.

Each variable occurrence gets a word-indexed potential. The potentials sum to zero across occurrences for each variable and word. Thus they cancel on a consistent assignment, and the sum of the adjusted local maxima is an upper bound for the original objective. Agreement on full words attains this bound. The certificate gives each local maximizer, its adjusted score, and the potentials needed to check the claim. When the iteration limit is reached before agreement, the result gives the best bound and any feasible score encountered. An empty local support certifies infeasibility.

A sweep scans the explicitly supplied local supports. Centering the update takes one pass over variable occurrences and uses rational arithmetic. The costs of exact rational operations depend on the bit length of the adjusted scores and potentials.

Fixed n-gram projection

An NgramFamily defines log-linear distributions over a finite support supplied by the caller. It counts contiguous n-grams up to the given order. Exact elimination on integer feature differences retains an affine basis that represents the same distributions. The base measure may be set to the cavity weight of a local EP update.

NgramFamily.project minimizes inclusive KL from the supplied tilted distribution to this family. Its convex objective is the log normalizer minus the dot product of the coefficients with the tilted feature means. The gradient is the difference in feature means and the Hessian is their covariance under the fitted distribution. Both input measures require finite log weights throughout the declared support. This ensures that the projected moments lie in the relative interior of the family's moment set.

The result reports the fitted probabilities, coefficients, divergence, moment residual, and solver status. The tolerance bounds the infinity norm of the feature residual at convergence. It does not bound a graph posterior error. For a support of size \(m\) and basis of size \(r\), each Newton direction takes \(O(mr^2+r^3)\) arithmetic work. Each line-search trial takes \(O(mr)\). Gradients follow the accepted sequence of operations. The line search evaluates the change in the objective from the current probabilities. For a coefficient displacement \(d\) and current mean \(\hat{\mu}\), that change is

\[ (\hat{\mu}-\mu)^\mathsf{T}d +\log\!\left(1+\mathbb{E}\left[e^U-1-U\right]\right), \qquad U=(\phi(w)-\hat{\mu})^\mathsf{T}d. \]

The centered change has zero expectation under the current probabilities. Evaluating the nonnegative exponential remainder preserves small changes near the optimum. Convergence still uses the requested moment tolerance.

Finite string belief propagation

A FiniteStringBeliefPlan uses an explicit list of admissible words for each variable. It compiles the factor scores on their finite supports, then reads the live sources once each per run. Construction counts the factor entries and the states and candidate arcs of their queries. Observed variables retain just their supplied word.

One synchronous sweep forms variable cavities from the previous messages, then sums the factor products over every other variable. The cavities and outgoing messages are normalized in log space. Prefix and suffix products allow the update to handle excluded words without subtracting an infinite log value. Damping mixes the old and proposed message probabilities.

The result reports the maximum undamped total variation between the returned messages and their one-sweep updates. This measures a fixed-point residual. The sweep limit can give a result with larger residual, and the residual gives no bound on the posterior error of a loopy graph. A fixed sweep count is available for differentiating a declared schedule.

Fixed-family string expectation propagation

FiniteStringBeliefPlan.expectation_propagation uses the same factor tables and cavities as finite string belief propagation. At each site it combines the cavity with the factor's outgoing log weights to form the tilted distribution and records its log normalizer. The fitted marginal is the inclusive-KL projection of that tilt onto the fixed-order n-gram family with the cavity as its base measure. Dividing the fitted marginal by the cavity gives the new site message. Damping interpolates log message weights to stay in the same family.

The schedule reports the outer message residual and the separate fit for each evaluated site. A local fitting limit, numerical stall, or tilt without positive weight on the full support leaves the previous accepted sweep in place. A fixed sweep count differentiates the executed updates. These finite message estimates use only the supplied word supports.

A positive projection_penalty adds the sum of Euclidean coefficient norms over the n-gram prefix groups, scaled by that penalty. Each group contains every feature with that prefix, including the feature equal to the prefix when present. The empty prefix covers all coefficients. This objective uses the full n-gram coordinates because an affine change of basis can change the penalty.

NgramFamily.project_penalized takes a step bounded by the maximum squared centered feature norm, then shrinks each prefix group from its descendants to the root. Two groups are disjoint or nested. A parent shrink preserves the directions of its descendants' subgradients, so the sum of the shrink displacements is a subgradient of the complete penalty at the final point. This gives the proximal update. The reported local convergence criterion is the infinity norm of its gradient mapping. The finite group implementation scans the declared feature vocabulary. Each shrink copies the coefficient vector, so a proximal update takes \(O(rg)\) work for \(r\) coefficients and \(g\) groups.

Candidate string messages

StringCandidatePlan scores a finite list of words in a unary LogProb relation. Its complement is a deterministic acceptor that recognizes every other word. Its unique accepting path for each omitted word gives exactly one matching path for every original occurrence of that word. The candidate queries and the complement thus partition the original path sum. In particular, the omitted mass can remain visible when it is too small to recover by subtracting the retained mass from the total.

An optional beam retains the highest-scoring candidates, breaking ties lexicographically and reporting a tie across the boundary. The full message scale and the weights of the selected words stay differentiable on the selected support. The normalized message uses centered log weights. Finite full, retained, and omitted candidate reductions restore their original log scale after summing centered weights. Their gradients use the relative weights within each reduction. A finite normalized candidate that overflows raises OverflowError. Construction limits raise a distinct error.

Batched contextual edits

ContextualEditChannel sums the alignments of observed input-output pairs with a single packed semiring plan. At input position \(i\) and consecutive insertion count \(j\), the scorer supplies logits for all legal edits using the complete input word. It assigns local probabilities before any restriction to the observed output, so competitors that emit other symbols still enter the denominator.

A consuming edit advances \(i\) and resets \(j\). An insertion advances \(j\) at fixed \(i\), with a finite upper bound. A stop is available only at the end of the input. Thus the generation graph is acyclic and has total mass one by reverse induction on \((i,j)\). For input length \(L\) and insertion bound \(I\), every emitted word has length at most \(L+(L+1)I\). The plan for a pair adds the observed output position to this state and includes only matching arcs. It groups the accepted mass by example after a shared packed forward pass. The original scorer supplies new logits on every evaluation, with gradients through both compatible paths and local normalization.

The scorer's rectangular action table scales with input positions, the insertion bound, and output alphabet size. Its cells and the compatible observation arcs count toward the explicit work budget. The bound on consecutive insertions is part of the channel model, and the scorer can use the whole input as context for each edit.

Globally normalized contextual edits

ContextualEditChannel.global_plan treats the original network's logits as raw log weights. For a fixed input \(x\), an edit path \(p\) has score \(s(p)\) equal to the sum of its legal action weights, including the stop. The conditional log probability of an observed output \(y\) is \(\log(\sum_{p\,\text{emits}\,y}\exp(s(p))/\sum_p\exp(s(p)))\), where the denominator sums all complete paths for \(x\). For example, an empty input with one available insertion can stop immediately or insert and then stop. Raw path weights 1 and 3 give output probabilities 1/4 and 3/4. Local normalization gives both outputs probability 1/2 if the first two action logits are equal. Rastogi, Cotterell, and Eisner (2016).

One evaluation reads the scorer once. The all-output suffix chart uses states \((i,j)\) and the packed observed chart adds the observed output offset. Every legal action contributes to the suffix sum separately, including actions that share a destination. Let \(U_s\) be the maximum suffix score at state \(s\), with \(U=0\) after the stop. Changing a log weight \(w_{s,a}\) on the move to \(t\) to \(w_{s,a}+U_t-U_s\) subtracts the same \(U_{(0,0)}\) from every complete path. Every row has a reduced action of weight zero. The suffix log sums of these reduced weights determine continuation terms for a second normalization. Multiplying those normalized transitions telescopes to the original path weight divided by the all-output mass. The packed chart then sums the normalized paths emitting the observed word.

The max-suffix calculation uses exact dyadic representations of the finite binary64 logits and rounds each reduced factor once. It performs this gauge calculation on a detached snapshot. Each rounded factor takes its derivative from its original live logit. A common path shift cancels in the conditional law, so treating the gauge as fixed preserves the conditional derivative in exact arithmetic, including at max-score ties. Residual suffix reductions, normalized action scores and the packed sum use ordinary binary64 arithmetic. Unrepresentable reduced factors, legal action log probabilities, and supported observed log probabilities raise an error. An output outside the finite path support has log probability \(-\infty\). On positive support, the log-score derivative is the expected raw path score derivative conditional on the observed pair, minus its expectation conditional on the input alone.

With batch size \(N\), padded input extent \(P\), insertion extent \(R\), and \(A\) actions, global mode charges \(NPR\) suffix states and \(NPRA\) suffix action cells before constructing the observed chart. The work cap also charges the original \(NPRA\) action cells and each compatible observed arc. Suffix processing takes \(O(NPRA)\) tensor or dyadic operations and \(O(NPRA)\) space before the observed chart, including the saved values for suffix differentiation. The detached step handles dyadic integers whose size is bounded by the binary64 range and the logarithm of the maximum path length. The budgets concern these chart units. The scorer's own computation and saved tensors have their own costs.

Packed training on a contextual channel

A two-layer scorer reads each word's remaining suffix and the current insertion count. The training fixture observes paired binary strings and fits their conditional log likelihood. Both execution modes reuse their observation plans and start with the same neural parameters. The benchmark checks the loss at all four updates and compares the final parameters. The singleton mode concatenates the individual scores before each backward pass so both modes optimize the same batch mean.

Batch size Mode Update ms Peak Python KiB Saved tape KiB Final loss
4 Packed 2.54 20.0 25.5 4.152484
4 Singletons 5.45 36.3 22.7 4.152484
16 Packed 2.32 35.8 104.2 4.248501
16 Singletons 22.92 130.7 95.2 4.248501
64 Packed 5.69 133.9 418.8 4.332192
64 Singletons 114.46 509.0 384.1 4.332192

Times are medians per update across three warmed runs on one arm64 CPU thread with PyTorch 2.15. They include scoring, backward, and parameter updates. The two memory columns measure peak Python allocations and unique tensor storage saved for backward in separate runs. At batch size 64, packing reduced Python allocations while retaining more saved tensor storage. To reproduce the comparison, run python tools/benchmark_contextual_edits.py from the repository checkout.

Native global training across lengths and batches

The benchmark's global mode compiles and reloads the checked module, reloads the observation request, and binds the original live scorer. The timed setup includes these steps and charts the observed pairs. Each four-step fit reuses its chart and checks one scorer call per step. The reported forward time includes the native call and batch mean. Backward computes gradients for all network parameters. The timer stops before applying the update.

At observed lengths \(n\) and \(m\), there are at most \((n+1)R(m+1)\) reachable observed states. Each contributes up to three compatible edit arcs. With \(S_i\) states and \(E_i\) observed arcs for pair \(i\), sorting and packing take \(O(\sum_i(S_i\log(1+S_i)+E_i))\) work under expected constant-time dictionary access. Incoming buckets pad each positive width to its next power of two, using fewer than twice the incoming operands. The forward and reverse chart work is linear in the observed states, arcs and suffix action cells. The scorer separately builds suffix features using Python slices and reductions, which can cost quadratic time in input length. The measured times include this scorer and native dispatch.

Input length Batch Suffix states Action cells per chart Observed states Observed arcs
2 1 6 36 12 17
2 16 96 576 160 216
6 4 56 336 264 530
10 1 22 132 176 385
10 16 352 2112 2720 5944

The counters above come from the actual reused chart. The limits charge suffix and observed states, two action tables, and observed arcs. For length 10 and batch 16 that is 3,072 states and 10,168 work units. These units measure construction size independently of timings.

Input length Batch Setup ms Forward ms Backward ms Setup Python KiB Fit Python KiB Saved tensor KiB
2 1 21.73 3.09 0.63 396.3 37.8 3.2
2 16 19.12 4.01 0.68 386.6 61.0 40.9
6 4 21.57 4.70 1.73 386.2 47.9 37.9
10 1 18.64 5.01 2.37 385.3 54.2 21.3
10 16 23.36 9.52 2.30 1671.2 150.6 325.0

The times are medians across three warmed runs on one arm64 CPU thread. The allocation columns use separate profiling runs. Python KiB is the peak traced allocation during setup or during a fit with the chart already bound. Saved tensor KiB is the maximum across steps of distinct backing storage requested by autograd during one forward pass. It includes saved scorer tensors. These are separate measures of Python allocation and autograd storage. Reproduce all nine rows with python tools/benchmark_contextual_edits.py --global-lengths 2 6 10 --sizes 1 4 16.

Path entropy and additive risk

FixedStringQuery.path_statistics uses packed prefix and suffix passes on the productive observation graph. Let \(\alpha(q)\) and \(\beta(q)\) be its prefix and suffix log masses and \(Z\) its total mass. The posterior log mass for a traversal of arc \(q \to t\) is \(\alpha(q) + \log w(q,t) + \beta(t) - \log Z\). Its conditional log probability given the visit to \(q\) is \(\log w(q,t) + \beta(t) - \beta(q)\). Initial and final choices have the corresponding one-sided prefix or suffix terms.

Entropy is the sum of the initial-choice entropy and the expected entropy of each subsequent choice, including stop decisions. This follows by factoring any complete path's posterior probability into its successive choice probabilities. The same event probabilities weight the supplied arc and boundary cost tensors. Thus the method computes the expectation of any additive path cost, which can also serve as a differentiable risk objective. Original occurrence IDs select costs even when arcs share weight parameters or an original arc appears at several observed offsets.

The log normalizer, entropy, and expected costs have derivatives on the current positive support. Zero-probability choices contribute zero. An entropy of paths can differ from an entropy of the output words when several paths emit the same word.

A typed QVR binding using expected_path_cost can serve as the loss for repeated parameter updates. Its FixedRelationCostRequest binds the observed pair and the signed initial, arc, and final costs. The provider reuses the fixed-word query and its packed charts while reading live weights on each call. For an acyclic observation, the chart passes and event reductions take linear work in active states, arcs, and boundary marks for scalar costs, apart from reading the original slot vector and constructing the observation. The gradient applies to the normalized distribution of accepting paths on the current positive support. Li and Eisner (2009), §§6.1–6.2

An authored refit check uses three accepting paths of masses \(p^2\), \(p^2\), and \(1-p\), with costs \(3\), \(1\), and \(-1\). The two \(p^2\) paths retain separate parallel arc occurrences and share one live weight. The expected cost is \((4p^2-(1-p))/(2p^2+1-p)\). At \(p=1/2\) the risk gradient is \(9/2\), and the negative log pair-weight gradient is \(-1\). Eight optimizer steps check values, gradients, and new parameters against exact path enumeration at the evaluated binary64 weights. The same chart is used throughout. Construction visits five configurations, examines six candidate arcs, and retains five productive arcs. The check concerns fixed-pair path risk with additive costs.

Packed nonnegative feature moments

FixedStringQuery.log_feature_moments runs the packed acyclic executor over an occurrence-indexed plan with ExpectationSemiring over FreeSemimodule(LogProb, d). Each initial mark, arc, and final mark has an optional nonnegative feature increment \(f\) represented by its logarithm. An occurrence with mass \(p\) starts with the pair \((p,pf)\). Multiplying two pairs adds the increments for the extended path because their second component is \(p_1(p_2f_2) + p_2(p_1f_1)\). Adding pairs sums the weighted increments across distinct paths. Li and Eisner (2009), §3

The query returns \(\log Z\) and the vector of unnormalized log moments. Subtract \(\log Z\) from the vector for conditional log expectations when \(Z\) is positive. Operations stay in log space, including for a path with a log weight of \(-1000\). Feature rows follow original occurrences even when weights are tied or an arc is traversed at multiple offsets. path_statistics computes entropy and signed additive costs, including on observations with a supported cyclic closure. The packed expectation pass uses a fixed-width carrier at each active entry of an acyclic observation chart.

For a productive cyclic observation, pass allow_cyclic=True to a query with a scalar closure budget. For each arc occurrence \(e:s\to t\), the unnormalized moment adds \(\alpha(s)w(e)f(e)\beta(t)\), with corresponding terms for initial and final marks. Choosing one marked visit gives a unique prefix, occurrence, and suffix. Since the summands are nonnegative, their order can change under a certified finite scalar closure. Inside one component this computes \(A^* B_f A^*\), where \(B_f\) sums the feature-weighted original arcs of that component. Repeated visits and distinct parallel occurrences both contribute. Divergence and an uncertifiable scalar closure produce the corresponding scalar errors.

Alignment-marginal output ranking

best_marginal_output compares the Markov path sum for each supplied output at a fixed input. Each observation graph must be productively acyclic. Summing over its aligned paths can favor a word whose best individual path is weaker than another word's. Whenever a fixed input has a positive finite conditional normalizer, that same normalizer applies to all candidates.

Each candidate is scored by a sparse topological pass over the reachable product of states and tape positions. Input coefficients are interpreted as exact binary rationals for comparison. State and arc limits apply cumulatively across candidates. The selected result also provides a packed log-space score whose derivatives flow to the original weights on the current positive support. Local derivatives hold the selected word fixed. This computation requires the candidate set to be supplied explicitly.

Adaptive joint alignment MAP

dual_alignment_map maximizes the sum of log weights of one path per factor subject to agreement on the complete shared strings. Each factor comes from the same typed graph used for sum-product messages. The score includes the initial and final weights. LogProb entries are interpreted as exact binary rationals for decoding. In a model where several paths emit the same strings, a different objective would sum their probabilities before comparing strings.

Each factor must have acyclic productive positive support before observation restrictions. Its exact decoder tracks the original state, positions in observed strings, and one finite suffix state per tape. The suffix state counts occurrences of active n-grams, including beginning and end markers. Two partial paths at the same configuration have the same continuations and future adjustments. Thus only the better adjusted partial score and its original trace need be retained. The decoder counts state visits and examined arcs against its configured limits.

For each shared variable and n-gram, the solver's multipliers sum to zero across copies. Thus the adjusted score sum of any feasible joint assignment equals its unadjusted score. Summing exact local maxima gives an upper bound. If the selected local paths agree on their full words, they are jointly feasible and attain that bound. If their words differ, the solver can activate a distinguishing n-gram within the order and feature limits and update centered multipliers. It can return an uncertified feasible assignment and an upper bound at the iteration limit. Feature-count agreement alone does not establish a certificate.

The selector ranks each order's n-grams using pairs of the preceding prefix rank and the new symbol. It includes the start and stop symbols in the same order as the word-counting rules. Sorting by the pair preserves lexicographic order because the preceding rank orders equal-length prefixes. Records also carry their original word and position. Within one rank, equal positive counts for all owners are equivalent to equal occurrences in every selected word. A missing owner has count zero. Already active n-grams follow the same rank transitions and exclude their matching complete ranks. The first eligible rank at the first eligible order gives the same choice as explicit count dictionaries. The selector materializes only that chosen n-gram.

Let \(N\) be the total length of the selected words including markers, \(W_d\) the number of candidate windows at length \(d\), and \(A\) the total length of active n-grams. Per order the selector sorts \(W_d\) fixed-width records and assigns ranks in one pass. For \(K\) visited orders, comparison work is \(O(KN + \sum_d W_d\log(W_d+1) + A\log(N+1))\), with integer comparison costs depending on symbol and rank widths. Candidate selection uses \(O(N+A)\) logical cells and makes no assumptions about hashing symbol sequences. A direct selector that slices each window would copy \(\sum_d dW_d\) symbols and can hold \(O(Nd)\) symbols at one order.

The host solver's max_feature_work caps the cumulative candidate windows, active prefix probes, and symbols copied or looked up by the direct count routines. Sort comparisons are bounded as above. The direct counts use hash tables and remain independent of both the rank selector and the decoder's suffix automaton. They count active n-grams for multiplier updates and reconstruct n-gram scores for verified traces. At one order \(d\), one word's count table can still store \(O(dW_d)\) symbol slots. The max_feature_cells cap covers charged active feature symbols, rank records and direct count buffers before allocation. Reported peak cells describe these buffers. Local decoder states, suffix automata, rational bit sizes and Python allocator overhead have separate costs. A feature limit raises the relation resource error, including during verification.

Before returning a bound, the solver checks the saved local witnesses under the multipliers that produced it. First it reconstructs each original walk, verifies its observed words, and recomputes its two scores from the boundaries, arc weights, and direct n-gram counts. Then it derives the exact suffix optimum in each reachable local configuration. In reverse topological order, each scalar suffix value is the maximum over its available final score and every arc score plus its successor's suffix value. This pass does not use the decoder's prefix maxima or backpointers. The claimed adjusted scores must attain these independently calculated maxima, and the multipliers must still sum to zero. Feasible lower witnesses are checked against their complete word assignment. An infeasibility claim requires a local subproblem with no accepting path under its observations.

Reachability and suffix verification each examine the same reachable configurations and candidate arcs as a local forward decode. They reuse its state limits. With max_work = B, each scan examines at most \(B\) arcs, for at most \(2B\) candidate arc probes per checked local witness, plus visits to the witness's original arcs. The verifier stores one exact score per reachable configuration and no materialized transition table. Trace checking additionally visits the selected primitive arcs and computes n-gram counts for the selected words. Exact rational arithmetic and feature work depend on coefficient bit lengths, tape widths, word lengths and active feature orders. max_verification_states and verification_arc_examinations record the additional graph work.

The solver may also stop at a requested absolute or relative objective gap. With an exact feasible score \(L\) and dual upper bound \(U\), the unknown optimum \(z\) satisfies \(L\leq z\leq U\). Thus \(U-L\) bounds the absolute suboptimality of the returned assignment. For \(z>0\), the relative error is \(1-L/z\). For \(z<0\), it is \(L/z-1\). On a positive interval with \(L\geq0\), or a strictly negative interval, the relevant function increases with \(z\). The maximum relative error is thus \((U-L)/|U|\). If \(L<0\leq U\), these bounds alone give no finite relative guarantee. When \(L=U\), the relative gap is defined to be zero, including at the exact zero optimum.

Supply absolute_gap or relative_gap as a nonnegative exact rational. All supplied targets must be established. An early stop based only on these bounds has status gap, with gap_target_met=True. The separate status optimal and its agreement certificate require exact local maximizers to agree on their complete words. When there is no feasible result, neither gap can be established.

The returned score and certificate concern the evaluated parameter snapshot. Local paths are discrete decisions. The solver reports the peak number of reached local configurations and total local arc examinations, including primal feasibility checks. The joint alignment MAP benchmark compares these counts with a materialized intersection and verifies both against independent path enumeration.

paired_dual_alignment_map accepts a partition of original factor positions into singletons and pairs. Each pair must share exactly one nominal tape variable. Its filtered sparse join keeps the shared tape once, retains the other tapes in join order, and represents every compatible original path pair once. The solver applies one multiplier copy per group for each shared variable. Equality between groups thus imposes the same original feasible assignments as the singleton solver.

The grouped decoder reads the original binary-rational log coefficients. Its arc macros retain primitive weight slots, and it adds the two boundary coefficients directly as rationals. This preserves the original objective even when adding the boundary in a float would lose a smaller coefficient. A feasible grouped path yields one StringAlignmentTrace per original factor. Each expansion checks its original endpoints, ordered arcs, emitted words, and exact base score. The grouped result's certificate has one local maximum per group.

Each paired product uses its own state and work limits. If its two operands have \(V_l\) and \(V_r\) states and the builder emits \(M\) matched moves, it has at most \(3 V_l V_r+M\) states. The extra states keep matched primitive weights separate. Label probes and emitted arcs are charged to max_group_work, and products remain available between dual updates. Local graph sizes and work are then bounded and reported as for singleton decoding. This groups only the explicitly requested factor pairs. A pair with zero or multiple shared variables is refused.

Compact regular n-gram messages

NgramMessagePlan compiles the product of a one-tape LogProb relation and a deterministic suffix automaton over supplied n-grams. The automaton moves on emitted symbols and retains its state across epsilon arcs. It charges every matching feature at its ending symbol, including overlapping occurrences. An original path has exactly one product path and receives the same feature score as any other path with the same output word.

The compiled message has log weight \(\log M(w) + \theta^\mathsf{T} \phi(w)\), where \(M\) is the original weighted language and \(\phi\) counts feature occurrences. It reuses the original weight and coefficient sources. Each weight evaluation gathers the required coefficient rows and shares identical pairs of original slots and feature emissions.

The automaton uses prefixes of the supplied feature set and failure links to proper suffixes. Only reached product configurations are created, and no iteration over the alphabet is required. The work budget includes trie construction, failure links, examined product arcs, and feature emissions. Ordinary relation limits and closure checks apply when summing the message. In particular, tilting a cyclic language can change whether its normalizer is finite.

Penalized projection on a regular language

penalized_regular_ngram_projection fits a regular n-gram message relative to a finite acyclic base language \(M\). The normalized target is the product of \(M\) and a supplied likelihood, so the target's support is included in the base. The product uses sparse epsilon-filtered intersection. The fitted distribution is proportional to \(M(w)\exp(\theta^\mathsf{T}\phi(w))\).

Let \(Z_\theta\) be its normalizer and let \(\mu\) be the target feature mean. The change in inclusive KL relative to the base is \(\log Z_\theta-\log Z_0-\theta^\mathsf{T}\mu\). The projection adds the sum of Euclidean norms of the coefficient groups for each feature prefix, scaled by the specified penalty. It obtains both sets of expected counts by differentiating sparse path sums. If the base's longest word has length \(L\), a feature for a gram \(g\) counts at most \(r_g=\max(0,L-|g|+1)\) occurrences. Its variance is at most \(r_g^2/4\). The Hessian of \(\log Z_\theta\) is the feature covariance, so its operator norm is at most the trace bound \(B=\sum_g r_g^2/4\). The fixed-Lipschitz optimizer uses a step at most \(1/\max(1,B)\), rounded downward in float64 if needed. It evaluates the target and base moments once each, then makes one moment evaluation per accepted step. Adaptive backtracking tries a step up to one and checks the quadratic upper bound on the smooth objective with a float64 rounding allowance. Halving ends at the globally valid step. The number of trials per accepted update grows at most logarithmically with \(\max(1,B)\). Both policies report actual moment evaluations, including rejected trials. They reuse the same sparse moment plan across proposals. On a uniform base over the empty word and an eight-symbol repetition, with tilted mass ratio \(7:1\) in favor of the repetition, both policies choose the first coefficient step \(3/16\). Adaptive backtracking takes seven moment evaluations including four rejected trials. The fixed policy takes three.

The projection reports the proximal gradient residual separately from its iteration status. The fitted message compiles only nonzero features, so the penalty can change the number of reached states. The result also retains the target's log mass and the site scale that matches it. The fit uses a fixed weight snapshot and reports its numerical result without differentiating the optimizer.

By default a fit uses the full finite candidate vocabulary declared for the variable. Its nonzero coefficients select the retained features and their automaton. With the fixed Lipschitz step, an optional frontier_seed specifies an ordered subset for the first fit stage. Each restricted problem evaluates the same prefix-group penalty at the zero extension of its coefficient vector.

After a restricted stage, one full-gradient proximal update tests stationarity over the whole candidate dictionary. The check uses the full-dictionary step and the same prefix groups as the original objective. In exact arithmetic, a zero update is equivalent to the convex optimality condition. The solver compares its computed gradient mapping with the requested tolerance. If the check fails, any nonzero update in an excluded coordinate can add that feature to the next stage. A feature can enter even when its proper prefixes have zero coefficients. Each new stage starts from the previous coefficients and shares the remaining iteration and moment budgets. A failed restricted solve or a failed full check without further growth has a distinct outcome from convergence. Cotterell and Eisner (2015), §6.1 and Figure 2

A fit can expand at most once per initially excluded coordinate. It prepares the full reference and tilted moment charts and computes the full tilted moments once. Each subsequent restricted plan uses the same reference language and only its current features. A full check after an accepted restricted update adds one evaluation of the full reference moment chart. The number of moment calls includes every full or restricted evaluation. The separate stage sizes, stage-boundary checks and restricted evaluation count expose how this work is divided.

Let \(C(D)\) be one moment evaluation on candidate dictionary \(D\). For stage \(j\) with subset \(A_j\) and \(t_j\) trial moment evaluations, trial work is \(\sum_j t_j C(A_j)\), along with the full chart preparation and up to one full moment evaluation and full proximal pass per stage boundary. A fit must also compile each strict subset that it uses. The useful regime has many trials on a substantially smaller chart before a full check. A fit that expands to the whole dictionary also pays for its earlier restricted stages. Both policies need enough resources for the full chart. This is a local stationarity check at working precision. Global posterior and derivative guarantees remain outside the regular EP policy.

A fixture places an independently uniform four-position suffix after a biased first symbol. The first-symbol feature fits the tilt's bias. The four suffix bigram counts have matching expectations under the tilt and fitted message. Both strategies fit first-symbol probability \(4/5 - 2(0.03) = 0.74\) and take the same number of accepted steps. Instrumenting the compiled charts, moment passes and prefix shrinks gives the following counts.

Strategy Moment calls Active arc visits in moment calls Prefix-group memberships visited Charged n-gram compilation work
Full dictionary 1,570 40,836 21,966 172
Finite frontier 1,571 18,910 3,152 188

The arc count sums the active query arcs over moment evaluations. Each evaluation runs the forward pass and the feature backward pass. The prefix count sums the group sizes for each proximal update. A separate fixture puts all the signal in a bigram whose unigram prefix is constant across words. The frontier expands to the full dictionary and pays for its initial restricted stage. Run pytest tests/test_regular_ngram_projection.py -k frontier to check both cases.

For a positive penalty, a candidate gram \(g\) contributes \(|g|+1\) coefficient indices to the prefix groups, including the empty prefix. The fit checks this sum against max_prefix_group_cells before building the group lists or their index tensors. A frontier charges both full and restricted groups when they coexist. A zero penalty allocates no prefix groups. For \(r\) candidates, \(G\) groups and \(M\) total memberships, one proximal step takes \(O(rG+M)\) work. The group index tensors store \(M\) elements. The candidate feature vectors, trie construction, product queries and their temporary tensors have separate costs.

Expectation propagation with regular messages

regular_string_ep takes a typed string factor graph and a finite acyclic reference language for each variable. Its model weights multiply the graph factors and the supplied reference weights. A unit-weight reference restricts a variable to its declared regular support. An observed variable is further restricted to its observed word.

A site has a log scale and a linear score over its active n-grams. A cavity reweights the reference language using the coefficients from all other incident sites. The factor multiplies its incoming cavities by joining on their shared tapes, and marginalizes the other variables. A variable can occur on the input or output side of any factor. Projection aligns the remaining unary likelihood with the orientation of its cavity, preserving word weights and path occurrences. When the orientations differ, this rebuilds the unary topology's indexes once before the fit. The sparse product and moment budgets retain their existing units. An observed word restricts a reference language of either orientation. Local projection fits the resulting tilted distribution in the cavity-based n-gram family. The site then retains the fitted coefficients and a scale that matches the tilted mass under normalized cavities.

Each sweep proposes all sites from the preceding state. Damping interpolates log scores and scales. The residual takes the largest undamped change in log scale plus the maximum accepted word length times the coefficient-change one-norm. This bounds the change in a site's log score uniformly over its reference support. A failed local optimizer and an exhausted outer sweep retain the last accepted messages with distinct statuses. Relation construction or closure limits raise their usual errors. The result describes an approximate inference run over a fixed weight snapshot.

Unit sites initialize with zero coefficients and log scales. A supplied initializer may instead give finite coefficients and a finite log scale for every site in factor, tape, and feature order. This sets the initial iterate and carries no convergence claim. The solver still measures the undamped defect at the last accepted iterate, including at a zero sweep budget. Total moment evaluations include every attempted local fit of this synchronous schedule. Pass projection_frontiers to select initial candidate subsets by variable for the fixed-step optimizer. Each local projection starts with its declared subset and may expand within its full dictionary. max_moment_evaluations limits the same cumulative count. The solver checks the remaining budget before each target, base or trial evaluation, including trials in a fit that fails and every fit in the final diagnostic pass. Exceeding the cap raises a relation resource error. An admitted call returns the same iterate and diagnostics as a call with the cap omitted.

Each moment evaluation runs the packed normalizer and its feature backward pass on the corresponding local product, whose construction has its own state and work limits. A projection reuses its moment plans across trials. A new tilted site can require a new product on a later sweep. The moment cap counts evaluations of these plans. The prefix-group cap counts index memberships per fit. The two caps cover different operations and leave the other sparse limits in effect. The memory benchmark below measures Python allocations.

Two-variable comparison

All methods use the same graph with one binary factor, two unary factors, and the same four two-symbol words on each variable. An independent dense sum over the 16 assignments supplies the exact marginals. The exact sparse tree and full-width production beam agree with these marginals. The width-three row runs FiniteStringBeliefPlan.run_pruned on the same graph, including its final proposal pass. Regular EP uses both unigrams and all four bigrams as candidate features.

Method Status Mean TV error Site features Site states/arcs Marginal states/arcs
Exact sparse tree exact 0.000000 — — 260/192
Production beam 3 converged (truncated) 0.399886 — 24/20 8/6
Regular EP (0) converged 0.000000 24 28/24 14/12
Regular EP (0.025) converged 0.048646 12 24/22 14/12
Regular EP (0.1) converged 0.112319 7 19/20 13/12
Regular EP (0.3) converged 0.153415 0 12/16 6/8
Regular EP (1) converged 0.153415 0 12/16 6/8

The representation counts sum states and arcs across the individual sites or queried marginals. For regular sites the benchmark compiles the automaton induced by the fitted active features. The beam counts derive from the tries of the surviving word prefixes. The production beam holds dense vectors over the declared finite axes.

Let \(A\) count the factor-argument sites, \(S\) count accepted sweeps, and \(L\) count fits recorded on the final pass. Each accepted sweep visits all \(A\) sites, and the solver evaluates another pass at the returned state. Thus it attempts \(AS+L\) local fits, including any failing fit on a final partial pass. A moment evaluation is one evaluation of the sparse normalizer and feature counts. The solver counts both target and base calls and the calls made by rejected optimizer trials. The benchmark test observes the actual site and moment invocations and detects a false reported sweep.

On this graph a complete beam pass has four proposals and charges \(2\cdot16+4+4=40\) factor-table cells across the outgoing axes. The three executed passes include the final check. These counts describe the input cells for the proposal reductions. Beam sorting, cavity normalization, and table construction have separate costs. A test derives the expected width-three support from the sums over retained incoming candidates and detects a wider beam substituted for it.

Method Sweeps Site fits Moment evaluations Beam input cells Median ms Peak Python KiB
Exact sparse tree — — — — 6.6 128.4
Production beam 3 2 — — 120 6.0 30.5
Regular EP (0) 4 20 1709 — 643.1 195.5
Regular EP (0.025) 9 40 4139 — 2107.6 206.1
Regular EP (0.1) 2 12 141 — 91.4 197.1
Regular EP (0.3) 1 8 16 — 24.7 175.5
Regular EP (1) 1 8 16 — 25.0 175.5

Run python tools/benchmark_string_messages.py --repeats 5 from the checkout. Times are medians of five calls after one warmup per row, on macOS 15.7.4 arm64 with one CPU thread and PyTorch 2.15.0. Calls include solver preparation, marginal scoring, and representation counts. Every invocation starts from the same initial sites. The memory column measures peak allocations traced by Python's tracemalloc during a separate call. It describes Python allocations and omits native tensor and allocator storage. The smallest positive penalty halved the retained feature count in this graph and increased moment evaluations from 1,709 to 4,139.

The errors measure posterior inference on this fixed length-two support. Scaling whole-graph inference to longer strings and measuring prediction on held-out data are separate benchmark settings.

Length scaling on coupled Markov strings

Run python tools/benchmark_string_message_scaling.py to compare the same four methods on lengths 2, 4, 6, 8, and 10. Both latent variables range over all binary strings of length \(n\). The two unary factors assign positive first-order Markov weights, and a synchronized binary relation assigns a positive weight \(C_{xy}\) at each aligned symbol pair. Each factor has \(O(n)\) states and arcs. The factor graph is a tree with \(2^n\) supported words per variable.

The oracle sums over the four paired symbol states. Its first state vector has entries \(a_x b_y C_{xy}\), and its transition from \((x,y)\) to \((u,v)\) has weight \(A_{xu} B_{yv} C_{uv}\). For a marginal word, clamping one coordinate at every position gives a two-state recurrence. These recurrences use integers and form exact fractions for the normalized marginals. Checking every output word at both variables takes \(O(n 2^n)\) arithmetic operations over integers with \(O(n)\) bits. The oracle uses the full \(4^n\) Cartesian enumeration only at length two. That check also tests the swapped off-diagonal coupling weights, which change the partition and the marginals. Solver weights are stored as float64 log weights. The benchmark compares exact sparse word scores with the fraction oracle at absolute tolerance \(10^{-12}\) on the probability scale.

Regular EP uses unit-weight references, declared unigrams and bigrams, and the same backtracking policy at each length. The references impose the common length support and leave the factor weights intact. Each row starts from unit sites and admits up to eight synchronous sweeps, 2,048 accepted inner steps per fit, and 100,000 total moment calls. The site residual tolerance is \(5\times10^{-4}\) and the local projection tolerance is \(10^{-4}\). The penalty varies from 0 to 0.3 and the retained features depend on the fit. A converged row still has a measured word-marginal error. This finite synthetic graph tests regular message approximation and uses no held-out linguistic data. Dreyer and Eisner (2009), Cotterell and Eisner (2015).

The production beam keeps at most 16 words per message after building its finite factor tables. The two unary tables and one binary table request \(4^n+2\cdot 2^n\) cells. The declared 5,000-cell cap applies before table construction. A refused row leaves the probability and construction-work columns empty. Use --projection-iterations 0 to exercise local projection failure separately. That failure can return the last accepted belief. The script verifies checked native round trips on the same authored graph, including the pruned solver's truncation and resource diagnostics at the relevant lengths.

At length six, unpenalized EP has mean word-marginal TV error 0.00818 with 24 retained features and 6,291 moment evaluations. Penalty 0.025 retains 20 features and uses 3,628 moment evaluations, with mean TV error 0.06113. The beam truncates at the same length and has mean TV error 0.76468. At length eight its 66,048 requested cells exceed the construction budget. Regular EP still returns word marginals under the declared settings.

State and arc counts sum the two returned marginal representations. The beam count describes tries of surviving words, while its actual schedule retains dense candidate axes. Site features count nonzero coefficients across all regular sites. Moment calls and beam build arc examinations have different units. Every row excludes static model parsing and independent oracle computation from its timing. The wall time includes solver preparation and full per-word scoring. The separate tracemalloc pass reports peak Python allocation and excludes native tensor storage.

Transient storage in regular EP projection

On the same length-two model, run python tools/benchmark_string_message_scaling.py --lengths 2 --profile-moment-memory. This mode caps moment calls at 512 and uses the same sparse, sweep, prefix-group and local optimizer settings. It checks that the native probabilities match the host solver's first marginal, then compares both host marginals with the independent transfer oracle. A resource refusal leaves the accuracy and feature columns empty.

The native regular solver uses coefficient gradients to compute moments. For each call, saved tensor hooks count distinct live backing storage at the first unpack in that call's backward. The maximum across calls describes storage at that point in the local tape. A separate CPU allocator pass measures the original named call, including site construction and control work. Its total counts positive allocation events. Its peak is measured relative to the allocator balance at entry. This run excludes source compilation and Python allocation. The regular solver returns detached beliefs. Its temporary projection tape is distinct from a finite unrolled trajectory retained to differentiate a returned score.

Penalty Mean word TV Site features Moment calls Saved bytes at first unpack (max) CPU allocated bytes CPU additional peak bytes
0 0.00005903436 24 377 2,081 1,131,115 5,321
0.025 0.10782167 16 433 2,081 1,844,631 5,161
0.1 0.15001886 0 16 1,415 95,634 3,118
0.3 0.15001886 0 16 1,415 95,634 3,118

These CPU float64 measurements use one arm64 thread with PyTorch 2.15. Every moment in these rows unpacks saved tensors. At penalty 0.025 the fit retains fewer site features and performs more local projection work, even though the largest local tape measurement stays the same.

Posteriors on closed productive components

For an explicitly permitted finite star, the prefix weight at a state is the weight of every walk ending there, including walks inside its component. Within a cyclic component the chart reads the prefix at the component exit introduced for that state. The suffix chart reverses the arcs and exchanges boundary roles, using the same component closure. This gives the prefix and suffix factors needed for expected traversal counts and path entropy. A primitive arc's traversal can recur along one path, and each occurrence enters its expected count.

Sampling first selects an initial mark in proportion to its weight times its suffix mass. At each state it chooses a stop or primitive arc in proportion to the stop weight or the arc weight times the successor suffix mass. In exact arithmetic the suffix ratios telescope to the normalized weight of each complete path. Their weights sum to one under the finite closure contract, giving almost-sure termination. Runtime sampling uses float64 and a cyclic query requires an arc-step budget. A draw beyond that budget raises a resource error. The reported path weight uses the original algebra and must fit its input precision.

Sparse backoff queries

A FailureArc applies when a one-tape deterministic state lacks a transition for the requested symbol. An explicit zero-weight transition still takes precedence. backoff_query carries the unconsumed symbol through the failure chain, then consumes it at its first explicit match. It multiplies the failure weights in traversal order before the explicit weight. Completion uses the state's own final weight. Every failure chain must be acyclic.

After indexing the declared transitions and checking the failure links, query construction follows only the selected path. Its work is linear in the number of examined symbol probes, and its storage is linear in the selected path length. In particular, the number of symbols in the alphabet does not determine either cost. The ordinary fixed-string evaluator reads the original weights when it scores the resulting path.

backoff_total_weight sums over every word when the reachable union of ordinary and failure edges is acyclic. In reverse topological order, the suffix total at a state is the sum of its own final weight and its first-symbol contributions. Each explicit symbol contributes its arc weight times the target's suffix total. A missing symbol can inherit its contribution from the failure target, left-multiplied by the failure weight. This recurrence follows from partitioning nonempty words by their first symbol. Its empty-word contribution uses the state's own final weight.

A persistent sum tree stores the contributions across the distinct symbols present on reachable arcs. A failure edge scales a shared tree, and an explicit symbol overrides a single leaf, even at zero weight. This uses distributivity and requires only semiring operations. Following a linear scan of the declared topology and weight source, each reached fallback needs at most one tree update, and each reached ordinary edge needs logarithmically many in the number of distinct reached symbols. State and work limits apply to the reachable graph and tree updates. The calculation keeps derivatives through the original weights for differentiable semirings.

Static deterministic minimization

minimize_static_acceptor snapshots a one-tape Markov acceptor, removes zero-weight arcs and marks, and trims states outside its positive support. The remaining graph must be acyclic. Each state must have at most one outgoing arc per symbol, with all arcs consuming one symbol.

For a state \(q\), let \(R_q\) be its weighted suffix series and \(g_q\) the rational greatest common divisor of its nonzero coefficients. Outgoing labels have disjoint suffix supports. Thus \(g_q\) is the gcd of the final weight and the products \(w(q,a,t)g_t\) over outgoing arcs. A pass from the leaves computes \(g_q\) and hashes a signature containing the final weight divided by \(g_q\), the scaled outgoing weights, and the successor classes. Equality of signatures is equivalent to equality of \(R_q/g_q\) by induction on the maximum suffix length. Multiplying the original initial weight by \(g_q\) preserves the weighted language. Any epsilon-free deterministic acceptor with one initial state must distinguish positive prefixes whose residual series are not proportional, so this construction uses the minimum number of states.

The pass performs one rational gcd per retained arc and sorts each state's outgoing labels. Its work also includes validating the source weight slots and the input topology. Rational arithmetic costs depend on coefficient bit lengths. Coefficients in the result must be exactly representable in the input floating-point dtype. Trainable weights are refused because changing them can change the equivalence classes.

minimize_static_acceptor_with_work also accepts cyclic positive support. For each productive state \(q\), let \(u_q\) be its least accepted suffix in length-then-symbol order and let \(p_q=R_q(u_q)>0\). A reverse breadth-first traversal finds the distance to a final mark. A pass in increasing distance uses the least first symbol that decreases the distance, multiplying its weight by the already computed scale of its target. This is finite-suffix weight pushing over exact rationals. Eisner (2003), §6.

The quotient construction scales an initial coefficient at \(q\) by \(p_q\), divides a final coefficient at \(q\) by \(p_q\), and replaces an arc coefficient \(w(q,a,t)\) by \(w(q,a,t)p_t/p_q\). These factors telescope on every finite word. The argument applies even if the sum of the weights of all words diverges. Two nonzero residuals are positively proportional if and only if their normalized series agree, since proportional series have the same support and hence the same least suffix. Equality of normalized series forces equal final coefficients and equal support after every symbol. The normalized target series assign weight one to the same least suffix, so evaluating this suffix also forces the two pushed arc weights to agree. The resulting partition is thus exactly the stable partition of the deterministic partial automaton with final weights as state observations and (symbol, pushed weight) as labels. Each class represents a nonzero residual of a reachable prefix, up to its positive prefix scale. An equivalent deterministic epsilon-free one-initial acceptor must reach a different state for each such class, since two prefixes reaching one state have proportional residuals. This gives the state lower bound for the class in which minimization is claimed.

Refinement initially queues all final-weight blocks. Each popped block only examines its own states and their incoming arcs, grouped by label. If two states remain in the same source block but a label takes them to distinct target blocks, at least one of the defined target blocks remains queued. Processing that block separates the sources. Splitting a queued block retains both children in the queue. Splitting any other block adds its smaller child, which suffices for this invariant when targets first separate. A state returns to the queue after processing only in a block of at most half its previous processed size. With \(V\) productive states and \(E\) productive arcs, the measured state and predecessor visits are thus bounded by \(V(1+\lfloor\log_2 V\rfloor)\) and \(E(1+\lfloor\log_2 V\rfloor)\) respectively for \(V>0\). Grouping and splitting use expected constant-time hash operations per record at fixed key size. Preprocessing is linear in the input records, and rational arithmetic and coefficient storage depend separately on bit length. This uses sparse partial-automaton refinement. Hopcroft (1971), Valmari and Lehtinen (2008), §§2–5.

StaticMinimizationWork reports input records, productive states and arcs, and the two refinement counts. max_states bounds the productive states, and max_work bounds the input records plus the two refinement counts. The returned snapshot uses the input dtype and device. The shortest-suffix gauge can produce coefficients outside the original floating-point dtype, even from exactly represented source weights. The routine raises in that case. The acyclic gcd entry point retains its own gauge and coefficient ordering.

Ranked constraints for a fixed input

ranked_output_candidates restricts a candidate generator to one input word. Each original arc occurrence carries a vector of nonnegative integer violations. Each path sums its vectors and the highest-ranked coordinate on which two candidates differ determines their order. The returned acceptor keeps every globally optimal path and retains the original sources of its semiring weights. Ranking considers structural paths even when their current semiring weight is zero.

For each state \(q\) in the fixed-input graph, a reverse Dijkstra pass computes its least lexicographic suffix rank \(d_q\). Lexicographic order is translation-invariant and every arc rank is nonnegative in that order. An arc \(q \to t\) with rank \(v\) belongs to an optimal suffix exactly when \(d_q = v + d_t\). The construction keeps these tight arcs and the least-ranked initial marks, then trims inaccessible arcs. Summing the equality along any retained accepting path gives the global optimum. Conversely, a globally optimal path has no positive rank slack at any step. A retained cycle can contain only zero violation vectors. Finite-state weight queries use their ordinary closure contract if such a cycle emits no output.

For \(Q\) reached configurations, \(E\) examined compatible transitions, and \(r\) coordinates, the ranking pass takes \(O(Q + E + (Q + E)r \log(Q + E + 1))\) operations counting each integer operation as one. Building the fixed-input graph obeys its explicit state and work budgets and also scans the original topology and rank table. The acceptor describes candidates for this input alone. Compiling one transducer for arbitrary ranked inputs requires additional regularity hypotheses.

Uniform compilation for capped ranked constraints

compile_ranked_ot compiles a single transducer for all inputs when each violation count has an explicit finite cap. A cap of one records whether a constraint has been violated. The count update adds the arc's violations, then clips each coordinate at its cap.

Each weighted product state records the current candidate and its capped vector. It also records the set of all candidate configurations reachable by consuming the same input prefix. This set is closed under input-epsilon transitions. A consuming transition updates the set for its input symbol and takes the epsilon closure again. The construction retains all reachable vectors, since saturation can reverse the ordering of two prefix vectors after they receive the same further violations.

An original path uniquely determines its weighted product path. That path accepts exactly when the original path ends in a final state and its rank equals the minimum among all final configurations in the competitor set. The competitor set filters the original paths without contributing any weight or alignment multiplicity. All tied original paths keep their weights, and sharing through the original parameters remains live.

The compiler visits reachable weighted product states and caches competitor transitions by state set and observed label. It does not iterate over the entire alphabet or the entire cap product. Nevertheless the number of reachable sets can be exponential. State and work limits give explicit failure when exploration exceeds the supplied budgets. The caps define the model, and the limits bound construction.

Beam-pruned finite string beliefs

FiniteStringBeliefPlan.run_pruned applies synchronous sum-product over the declared typed candidate supports. It ranks each proposed factor-to-variable message by raw marginal weight, breaks ties by lexicographic word order, and normalizes the retained positive weights. The full and omitted masses use the same gauge, with incoming variable cavities normalized before the factor sum. These masses refer to the declared finite candidates.

Damping first restricts the old message to the positive support of the new pruned proposal. When the old message has positive retained mass, the update mixes the two normalized vectors on this support. When their positive supports are disjoint, the update uses the new proposal. Every transmitted message after the first sweep thus has at most the requested positive support size.

The reported total-variation residual compares the current messages with the undamped pruned proposal. converged describes this approximate update. The result also records positive omitted mass across completed proposal evaluations and per-message masses for the latest complete proposal. A hard support conflict reports empty_support with no normalized beliefs. Plan construction still reports resource exhaustion through the configured state, work, and factor-entry limits.

The declared factor tables are built within those limits. The beam caps positive message support and leaves the factor-table allocation bound in place. Derivatives follow the executed updates with beam choices held fixed.

Certified marginal error on a bounded Markov restriction

certify_pruned_string_beliefs runs the same beam schedule and compares each returned belief with its exact marginal in the graph restricted to the declared finite supports. Each factor query must be acyclic with positive Markov weight on every cell of its effective axes. Observations restrict their axes before verification. The bound uses the evaluated binary64 factor slots from the same live snapshot and exact rational path sums, including separate parallel occurrences. The bound concerns the values of the marginal distributions. The ordinary returned scores retain their finite-schedule gradients.

Write \(K_i(\cdot\mid x)\) for the model's single-site conditional. For each pair of neighboring variables, the verifier computes \(C_{ij}\), the largest total variation in \(K_i\) under a change in the value of \(j\) alone. The maximum row sum \(\alpha\) must be strictly below one. Directed exponentiation encloses the mathematical weights of the returned binary64 log scores. Let \(q_i\) normalize their lower endpoints. If the lower and upper endpoint sums are \(A_i\) and \(B_i\), respectively, then the exact normalization of the returned row contains \(q_i\) as a mixture component of mass at least \(A_i/B_i\). The conversion allowance is thus \(1-A_i/B_i\).

Let \(Q\) be the product of the reference marginals \(q_i\). Let \(e_i\) and \(m_i\) be the mean under \(Q\) and the maximum over boundary configurations of \(\operatorname{TV}(K_i(\cdot\mid x),q_i)\). A stationary coupling of the exact model and \(Q\) updates both laws at the same uniformly chosen site. For that update, a maximal coupling and the single-neighbor bounds give coordinate mismatch probabilities \(d_i\leq e_i+\sum_j C_{ij}d_j\). Thus \(D=\min(1,\max_i e_i/(1-\alpha))\) bounds every \(d_i\). The direct conditional-mixture bound also gives \(\operatorname{TV}(\mu_i,q_i)\leq m_i\), where \(\mu_i\) is the true marginal. The reported bound caps at one the smaller of \(m_i\) and \(e_i+D\sum_j C_{ij}\), plus the conversion allowance. This is the singleton finite Gibbs comparison setting. Rebeschini and van Handel, Corollaries 2.6 and 2.8

This calculation is valid for a finite schedule, including a returned pruned belief with zero coordinates. It uses the actual model blankets and the returned probability rows. A convergence flag or rounded message residual cannot establish these bounds. Graph support failure, insufficient contraction, unsupported closure, and resource exhaustion have separate diagnostics.

Writing \(S_i\) for effective support size and \(P_i\) for the product of neighbor support sizes, the local cell cap charges \(\sum_i S_i P_i\) before allocating the conditionals. Each site uses the product of its incident factor entries for each cell. There are \(\sum_i P_i\sum_{j\sim i}(S_j-1)/2\) compared boundary pairs, each comparing \(S_i\) entries at site \(i\). The rational operation and unreduced bit caps cover the exact arithmetic. The directed exponentials have separate work and range limits. Exact factor verification makes one further pass over the original path plans under their existing observation bounds. The verifier enumerates local blankets, which can be large for high-degree graphs.

relations

Sparse weighted relations over strings and finite observations of them.

EPSILON module-attribute

EPSILON = None

An arc with epsilon on a tape consumes no symbol on that tape.

Label

Label = int | None

A symbol index or None for epsilon.

Words

Words = tuple[tuple[int, ...], ...]

One word on each tape in tape order.

RationalRelation

RationalRelation(topology: RelationTopology, weights: Tensor | Module, *, algebra: Semiring = REAL)

Bases: Morphism

A finite-state representation of a weighted relation on ordered tapes.

At every fixed tuple of words, the relation sums the weights of all accepting walks realizing that tuple. A walk's weight multiplies its initial weight, its arc weights in traversal order, and its final weight. An empty walk contributes its initial and final weights. Topology and parameter values are separate.

PARAMETER DESCRIPTION
topology

Finite topology and weight-slot names.

TYPE: RelationTopology

weights

A vector of scalar weights in slot order, with every entry in the declared algebra's carrier. A tensor must be a leaf. A module supplies the vector through its zero-argument forward call and can compute fresh differentiable weights from its parameters.

TYPE: Tensor or Module

algebra

The scalar algebra for path multiplication and addition. Defaults to real weights.

TYPE: Semiring DEFAULT: REAL

Notes

Fixed-word queries accept cycles that consume symbols, because each such step advances a position in a finite observation. A reachable all-epsilon cycle with an accepting continuation requires a star calculation. Supplying max_closure_size to query admits productive cyclic components under an established semiring star. The plan depends on topology and records zero-weight occurrences. Each evaluation checks the current weight vector and the numerical domain of every closure it uses.

Source code in src/quivers/core/relations/__init__.py
def __init__(
    self,
    topology: RelationTopology,
    weights: torch.Tensor | nn.Module,
    *,
    algebra: Semiring = REAL,
) -> None:
    if not isinstance(algebra, Semiring) or algebra.element_shape:
        raise TypeError("a rational relation requires a scalar semiring")
    super().__init__(
        _tape_object(topology.tapes[: topology.input_tapes]),
        _tape_object(topology.tapes[topology.input_tapes :]),
        algebra,
    )
    self._topology = topology
    if isinstance(weights, torch.Tensor):
        self._check_weights(weights)
        self._weight_source = _TensorWeights(weights)
    elif isinstance(weights, nn.Module):
        self._weight_source = weights
    else:
        raise TypeError("weights must be a tensor or a weight source module")

topology property

topology: RelationTopology

The immutable topology of this relation.

module

module() -> Module

The original weight source and its parameters.

Source code in src/quivers/core/relations/__init__.py
def module(self) -> nn.Module:
    """The original weight source and its parameters."""
    return self._weight_source

query

query(words: Words, *, max_states: int | None = None, max_work: int | None = None, max_closure_size: int | None = None) -> FixedStringQuery

Compile a reusable query for one tuple of words.

PARAMETER DESCRIPTION
words

Observations in tape order. Each word contains only symbols of its tape's alphabet.

TYPE: Words

max_states

Limit on visited state and offset configurations.

TYPE: int or None DEFAULT: None

max_work

Limit on candidate arc examinations, including rejected matches.

TYPE: int or None DEFAULT: None

max_closure_size

Maximum order of each local star matrix, including auxiliary vertices for parallel arcs. None requires an acyclic productive graph.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
FixedStringQuery

The query and construction counts.

RAISES DESCRIPTION
RelationLimitError

If a construction limit is reached before the query is ready.

ProductiveEpsilonCycleError

If the productive graph has a cycle and closure was not requested.

Source code in src/quivers/core/relations/__init__.py
def query(
    self,
    words: Words,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
    max_closure_size: int | None = None,
) -> FixedStringQuery:
    """Compile a reusable query for one tuple of words.

    Parameters
    ----------
    words : Words
        Observations in tape order. Each word contains only symbols
        of its tape's alphabet.
    max_states : int or None
        Limit on visited state and offset configurations.
    max_work : int or None
        Limit on candidate arc examinations, including rejected matches.
    max_closure_size : int or None
        Maximum order of each local star matrix, including auxiliary
        vertices for parallel arcs. None requires an acyclic
        productive graph.

    Returns
    -------
    FixedStringQuery
        The query and construction counts.

    Raises
    ------
    RelationLimitError
        If a construction limit is reached before the query is ready.
    ProductiveEpsilonCycleError
        If the productive graph has a cycle and closure was not requested.
    """
    return FixedStringQuery(
        self,
        words,
        max_states=max_states,
        max_work=max_work,
        max_closure_size=max_closure_size,
    )

weight

weight(words: Words) -> Tensor

Evaluate the total accepting walk weight for the supplied words.

PARAMETER DESCRIPTION
words

One observed word per tape, in tape order.

TYPE: Words

RETURNS DESCRIPTION
Tensor

The scalar in the relation's algebra.

Source code in src/quivers/core/relations/__init__.py
def weight(self, words: Words) -> torch.Tensor:
    """Evaluate the total accepting walk weight for the supplied words.

    Parameters
    ----------
    words : Words
        One observed word per tape, in tape order.

    Returns
    -------
    torch.Tensor
        The scalar in the relation's algebra.
    """
    return self.query(words).weight()

conditional

conditional(input_words: Words, *, max_states: int, max_work: int, max_closure_size: int | None = None) -> ConditionalStringQuery

Compile a conditional over outputs for the fixed input words.

Source code in src/quivers/core/relations/__init__.py
def conditional(
    self,
    input_words: Words,
    *,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
) -> ConditionalStringQuery:
    """Compile a conditional over outputs for the fixed input words."""
    return ConditionalStringQuery(
        self,
        input_words,
        max_states=max_states,
        max_work=max_work,
        max_closure_size=max_closure_size,
    )

total_weight

total_weight(*, max_states: int | None = None, max_work: int | None = None, max_closure_size: int | None = None) -> Tensor

Sum the weights of all accepting walks over every word tuple.

One additional linear pass erases the tape labels. The usual state, arc examination and closure limits then apply. A productive cycle requires the established star to decide a usable weight for its component.

Source code in src/quivers/core/relations/__init__.py
def total_weight(
    self,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
    max_closure_size: int | None = None,
) -> torch.Tensor:
    """Sum the weights of all accepting walks over every word tuple.

    One additional linear pass erases the tape labels. The usual
    state, arc examination and closure limits then apply. A
    productive cycle requires the established star to decide a
    usable weight for its component.
    """
    return self._total_query(max_states, max_work, max_closure_size).weight()

restrict

restrict(max_lengths: tuple[int, ...], *, max_entries: int, max_states: int | None = None, max_work: int | None = None) -> FiniteRelationRestriction

View a declared length restriction as a finite tensor morphism.

PARAMETER DESCRIPTION
max_lengths

Inclusive maximum lengths in tape order.

TYPE: tuple of int

max_entries

Maximum number of tensor entries, checked before allocation.

TYPE: int

max_states

Total product states that may be visited across the bounded table.

TYPE: int or None DEFAULT: None

max_work

Total candidate arc examinations across the bounded table.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
FiniteRelationRestriction

A differentiable view over the bounded string carriers.

Source code in src/quivers/core/relations/__init__.py
def restrict(
    self,
    max_lengths: tuple[int, ...],
    *,
    max_entries: int,
    max_states: int | None = None,
    max_work: int | None = None,
) -> FiniteRelationRestriction:
    """View a declared length restriction as a finite tensor morphism.

    Parameters
    ----------
    max_lengths : tuple of int
        Inclusive maximum lengths in tape order.
    max_entries : int
        Maximum number of tensor entries, checked before allocation.
    max_states : int or None
        Total product states that may be visited across the bounded table.
    max_work : int or None
        Total candidate arc examinations across the bounded table.

    Returns
    -------
    FiniteRelationRestriction
        A differentiable view over the bounded string carriers.
    """
    return FiniteRelationRestriction(
        self,
        max_lengths,
        max_entries=max_entries,
        max_states=max_states,
        max_work=max_work,
    )

RegularNgramProjection dataclass

RegularNgramProjection(status: Literal['converged', 'limit', 'stalled'], iterations: int, coefficients: Tensor, active_features: tuple[_Feature, ...], target_moments: Tensor, fitted_moments: Tensor, log_base_mass: Tensor, log_tilt_mass: Tensor, log_normalizer: Tensor, objective_change: Tensor, regularization: Tensor, optimality_residual: float, message: RationalRelation, full_candidate_states: int, retained_states: int, optimizer: _ProjectionOptimizer = 'backtracking', moment_evaluations: int = 0, frontier_sizes: tuple[int, ...] = (), frontier_checks: int = 0, restricted_moment_evaluations: int = 0)

An inclusive projection and the compact message for its active features.

The full coefficients and both moment vectors follow candidate feature order. The message uses a frozen weight snapshot and has unnormalized mass exp(log_normalizer). Its density relative to the original base is the exponential of the fitted feature score. The objective change is relative to the unpenalized base at zero. Moment evaluations count both initial distributions and every trial fitted distribution, including rejected backtracking trials. A finite frontier records the candidate count at each stage, the number of full-domain residual checks, and the number of moments evaluated with a strict subset of the candidate dictionary.

log_site_scale property

log_site_scale: Tensor

Log scale making the fitted tilt's total mass equal the target's.

RegularStringBelief dataclass

RegularStringBelief(relation: RationalRelation, log_normalizer: Tensor, max_states: int, max_work: int)

A finite regular relation and the log mass used to normalize it.

log_prob

log_prob(word: tuple[int, ...]) -> Tensor

Return the fitted belief's normalized log probability of a word.

Source code in src/quivers/core/relations/regular_ep.py
def log_prob(self, word: tuple[int, ...]) -> torch.Tensor:
    """Return the fitted belief's normalized log probability of a word."""
    score = self.relation.query(
        (word,), max_states=self.max_states, max_work=self.max_work
    ).weight()
    return score - self.log_normalizer

RegularStringEPResult dataclass

RegularStringEPResult(marginals: Mapping[str, RegularStringBelief], sites: tuple[RegularStringSite, ...], status: Literal['converged', 'limit', 'projection_failed'], sweeps: int, message_residual: float | None, updates: tuple[RegularStringSiteUpdate, ...], moment_evaluations: int = 0)

Approximate beliefs and site diagnostics with total moment evaluations.

The moment count covers every attempted local fit across the schedule. Updates retain the individual fit reports for the final pass.

RegularStringSite dataclass

RegularStringSite(factor: int, variable: str, features: tuple[_Word, ...], coefficients: Tensor, log_scale: Tensor)

A scaled n-gram factor-to-variable message.

RegularStringSiteUpdate dataclass

RegularStringSiteUpdate(factor: int, variable: str, log_tilt_mass: Tensor, fit: RegularNgramProjection)

One local projection and its tilted mass with normalized cavities.

RelationTopology dataclass

RelationTopology(tapes: tuple[StringSet, ...], input_tapes: int, n_states: int, arcs: tuple[Arc, ...], initial: tuple[Boundary, ...], final: tuple[Boundary, ...], weight_names: tuple[str, ...])

Finite directed multigraph independent of its weight values.

State and symbol IDs start at zero. Tape IDs are positions in tapes. The first input_tapes tapes make up the domain and the other tapes make up the codomain. Arc IDs are positions in arcs, which can include multiple identical arc records. The positions in weight_names are weight slots. Arc and boundary occurrences can refer to the same slot.

Arc dataclass

Arc(source: int, target: int, labels: tuple[Label, ...], weight: int)

One arc occurrence, identified by its position in the arc table.

ArcCounts dataclass

ArcCounts(arc_ids: tuple[int, ...], counts: Tensor, normalizer: Tensor)

Sparse expected traversal counts conditional on the observed words.

The one-dimensional counts tensor aligns with the original arc IDs and uses ordinary nonnegative reals. The normalizer is the observed path sum in the relation's algebra.

Boundary dataclass

Boundary(state: int, weight: int)

An initial or final state with a weight slot.

FixedStringQuery

FixedStringQuery(relation: RationalRelation, words: Words, *, max_states: int | None = None, max_work: int | None = None, max_closure_size: int | None = None)

A path plan with live access to the relation's weights.

PARAMETER DESCRIPTION
relation

The relation of the query.

TYPE: RationalRelation

words

One word per tape in tape order.

TYPE: Words

max_states

Limit on visited state and offset configurations.

TYPE: int or None DEFAULT: None

max_work

Limit on candidate arc examinations.

TYPE: int or None DEFAULT: None

max_closure_size

Maximum order of each local star matrix. None requires an acyclic productive graph.

TYPE: int or None DEFAULT: None

Source code in src/quivers/core/relations/__init__.py
def __init__(
    self,
    relation: RationalRelation,
    words: Words,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
    max_closure_size: int | None = None,
) -> None:
    relation.topology._validate_words(words)
    _validate_limits(max_states, max_work, max_closure_size)
    self._plan = _compile_paths(
        relation.topology,
        words,
        max_states=max_states,
        max_work=max_work,
        max_closure_size=max_closure_size,
    )
    self._relation = relation
    self._words = tuple(tuple(word) for word in words)
    self._max_states = max_states
    self._max_work = max_work
    self._max_closure_size = max_closure_size

work property

work: QueryWork

Work of compiling this query.

max_path_length property

max_path_length: int | None

Return the maximum arc count over structurally accepting paths.

The productive graph must be acyclic. A graph without accepting paths has no maximum. The bound includes paths whose current weights are zero, since subsequent weight changes may enable them.

weight

weight(*, recompute_backward: bool = False) -> Tensor

Evaluate the plan with the current weights.

A cyclic plan requires floating-point weights and an algebra that establishes the semiring laws and the least-solution law of its star. Closure can raise DivergentClosureError or UndecidedClosureError for the current weights.

With recompute_backward, autograd retains the path-plan inputs and recomputes required intermediate values during backward. The weight source runs once, outside the checkpoint.

Source code in src/quivers/core/relations/__init__.py
def weight(self, *, recompute_backward: bool = False) -> torch.Tensor:
    """Evaluate the plan with the current weights.

    A cyclic plan requires floating-point weights and an algebra that
    establishes the semiring laws and the least-solution law of its
    star. Closure can raise `DivergentClosureError` or
    `UndecidedClosureError` for the current weights.

    With `recompute_backward`, autograd retains the path-plan inputs
    and recomputes required intermediate values during backward.
    The weight source runs once, outside the checkpoint.
    """
    weights = self._relation._weights()
    algebra = self._relation.algebra
    if recompute_backward and torch.is_grad_enabled() and weights.requires_grad:
        from torch.utils.checkpoint import checkpoint

        return checkpoint(
            self._plan.evaluate, weights, algebra, use_reentrant=False
        )
    return self._plan.evaluate(weights, algebra)

best_path

best_path() -> RelationPath | None

Return the highest-weight positive path, if the query has one.

The productive graph must be acyclic, and weights must belong to Markov or LogProb. The result identifies a single path.

Source code in src/quivers/core/relations/__init__.py
def best_path(self) -> RelationPath | None:
    """Return the highest-weight positive path, if the query has one.

    The productive graph must be acyclic, and weights must belong
    to Markov or LogProb. The result identifies a single path.
    """
    paths = self.k_best_paths(1)
    return paths[0] if paths else None

best_path_weight

best_path_weight() -> Tensor

Return the best positive path weight, or the semiring zero.

The same exact ranking and deterministic tie order as best_path select the path. The result differentiates its original occurrences with the selected path held fixed. At a tie the derivative is that of the selected path. If no positive path exists, the result is a constant semiring zero.

Source code in src/quivers/core/relations/__init__.py
def best_path_weight(self) -> torch.Tensor:
    """Return the best positive path weight, or the semiring zero.

    The same exact ranking and deterministic tie order as
    `best_path` select the path. The result differentiates its
    original occurrences with the selected path held fixed. At a
    tie the derivative is that of the selected path. If no positive
    path exists, the result is a constant semiring zero.
    """
    weights = self._relation._weights()
    algebra = self._relation.algebra
    paths = self._walks.k_best(1, weights, algebra)
    return paths[0].weight if paths else algebra.zero_like((), weights)

k_best_paths

k_best_paths(k: int) -> tuple[RelationPath, ...]

Return up to k positive paths in decreasing weight order.

Ties follow a deterministic order determined by the topology. Ranking compares the exact rational values of the stored binary weights. Each arc supplies a ranked stream of suffixes, and merging computes only the heads needed for the result. Zero-weight paths are omitted.

Source code in src/quivers/core/relations/__init__.py
def k_best_paths(self, k: int) -> tuple[RelationPath, ...]:
    """Return up to `k` positive paths in decreasing weight order.

    Ties follow a deterministic order determined by the topology.
    Ranking compares the exact rational values of the stored binary
    weights. Each arc supplies a ranked stream of suffixes,
    and merging computes only the heads needed for the result.
    Zero-weight paths are omitted.
    """
    if type(k) is not int or k < 0:
        raise ValueError("k must be a nonnegative integer")
    return self._walks.k_best(k, self._relation._weights(), self._relation.algebra)

path_log_prob

path_log_prob(initial_state: int, arc_ids: tuple[int, ...], final_state: int) -> Tensor

Score an original trace under the fixed-word path posterior.

The trace supplies its original initial state, ordered arc occurrence IDs, and original final state. Invalid or zero-weight traces have log probability negative infinity. The observed path mass must be positive and finite. The positive trace score and the normalizer use the same current weight source.

Source code in src/quivers/core/relations/__init__.py
def path_log_prob(
    self, initial_state: int, arc_ids: tuple[int, ...], final_state: int
) -> torch.Tensor:
    """Score an original trace under the fixed-word path posterior.

    The trace supplies its original initial state, ordered arc
    occurrence IDs, and original final state. Invalid or zero-weight
    traces have log probability negative infinity. The observed path
    mass must be positive and finite. The positive trace score and
    the normalizer use the same current weight source.
    """
    log_weights = self._log_path_weights()
    total = self._path_log_normalizer(log_weights)
    return self._walks.path_log_prob(
        self._words, initial_state, arc_ids, final_state, log_weights, total
    )

sample_path

sample_path(*, generator: Generator | None = None, max_steps: int | None = None) -> RelationPath

Draw a path conditional on the observed words.

Sampling uses float64 log-space suffix weights and a CPU generator. The observed Markov or LogProb mass must be positive and finite. A cyclic plan requires a supported closure and an explicit max_steps. An attempted traversal beyond that arc limit raises a resource error. The sampled path retains its original arc occurrences.

Source code in src/quivers/core/relations/__init__.py
def sample_path(
    self, *, generator: torch.Generator | None = None, max_steps: int | None = None
) -> RelationPath:
    """Draw a path conditional on the observed words.

    Sampling uses float64 log-space suffix weights and a CPU
    generator. The observed Markov or LogProb mass must be
    positive and finite. A cyclic plan requires a supported
    closure and an explicit max_steps. An attempted traversal
    beyond that arc limit raises a resource error.
    The sampled path retains its original arc occurrences.
    """
    return self._walks.sample(
        self._relation._weights(), self._relation.algebra, generator, max_steps
    )

expected_arc_counts

expected_arc_counts() -> ArcCounts

Return differentiable conditional expected arc traversal counts.

Two packed passes sum the prefixes and suffixes at each configuration. Occurrences of an original arc at different configurations are added after normalizing. The productive graph can use an explicitly permitted, finite closure. The Markov or LogProb normalizer must be positive and finite.

Source code in src/quivers/core/relations/__init__.py
def expected_arc_counts(self) -> ArcCounts:
    """Return differentiable conditional expected arc traversal counts.

    Two packed passes sum the prefixes and suffixes at each
    configuration. Occurrences of an original arc at different
    configurations are added after normalizing. The productive
    graph can use an explicitly permitted, finite closure. The
    Markov or LogProb normalizer must be positive and finite.
    """
    return self._walks.counts(self._relation._weights(), self._relation.algebra)

path_statistics

path_statistics(*, initial_costs: Tensor | None = None, arc_costs: Tensor | None = None, final_costs: Tensor | None = None) -> PathStatistics

Return path entropy and the expectation of optional additive costs.

The observed Markov or LogProb mass must be positive and finite. Its normalization is evaluated in log space, with explicit closure support for a cyclic observation. Costs have one row per original mark or arc, in topology order. Boundary and arc costs can be combined when their trailing shapes agree. Derivatives on the current positive support flow through the weights and costs. Probability-zero choices are masked.

Source code in src/quivers/core/relations/__init__.py
def path_statistics(
    self,
    *,
    initial_costs: torch.Tensor | None = None,
    arc_costs: torch.Tensor | None = None,
    final_costs: torch.Tensor | None = None,
) -> PathStatistics:
    """Return path entropy and the expectation of optional additive costs.

    The observed Markov or LogProb mass must be positive and
    finite. Its normalization is evaluated in log space, with
    explicit closure support for a cyclic observation. Costs have one row
    per original mark or arc, in topology order. Boundary and
    arc costs can be combined when their trailing shapes agree.
    Derivatives on the current positive support flow through
    the weights and costs. Probability-zero choices are masked.
    """
    return self._walks.statistics(
        self._relation._weights(),
        self._relation.algebra,
        initial_costs,
        arc_costs,
        final_costs,
    )

path_statistic_right_action

path_statistic_right_action(direction: tuple[float, ...], *, initial_costs: Tensor | None = None, arc_costs: Tensor | None = None, final_costs: Tensor | None = None) -> PathStatisticRightAction

Evaluate a scalar statistic along a raw Markov weight direction.

The observation must be structurally acyclic. The direction is the exact affine path w + t * direction for nonnegative t close to zero. All omitted cost groups select entropy. This explicit action is separate from the supportwise derivative of path_statistics.

PARAMETER DESCRIPTION
direction

One finite coefficient per original slot in slot order, in float64 working precision.

TYPE: tuple[float, ...]

initial_costs

Optional fixed float64 scalar costs in the original occurrence order, on the weight device.

TYPE: Tensor | None DEFAULT: None

arc_costs

Optional fixed float64 scalar costs in the original occurrence order, on the weight device.

TYPE: Tensor | None DEFAULT: None

final_costs

Optional fixed float64 scalar costs in the original occurrence order, on the weight device.

TYPE: Tensor | None DEFAULT: None

RETURNS DESCRIPTION
PathStatisticRightAction

The statistic and its finite right action, or the entropy value with a named refusal when support opens at first order.

RAISES DESCRIPTION
TypeError

If the raw carrier, direction, or costs are unsupported.

ValueError

If the direction crosses the Markov domain or no path has positive mass.

ProductiveEpsilonCycleError

If the directional observation needs cyclic closure.

FloatingPointError

If a required value or finite action does not fit working precision.

Source code in src/quivers/core/relations/__init__.py
def path_statistic_right_action(
    self,
    direction: tuple[float, ...],
    *,
    initial_costs: torch.Tensor | None = None,
    arc_costs: torch.Tensor | None = None,
    final_costs: torch.Tensor | None = None,
) -> PathStatisticRightAction:
    """Evaluate a scalar statistic along a raw Markov weight direction.

    The observation must be structurally acyclic. The direction is
    the exact affine path `w + t * direction` for nonnegative t
    close to zero. All omitted cost groups select entropy. This
    explicit action is separate from the supportwise derivative of
    `path_statistics`.

    Parameters
    ----------
    direction
        One finite coefficient per original slot in slot order, in
        float64 working precision.
    initial_costs, arc_costs, final_costs
        Optional fixed float64 scalar costs in the original occurrence
        order, on the weight device.

    Returns
    -------
    PathStatisticRightAction
        The statistic and its finite right action, or the entropy
        value with a named refusal when support opens at first order.

    Raises
    ------
    TypeError
        If the raw carrier, direction, or costs are unsupported.
    ValueError
        If the direction crosses the Markov domain or no path has positive mass.
    ProductiveEpsilonCycleError
        If the directional observation needs cyclic closure.
    FloatingPointError
        If a required value or finite action does not fit working precision.
    """
    weights = self._relation._weights().detach()
    if not isinstance(direction, tuple) or any(
        type(value) not in (int, float) for value in direction
    ):
        raise TypeError(
            "path right action requires a tuple of raw slot coefficients"
        )
    return self._walks.statistic_right_action(
        weights,
        weights.new_tensor(direction),
        self._relation.algebra,
        (initial_costs, arc_costs, final_costs),
    )

log_feature_moments

log_feature_moments(arc_logs: Tensor, *, initial_logs: Tensor | None = None, final_logs: Tensor | None = None, allow_cyclic: bool = False) -> tuple[Tensor, Tensor]

Return the log total mass and unnormalized log feature moments.

For each feature, the moment sums the path weight times the sum of its nonnegative feature increments. Observations use Markov or LogProb probability weights. Acyclic observations use the packed expectation carrier. The cyclic form uses the certified scalar component closures on both sides of each marked occurrence.

PARAMETER DESCRIPTION
arc_logs

Log increments with one row per original occurrence and the same nonempty feature axis, dtype, and device. A value of minus infinity contributes zero. Omitted boundary tables contribute zero increments.

TYPE: Tensor or None

initial_logs

Log increments with one row per original occurrence and the same nonempty feature axis, dtype, and device. A value of minus infinity contributes zero. Omitted boundary tables contribute zero increments.

TYPE: Tensor or None

final_logs

Log increments with one row per original occurrence and the same nonempty feature axis, dtype, and device. A value of minus infinity contributes zero. Omitted boundary tables contribute zero increments.

TYPE: Tensor or None

allow_cyclic

Use the marked-occurrence evaluator for a productive cycle. The query must also have an explicit closure size limit.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple of torch.Tensor

The scalar log path mass and the vector of log weighted sums. Zero mass or feature sums return minus infinity. With positive mass, subtract its log from the vector to normalize the sums. Derivatives flow on the current positive support.

RAISES DESCRIPTION
ProductiveEpsilonCycleError

The productive observation needs explicit cyclic moments.

(DivergentClosureError, UndecidedClosureError)

A required scalar closure diverges or cannot be certified.

TypeError

The relation does not have floating-point probability weights.

ValueError

A log feature table has the wrong shape or carrier.

OverflowError

A reduction produces NaN or positive infinity.

Source code in src/quivers/core/relations/__init__.py
def log_feature_moments(
    self,
    arc_logs: torch.Tensor,
    *,
    initial_logs: torch.Tensor | None = None,
    final_logs: torch.Tensor | None = None,
    allow_cyclic: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Return the log total mass and unnormalized log feature moments.

    For each feature, the moment sums the path weight times the sum
    of its nonnegative feature increments. Observations use Markov or
    LogProb probability weights. Acyclic observations use the packed
    expectation carrier. The cyclic form uses the certified scalar
    component closures on both sides of each marked occurrence.

    Parameters
    ----------
    arc_logs, initial_logs, final_logs : torch.Tensor or None
        Log increments with one row per original occurrence and the
        same nonempty feature axis, dtype, and device. A value of
        minus infinity contributes zero. Omitted boundary tables
        contribute zero increments.
    allow_cyclic : bool
        Use the marked-occurrence evaluator for a productive cycle.
        The query must also have an explicit closure size limit.

    Returns
    -------
    tuple of torch.Tensor
        The scalar log path mass and the vector of log weighted sums.
        Zero mass or feature sums return minus infinity. With positive
        mass, subtract its log from the vector to normalize the sums.
        Derivatives flow on the current positive support.

    Raises
    ------
    ProductiveEpsilonCycleError
        The productive observation needs explicit cyclic moments.
    DivergentClosureError, UndecidedClosureError
        A required scalar closure diverges or cannot be certified.
    TypeError
        The relation does not have floating-point probability weights.
    ValueError
        A log feature table has the wrong shape or carrier.
    OverflowError
        A reduction produces NaN or positive infinity.
    """
    return self._walks.log_feature_moments(
        self._relation._weights(),
        self._relation.algebra,
        arc_logs,
        initial_logs,
        final_logs,
        allow_cyclic=allow_cyclic,
    )

ComposedRelation

ComposedRelation(left: RationalRelation, right: RationalRelation)

Bases: Morphism

Binary sparse composition on a checked shared tape.

Each operand has one input tape and one output tape. The shared tape types must agree. The operands use the same scalar semiring, which must establish the semiring laws and commutative multiplication.

A query constructs only reachable product configurations compatible with its two outer words. The three-state filter assigns one product path to each compatible pair of accepting operand paths.

Source code in src/quivers/core/relations/calculus.py
def __init__(self, left: RationalRelation, right: RationalRelation) -> None:
    if not isinstance(left, RationalRelation) or not isinstance(
        right, RationalRelation
    ):
        raise TypeError("composition requires two rational relation operands")
    if any(
        len(operand.topology.tapes) != 2 or operand.topology.input_tapes != 1
        for operand in (left, right)
    ):
        raise TypeError(
            "composition requires one input and one output tape per operand"
        )
    if left.codomain != right.domain:
        raise TypeError("composition requires the same shared tape type")
    algebra = left.algebra
    if algebra is not right.algebra or not algebra.establishes(
        *SEMIRING_LAWS, TIMES_COMMUTATIVE
    ):
        raise TypeError("composition requires one established commutative semiring")
    super().__init__(left.domain, right.codomain, algebra)
    self._left = left
    self._right = right
    self._left_index = _arc_index(left.topology, 0, 1)
    self._right_index = _arc_index(right.topology, 1, 0)
    self._materialized: (
        tuple[
            tuple[int, int],
            RelationTopology,
            tuple[_WeightPair, ...],
            tuple[_ArcOrigin, ...] | None,
        ]
        | None
    ) = None
    left_module, right_module = left.module(), right.module()
    self._module = nn.ModuleList(
        (left_module,)
        if left_module is right_module
        else (left_module, right_module)
    )

algebra property

algebra: Semiring

The common scalar semiring.

module

module() -> Module

The two operands' original weight sources and their parameters.

Source code in src/quivers/core/relations/calculus.py
def module(self) -> nn.Module:
    """The two operands' original weight sources and their parameters."""
    return self._module

materialize

materialize(*, max_states: int, max_work: int) -> RationalRelation

Build a reusable, trimmed sparse product topology.

The limits bound the states and the sum of shared-label probes and arcs. They include intermediate states and arcs that retain the primitive factors of a matched pair. Trimming keeps the state IDs and removes arc and boundary records outside accepting paths. The last topology and weight-slot mapping can be reused for identical budgets. Each result reads both original weight sources on evaluation.

Source code in src/quivers/core/relations/calculus.py
def materialize(self, *, max_states: int, max_work: int) -> RationalRelation:
    """Build a reusable, trimmed sparse product topology.

    The limits bound the states and the sum of shared-label probes
    and arcs. They include intermediate states and arcs that retain
    the primitive factors of a matched pair. Trimming keeps the state
    IDs and removes arc and boundary records outside accepting paths.
    The last topology and weight-slot mapping can be reused for
    identical budgets.
    Each result reads both original weight sources on evaluation.
    """
    return self._materialize(max_states=max_states, max_work=max_work)[0]

query

query(words: Words, *, max_states: int | None = None, max_work: int | None = None) -> ComposedStringQuery

Compile a reusable plan for a pair of outer words.

max_states limits reached configurations, including initial pairs. max_work limits the sum of shared-label probes and candidate arc occurrences. A productive cycle on the fixed words requires a closure capability and raises ProductiveEpsilonCycleError.

Source code in src/quivers/core/relations/calculus.py
def query(
    self,
    words: Words,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
) -> ComposedStringQuery:
    """Compile a reusable plan for a pair of outer words.

    `max_states` limits reached configurations, including initial
    pairs. `max_work` limits the sum of shared-label probes and
    candidate arc occurrences. A productive cycle on the fixed
    words requires a closure capability and raises
    `ProductiveEpsilonCycleError`.
    """
    return ComposedStringQuery(
        self, words, max_states=max_states, max_work=max_work
    )

weight

weight(words: Words) -> Tensor

Sum the weights of compatible path pairs for the two outer words.

Source code in src/quivers/core/relations/calculus.py
def weight(self, words: Words) -> torch.Tensor:
    """Sum the weights of compatible path pairs for the two outer words."""
    return self.query(words).weight()

ComposedStringQuery

ComposedStringQuery(relation: ComposedRelation, words: Words, *, max_states: int | None = None, max_work: int | None = None)

A fixed-word composition plan with live operand weights.

Source code in src/quivers/core/relations/calculus.py
def __init__(
    self,
    relation: ComposedRelation,
    words: Words,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
) -> None:
    if len(words) != 2:
        raise ValueError("composition queries require two outer words")
    left, right = relation._left, relation._right
    left.topology._validate_words((words[0], ()))
    right.topology._validate_words(((), words[1]))
    _validate_limits(max_states, max_work)
    self._relation = relation
    self._plan = _compile_composition(
        left.topology,
        right.topology,
        relation._left_index,
        relation._right_index,
        words,
        max_states=max_states,
        max_work=max_work,
    )

work property

work: QueryWork

Reached and productive configuration and arc counts.

label_probes property

label_probes: int

Shared labels examined when matching two allowed outer-label groups.

weight

weight() -> Tensor

Read fresh operand weights and evaluate the packed plan.

Source code in src/quivers/core/relations/calculus.py
def weight(self) -> torch.Tensor:
    """Read fresh operand weights and evaluate the packed plan."""
    left, right = self._relation._operand_weights()
    return self._plan.evaluate(left, right, self._relation.algebra)

ConditionalStringQuery

ConditionalStringQuery(relation: RationalRelation, input_words: Words, *, max_states: int, max_work: int, max_closure_size: int | None = None)

A sparse conditional distribution over all output word tuples.

The input words are fixed in tape order. The denominator sums every accepting path that agrees with them. An output query then sums only paths that also agree with its output words. Both sums use the same current weights and the same limits on productive closure.

Source code in src/quivers/core/relations/conditional.py
def __init__(
    self,
    relation: RationalRelation,
    input_words: Words,
    *,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
) -> None:
    if relation.algebra is not MARKOV and relation.algebra is not LOG_PROB:
        raise TypeError("conditional string queries require Markov or LogProb")
    if max_states is None or max_work is None:
        raise ValueError(
            "conditional string queries require explicit state and work limits"
        )
    _validate_limits(max_states, max_work, max_closure_size)
    topology = relation.topology
    if not 0 < topology.input_tapes < len(topology.tapes):
        raise ValueError(
            "conditional string queries require input and output tapes"
        )
    if len(input_words) != topology.input_tapes:
        raise ValueError(
            "a conditional string query requires a word for each input tape"
        )
    for tape, word in reversed(tuple(enumerate(input_words))):
        relation = condition(
            relation, tape, word, max_states=max_states, max_work=max_work
        )
    self._relation = relation
    self._max_states = max_states
    self._max_work = max_work
    self._max_closure_size = max_closure_size
    self._mass = relation._total_query(max_states, max_work, max_closure_size)

normalizer

normalizer() -> Tensor

Return the total output mass in the relation's algebra.

Source code in src/quivers/core/relations/conditional.py
def normalizer(self) -> torch.Tensor:
    """Return the total output mass in the relation's algebra."""
    return self._mass.weight()

log_prob

log_prob(output_words: Words) -> Tensor

Return the log probability of the supplied output word tuple.

Source code in src/quivers/core/relations/conditional.py
def log_prob(self, output_words: Words) -> torch.Tensor:
    """Return the log probability of the supplied output word tuple."""
    return self._evaluate_log_prob(self._output_query(output_words))

centered_query

centered_query(output_words: Words, *, max_center_occurrences: int, max_dyadic_work: int) -> Callable[[], CenteredStringLogScore]

Compile an opt-in centered binary64 LogProb likelihood.

Both the fixed-output and all-output productive observations must be acyclic. Each call reads one live weight vector and uses its exact binary64 factors to remove the large absolute log masses before packed summation. The limits bound occurrence storage and a worst-case count of exact pass visits.

Source code in src/quivers/core/relations/conditional.py
def centered_query(
    self, output_words: Words, *, max_center_occurrences: int, max_dyadic_work: int
) -> Callable[[], CenteredStringLogScore]:
    """Compile an opt-in centered binary64 LogProb likelihood.

    Both the fixed-output and all-output productive observations
    must be acyclic. Each call reads one live weight vector and
    uses its exact binary64 factors to remove the large absolute
    log masses before packed summation. The limits bound occurrence
    storage and a worst-case count of exact pass visits.
    """
    plan, weights = self._centered_binding(
        output_words,
        max_center_occurrences=max_center_occurrences,
        max_dyadic_work=max_dyadic_work,
    )

    def evaluate() -> CenteredStringLogScore:
        return plan.evaluate(weights())

    return evaluate

CenteredStringLogScore dataclass

CenteredStringLogScore(log_prob: Tensor, states: int, occurrences: int, weight_slots: int, dyadic_work: int)

A normalized log probability and work on its two acyclic charts.

The state and occurrence counts include both structurally productive observations. Occurrences include boundary marks. The dyadic work counts slot reads and state and occurrence visits in the exact pass.

ContextualEditChannel

ContextualEditChannel(input_tape: StringSet, output_tape: StringSet, scorer: Module, *, max_insertions: int)

Bases: Module

An edit channel scored from the entire fixed input.

At a position in the input and a current insertion count, the legal moves either consume the next symbol (with or without an output), insert an output symbol, or stop at the end of the input. The consecutive insertion bound ensures every path terminates.

PARAMETER DESCRIPTION
input_tape

The type of input words.

TYPE: StringSet

output_tape

The type of output words.

TYPE: StringSet

scorer

A module called once with the tuple of input words. It returns a floating tensor with axes example, input position (including an end position), insertion count, and action. The input position dimension is padded to the longest input length plus one. The action order is delete, stop, the insertions in output-alphabet order, and the replacements in output-alphabet order. The scorer can use arbitrary context from the supplied input words. The logits for a given input must be unchanged by batching with other inputs to define one probability model per example.

TYPE: Module

max_insertions

Maximum consecutive insertions. A consuming edit resets the count. The same bound applies at the end of the input.

TYPE: int

Source code in src/quivers/core/relations/contextual_edit.py
def __init__(
    self,
    input_tape: StringSet,
    output_tape: StringSet,
    scorer: nn.Module,
    *,
    max_insertions: int,
) -> None:
    super().__init__()
    if not isinstance(input_tape, StringSet) or not isinstance(
        output_tape, StringSet
    ):
        raise TypeError(
            "contextual edit input and output tapes must be StringSet objects"
        )
    if not isinstance(scorer, nn.Module):
        raise TypeError("contextual edit scoring requires a torch module")
    if type(max_insertions) is not int or max_insertions < 0:
        raise ValueError("max_insertions must be a nonnegative integer")
    self._input_tape = input_tape
    self._output_tape = output_tape
    self._scorer = scorer
    self._max_insertions = max_insertions

input_tape property

input_tape: StringSet

The nominal alphabet of the channel's fixed input context.

output_tape property

output_tape: StringSet

The nominal alphabet of the channel's generated words.

max_insertions property

max_insertions: int

The maximum consecutive insertions, including at end of input.

plan

plan(input_words: Words, output_words: Words, *, max_states: int, max_work: int) -> ContextualEditPlan

Plan a batch of observed pairs for repeated differentiable scoring.

Source code in src/quivers/core/relations/contextual_edit.py
def plan(
    self,
    input_words: Words,
    output_words: Words,
    *,
    max_states: int,
    max_work: int,
) -> ContextualEditPlan:
    """Plan a batch of observed pairs for repeated differentiable scoring."""
    return ContextualEditPlan(
        self, input_words, output_words, max_states=max_states, max_work=max_work
    )

global_plan

global_plan(input_words: Words, output_words: Words, *, max_states: int, max_work: int) -> ContextualEditPlan

Plan a batch using the raw scores and the all-output normalizer.

Source code in src/quivers/core/relations/contextual_edit.py
def global_plan(
    self,
    input_words: Words,
    output_words: Words,
    *,
    max_states: int,
    max_work: int,
) -> ContextualEditPlan:
    """Plan a batch using the raw scores and the all-output normalizer."""
    return ContextualEditPlan(
        self,
        input_words,
        output_words,
        max_states=max_states,
        max_work=max_work,
        normalization="global",
    )

forward

forward(input_words: Words, output_words: Words, *, max_states: int, max_work: int) -> Tensor

Return one alignment-marginal log probability per input-output pair.

Source code in src/quivers/core/relations/contextual_edit.py
def forward(
    self,
    input_words: Words,
    output_words: Words,
    *,
    max_states: int,
    max_work: int,
) -> torch.Tensor:
    """Return one alignment-marginal log probability per input-output pair."""
    return self.plan(
        input_words, output_words, max_states=max_states, max_work=max_work
    ).log_prob()

ContextualEditPlan

ContextualEditPlan(channel: ContextualEditChannel, input_words: Words, output_words: Words, *, max_states: int, max_work: int, normalization: _EditNormalization = 'local')

A reusable packed evaluation of a fixed batch of edit observations.

PARAMETER DESCRIPTION
channel

The channel and its original scorer.

TYPE: ContextualEditChannel

input_words

A nonempty batch of fixed input words.

TYPE: Words

output_words

One observed output word per input word.

TYPE: Words

max_states

Maximum total observation configurations across the batch. Global normalization includes the padded all-output suffix positions.

TYPE: int

max_work

Upper bound on padded action cells and compatible observation arcs. Global normalization also charges the padded action cells in the suffix computation.

TYPE: int

normalization

Normalize each action row, or normalize the sum of raw path scores over all outputs for each input. Global normalization uses binary64.

TYPE: ('local', 'global') DEFAULT: "local"

Source code in src/quivers/core/relations/contextual_edit.py
def __init__(
    self,
    channel: ContextualEditChannel,
    input_words: Words,
    output_words: Words,
    *,
    max_states: int,
    max_work: int,
    normalization: _EditNormalization = "local",
) -> None:
    if max_states is None or max_work is None:
        raise ValueError(
            "contextual edit scoring requires explicit state and work limits"
        )
    _validate_limits(max_states, max_work)
    if normalization not in ("local", "global"):
        raise ValueError("contextual edit normalization must be local or global")
    self._normalization = normalization
    if not input_words or len(input_words) != len(output_words):
        raise ValueError(
            "contextual edits require a nonempty batch of paired inputs and outputs"
        )
    self._inputs = inputs = tuple(map(tuple, input_words))
    outputs = tuple(map(tuple, output_words))
    _validate_words(inputs, channel._input_tape, "input")
    _validate_words(outputs, channel._output_tape, "output")
    self._alphabet_size = channel._output_tape.alphabet.cardinality
    self._scorer = channel._scorer
    self._lengths = tuple(map(len, inputs))
    self._shape = (
        len(inputs),
        max(self._lengths) + 1,
        channel._max_insertions + 1,
        2 + 2 * self._alphabet_size,
    )
    if normalization == "global":
        suffix_states = prod(self._shape[:-1])
        suffix_cells = prod(self._shape)
        if suffix_states > max_states:
            raise RelationLimitError(
                "contextual edit suffix chart exceeds max_states"
            )
        if 2 * suffix_cells > max_work:
            raise RelationLimitError(
                "contextual edit suffix action cells exceed max_work"
            )
        max_states -= suffix_states
        max_work -= suffix_cells
    self._packed, self._groups, self._supported = _compile(
        inputs, outputs, self._shape, max_states, max_work
    )

log_prob

log_prob() -> Tensor

Sum all paths realizing each pair under the selected conditional law.

Source code in src/quivers/core/relations/contextual_edit.py
def log_prob(self) -> torch.Tensor:
    """Sum all paths realizing each pair under the selected conditional law."""
    logits = self._scorer(self._inputs)
    if (
        not isinstance(logits, torch.Tensor)
        or logits.shape != self._shape
        or not logits.is_floating_point()
    ):
        raise ValueError(
            f"contextual edit logits must be a floating tensor of shape {self._shape}"
        )
    if not bool(torch.isfinite(logits).all()):
        raise ValueError("contextual edit logits must be finite")
    actions = (
        _global_log_actions(logits, self._lengths)
        if self._normalization == "global"
        else self._local_log_actions(logits)
    )
    packed = torch.cat((actions.reshape(-1), logits.new_zeros(1)))
    result = self._packed.evaluate(packed, LOG_PROB, final_groups=self._groups)
    supported = torch.tensor(self._supported, device=logits.device)
    if not bool((torch.isfinite(result) | ~supported).all()):
        raise OverflowError(
            "an observed contextual edit log probability is outside the input precision"
        )
    return result

QueryWork dataclass

QueryWork(visited_states: int, candidate_arcs: int, active_states: int, active_arcs: int, closure_sizes: tuple[int, ...] = ())

Graph counts and planned star matrix orders for a fixed-word query.

State and arc counts refer to the observation graph. Each entry of closure_sizes is the order of a local matrix, including any auxiliary vertices.

FailureArc dataclass

FailureArc(source: int, target: int, weight: int)

A weighted transition taken when a state lacks the requested symbol.

FiniteRelationRestriction

FiniteRelationRestriction(relation: RationalRelation, max_lengths: tuple[int, ...], *, max_entries: int, max_states: int | None = None, max_work: int | None = None)

Bases: FiniteMorphism

A size-checked finite tensor view of a rational relation.

PARAMETER DESCRIPTION
relation

The relation to restrict.

TYPE: RationalRelation

max_lengths

Inclusive bounds for tape lengths, in tape order.

TYPE: tuple of int

max_entries

Maximum number of entries in the resulting tensor.

TYPE: int

max_states

Total product states visited across the bounded table.

TYPE: int or None DEFAULT: None

max_work

Total candidate arc examinations across the bounded table.

TYPE: int or None DEFAULT: None

Source code in src/quivers/core/relations/__init__.py
def __init__(
    self,
    relation: RationalRelation,
    max_lengths: tuple[int, ...],
    *,
    max_entries: int,
    max_states: int | None = None,
    max_work: int | None = None,
) -> None:
    _validate_limits(max_states, max_work)
    if type(max_entries) is not int or max_entries < 1:
        raise ValueError("max_entries must be a positive integer")
    if len(max_lengths) != len(relation.topology.tapes):
        raise ValueError("a restriction must bound every tape")
    if any(type(length) is not int or length < 0 for length in max_lengths):
        raise ValueError("every tape length bound must be a nonnegative integer")
    remaining = max_entries
    carriers: list[FreeMonoid] = []
    for tape, length in zip(relation.topology.tapes, max_lengths):
        try:
            bounded = tape.bounded(length, max_size=remaining)
        except ValueError as error:
            raise RelationLimitError(
                "finite restriction exceeds max_entries"
            ) from error
        carriers.append(bounded)
        remaining //= bounded.size
    input_tapes = relation.topology.input_tapes
    super().__init__(
        _tape_object(tuple(carriers[:input_tapes])),
        _tape_object(tuple(carriers[input_tapes:])),
        relation.algebra,
    )
    self._carriers = tuple(carriers)
    self._relation = relation
    self._max_states = max_states
    self._max_work = max_work

tensor property

tensor: Tensor

Evaluate the bounded table using a fresh weight-source forward call.

module

module() -> Module

The original relation's weight source.

Source code in src/quivers/core/relations/__init__.py
def module(self) -> nn.Module:
    """The original relation's weight source."""
    return self._relation.module()

FiniteStringBeliefPlan

FiniteStringBeliefPlan(graph: StringFactorGraph, supports: Mapping[str, tuple[_Word, ...]], *, max_entries: int, max_states: int, max_work: int, max_closure_size: int | None = None)

Compile factor scores on explicit supports for loopy sum-product.

This is a finite model supplied by the caller. The gate on entries limits its construction, and does not impose a string length cutoff. Scores remain live and are read once per original weight source in each run. Factor tables follow the graph's declared tape order.

Source code in src/quivers/core/relations/beliefs.py
def __init__(
    self,
    graph: StringFactorGraph,
    supports: Mapping[str, tuple[_Word, ...]],
    *,
    max_entries: int,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
) -> None:
    if type(max_entries) is not int or max_entries < 0:
        raise ValueError("max_entries must be a nonnegative integer")
    if max_states is None or max_work is None:
        raise ValueError(
            "finite string messages require explicit state and work limits"
        )
    _validate_limits(max_states, max_work, max_closure_size)
    if set(supports) != graph._variables.keys():
        raise ValueError(
            "finite string supports must name every graph variable exactly once"
        )
    actual: dict[str, tuple[_Word, ...]] = {}
    for name, variable in graph._variables.items():
        words = tuple(tuple(word) for word in supports[name])
        if not words or len(words) != len(set(words)):
            raise ValueError(f"finite support for {name!r} requires distinct words")
        if any(
            type(symbol) is not int
            or not 0 <= symbol < variable.tape.alphabet.cardinality
            for word in words
            for symbol in word
        ):
            raise ValueError(
                f"finite support for {name!r} contains an invalid symbol"
            )
        if variable.observed is not None:
            if variable.observed not in words:
                raise ValueError(
                    f"finite support for {name!r} excludes its observation"
                )
            words = (variable.observed,)
        actual[name] = words
    self._supports = MappingProxyType(actual)
    self._tapes = {
        name: variable.tape for name, variable in graph._variables.items()
    }
    shapes = tuple(
        tuple(len(actual[name]) for name in factor.variables)
        for factor in graph._factors
    )
    if sum(prod(shape) for shape in shapes) > max_entries:
        raise RelationLimitError("finite string belief plan exceeds max_entries")
    occurrences: dict[str, list[_Occurrence]] = {name: [] for name in actual}
    factors = []
    for index, (factor, shape) in enumerate(
        zip(graph._factors, shapes, strict=True)
    ):
        for axis, name in enumerate(factor.variables):
            occurrences[name].append((index, axis))
        queries = []
        for words in product(*(actual[name] for name in factor.variables)):
            plan = factor.relation.query(
                words,
                max_states=max_states,
                max_work=max_work,
                max_closure_size=max_closure_size,
            )
            max_states -= plan.work.visited_states
            max_work -= plan.work.candidate_arcs
            queries.append(plan)
        factors.append(
            _FactorTable(factor.variables, factor.relation, shape, tuple(queries))
        )
    self._tables = tuple(factors)
    self._occurrences = occurrences
    self._ep_families: tuple[int, dict[str, NgramFamily]] | None = None

supports property

supports: Mapping[str, tuple[_Word, ...]]

The word order along each variable's finite axis.

run

run(*, max_sweeps: int, tolerance: float | None = 1e-09, damping: float = 0.0) -> StringBeliefResult

Run synchronous log-space messages on the declared model.

Damping mixes probabilities and lies in [0, 1). Convergence means the maximum undamped message total variation is within tolerance. The final residual is measured on the returned messages. A tolerance of None executes exactly the supplied number of sweeps. Autograd follows the executed schedule.

Source code in src/quivers/core/relations/beliefs.py
def run(
    self, *, max_sweeps: int, tolerance: float | None = 1e-9, damping: float = 0.0
) -> StringBeliefResult:
    """Run synchronous log-space messages on the declared model.

    Damping mixes probabilities and lies in [0, 1). Convergence
    means the maximum undamped message total variation is within
    tolerance. The final residual is measured on the returned
    messages. A tolerance of None executes exactly the supplied
    number of sweeps. Autograd follows the executed schedule.
    """
    _validate_sweeps(max_sweeps, tolerance, damping)
    tables, messages = self._start()
    like = tables[0]
    sweeps = 0
    while True:
        beliefs, cavities = self._variables(messages, like)
        proposed = tuple(
            tuple(
                map(
                    _normalized,
                    _outgoing(
                        table, tuple(cavities[f, i] for i in range(table.ndim))
                    ),
                )
            )
            for f, table in enumerate(tables)
        )
        residual = _message_residual(messages, proposed)
        converged = tolerance is not None and residual <= tolerance
        if converged or sweeps == max_sweeps:
            return StringBeliefResult(
                MappingProxyType(beliefs),
                "converged" if converged else "limit",
                sweeps,
                residual,
                messages,
            )
        if damping:
            messages = tuple(
                tuple(
                    LOG_PROB.join(
                        torch.stack((old + log(damping), new + log1p(-damping))),
                        dim=0,
                    )
                    for old, new in zip(old_factor, new_factor, strict=True)
                )
                for old_factor, new_factor in zip(messages, proposed, strict=True)
            )
        else:
            messages = proposed
        sweeps += 1

run_pruned

run_pruned(*, beam: int, max_sweeps: int, tolerance: float | None = 1e-09, damping: float = 0.0) -> PrunedStringBeliefResult

Run bounded top-weight messages on the declared finite supports.

Each raw proposal uses the normalized variable cavities. Its full and omitted log masses use this same gauge and are measured before normalization after pruning. Ties in the beam are resolved lexicographically by word. Damping projects the previous message onto the new proposal's positive support and normalizes it before mixing. With disjoint support, only the new proposal contributes.

The residual measures total variation from the undamped pruned proposal. Convergence concerns these approximate messages. Support failure may occur when hard pruning leaves no consistent variable or factor message. At least one sweep updates the uniform start before returning a converged or limited result.

Source code in src/quivers/core/relations/beliefs.py
def run_pruned(
    self,
    *,
    beam: int,
    max_sweeps: int,
    tolerance: float | None = 1e-9,
    damping: float = 0.0,
) -> PrunedStringBeliefResult:
    """Run bounded top-weight messages on the declared finite supports.

    Each raw proposal uses the normalized variable cavities. Its
    full and omitted log masses use this same gauge and are measured
    before normalization after pruning. Ties in the beam are resolved
    lexicographically by word. Damping projects the previous message
    onto the new proposal's positive support and normalizes it before
    mixing. With disjoint support, only the new proposal contributes.

    The residual measures total variation from the undamped pruned
    proposal. Convergence concerns these approximate messages.
    Support failure may occur when hard pruning leaves no consistent
    variable or factor message. At least one sweep updates the
    uniform start before returning a converged or limited result.
    """
    _validate_pruned_settings(beam, max_sweeps, tolerance, damping)
    return self._run_pruned(
        *self._start(),
        beam=beam,
        max_sweeps=max_sweeps,
        tolerance=tolerance,
        damping=damping,
    )

expectation_propagation

expectation_propagation(*, order: int, max_sweeps: int, tolerance: float | None = 1e-09, damping: float = 0.0, projection_tolerance: float = 1e-09, projection_penalty: float = 0.0, projection_max_iterations: int = 64, projection_max_backtracks: int = 16, initial_sites: _FiniteEPInitialSites | None = None) -> StringEPResult

Run fixed n-gram inclusive-KL updates over the declared support.

A site's projected marginal is divided by its normalized cavity and re-expressed as a normalized message. Damping interpolates log weights and preserves the family. The outer residual measures the undamped message update at the returned state. A failed local projection returns the preceding accepted state and the separate site diagnostic. A positive projection penalty uses the tree-group objective, with a proximal optimality residual and the same projection iteration limit. The backtracking limit applies to the unpenalized fit. Initial sites give factor position, variable, exact affine-basis order and finite coefficients. None starts each site at unit weight. Autograd follows the executed updates and local accepted steps.

Source code in src/quivers/core/relations/beliefs.py
def expectation_propagation(
    self,
    *,
    order: int,
    max_sweeps: int,
    tolerance: float | None = 1e-9,
    damping: float = 0.0,
    projection_tolerance: float = 1e-9,
    projection_penalty: float = 0.0,
    projection_max_iterations: int = 64,
    projection_max_backtracks: int = 16,
    initial_sites: _FiniteEPInitialSites | None = None,
) -> StringEPResult:
    """Run fixed n-gram inclusive-KL updates over the declared support.

    A site's projected marginal is divided by its normalized cavity
    and re-expressed as a normalized message. Damping interpolates
    log weights and preserves the family. The outer residual
    measures the undamped message update at the returned state.
    A failed local projection returns the preceding accepted state
    and the separate site diagnostic. A positive projection penalty
    uses the tree-group objective, with a proximal optimality
    residual and the same projection iteration limit. The
    backtracking limit applies to the unpenalized fit. Initial sites
    give factor position, variable, exact affine-basis order and
    finite coefficients. None starts each site at unit weight.
    Autograd follows the executed updates and local accepted steps.
    """
    _validate_sweeps(max_sweeps, tolerance, damping)
    _validate_projection_settings(
        projection_tolerance, projection_max_iterations, projection_max_backtracks
    )
    if not 0 <= projection_penalty < float("inf"):
        raise ValueError("projection_penalty must be nonnegative and finite")
    _validate_finite_ep_initial_sites(initial_sites)
    cached = self._ep_families
    if cached is None or type(order) is not int or order != cached[0]:
        families = {
            name: NgramFamily(words, order)
            for name, words in self._supports.items()
        }
        self._ep_families = order, families
    else:
        _, families = cached
    if initial_sites is not None:
        expected = tuple(
            (f, name, families[name].features)
            for f, factor in enumerate(self._tables)
            for name in factor.variables
        )
        if tuple(record[:3] for record in initial_sites) != expected:
            raise ValueError(
                "finite EP initial sites must match graph and affine-basis order"
            )
    tables, messages = self._start()
    like = tables[0]
    if like.dtype != torch.float64:
        raise TypeError("projected string messages require float64 factor weights")
    if initial_sites is not None:
        initial = iter(initial_sites)
        messages = tuple(
            tuple(
                _normalized(
                    like.new_tensor(families[name]._matrix)
                    @ like.new_tensor(next(initial)[3])
                )
                for name in factor.variables
            )
            for factor in self._tables
        )
    sweeps = projection_attempts = projection_iterations = line_search_trials = 0
    while True:
        beliefs, cavities = self._variables(messages, like)
        records: list[StringSiteProjection] = []
        proposed: list[tuple[torch.Tensor, ...]] = []
        for f, (table, factor) in enumerate(zip(tables, self._tables, strict=True)):
            local = tuple(cavities[f, axis] for axis in range(table.ndim))
            next_messages: list[torch.Tensor] = []
            for name, incoming, outgoing in zip(
                factor.variables, local, _outgoing(table, local), strict=True
            ):
                tilted = incoming + outgoing
                log_mass = LOG_PROB.join(tilted, dim=0)
                fit: NgramProjection | PenalizedNgramProjection | None = None
                projection_attempts += 1
                if bool(
                    torch.isfinite(log_mass) & ((tilted - log_mass).exp() > 0).all()
                ):
                    family = families[name]
                    if projection_penalty:
                        fit = family.project_penalized(
                            tilted,
                            penalty=projection_penalty,
                            base_log_weights=incoming,
                            tolerance=projection_tolerance,
                            max_iterations=projection_max_iterations,
                        )
                    else:
                        fit = family.project(
                            tilted,
                            base_log_weights=incoming,
                            tolerance=projection_tolerance,
                            max_iterations=projection_max_iterations,
                            max_backtracks=projection_max_backtracks,
                        )
                if fit is not None:
                    projection_iterations += fit.iterations
                    if isinstance(fit, NgramProjection):
                        line_search_trials += fit.line_search_trials
                if fit is None or fit.status != "converged":
                    problem = (
                        "tilted weights must be positive on the full support"
                        if fit is None
                        else f"local projection {fit.status}"
                    )
                    records.append(
                        StringSiteProjection(f, name, log_mass, fit, problem)
                    )
                    return StringEPResult(
                        MappingProxyType(beliefs),
                        "projection_failed",
                        sweeps,
                        None,
                        messages,
                        tuple(records),
                        projection_attempts,
                        projection_iterations,
                        line_search_trials,
                    )
                records.append(StringSiteProjection(f, name, log_mass, fit))
                next_messages.append(_normalized(fit.log_probabilities - incoming))
            proposed.append(tuple(next_messages))

        candidates = tuple(proposed)
        residual = _message_residual(messages, candidates)
        converged = tolerance is not None and residual <= tolerance
        if converged or sweeps == max_sweeps:
            return StringEPResult(
                MappingProxyType(beliefs),
                "converged" if converged else "limit",
                sweeps,
                residual,
                messages,
                tuple(records),
                projection_attempts,
                projection_iterations,
                line_search_trials,
            )
        messages = (
            tuple(
                tuple(
                    _normalized(damping * old + (1 - damping) * new)
                    for old, new in zip(old_factor, new_factor, strict=True)
                )
                for old_factor, new_factor in zip(messages, candidates, strict=True)
            )
            if damping
            else candidates
        )
        sweeps += 1

FiniteStringScore dataclass

FiniteStringScore(variables: tuple[str, ...], scores: Mapping[Words, Fraction | int])

An explicitly listed support with exact additive scores.

A key lists one full word for each named variable. Unlisted tuples are infeasible. The scores may be rational or integral, and may have either sign.

MarginalOutputChoice dataclass

MarginalOutputChoice(output: Words, exact_weight: Fraction, log_pair_weight: Tensor)

One positive candidate ranked by its exact alignment sum.

The log pair weight remains differentiable for this candidate. Selection itself is a discrete operation.

NgramFamily dataclass

NgramFamily(words: tuple[_Word, ...], order: int)

A fixed inclusive-KL family on a declared finite string support.

The features count contiguous n-grams of orders one through order. Exact elimination selects an affine basis of these counts on the support. A base measure can modulate the family at each call, including a cavity distribution for EP.

project

project(tilted_log_weights: Tensor, *, base_log_weights: Tensor | None = None, tolerance: float = 1e-09, max_iterations: int = 64, max_backtracks: int = 16) -> NgramProjection

Match tilted feature moments by minimizing inclusive KL.

Both measures require positive finite weights on the declared support, represented in float64 log space. Each Newton step checks the update in the convex moment objective. The tolerance is an infinity-norm bound on the feature residual. Autograd differentiates the accepted sequence of operations.

Source code in src/quivers/core/relations/projection.py
def project(
    self,
    tilted_log_weights: torch.Tensor,
    *,
    base_log_weights: torch.Tensor | None = None,
    tolerance: float = 1e-9,
    max_iterations: int = 64,
    max_backtracks: int = 16,
) -> NgramProjection:
    """Match tilted feature moments by minimizing inclusive KL.

    Both measures require positive finite weights on the declared
    support, represented in float64 log space. Each Newton step
    checks the update in the convex moment objective. The
    tolerance is an infinity-norm bound on the feature residual.
    Autograd differentiates the accepted sequence of operations.
    """
    _validate_projection_settings(tolerance, max_iterations, max_backtracks)
    base, target_log_prob, target = _projection_inputs(
        self.words, tilted_log_weights, base_log_weights
    )
    features = base.new_tensor(self._matrix)
    mean = target @ features
    coefficients = base.new_zeros(len(self.features))
    logits = base
    status: Literal["converged", "limit", "stalled"] = "limit"
    iteration = 0
    line_search_trials = 0
    while True:
        log_prob = logits.log_softmax(dim=0)
        prob = log_prob.exp()
        fit = prob @ features
        difference = fit - mean
        error = difference.abs().max().item() if difference.numel() else 0.0
        if not bool((prob > 0).all() & torch.isfinite(log_prob).all()):
            status = "stalled"
            break
        if error <= tolerance:
            status = "converged"
            break
        if iteration == max_iterations:
            break
        centered = features - fit
        hessian = centered.mT @ (prob[:, None] * centered)
        direction, info = torch.linalg.solve_ex(hessian, difference)
        decrement = (direction @ difference).item()
        if info.item() != 0 or not 0 < decrement < float("inf"):
            status = "stalled"
            break
        for backtrack in range(max_backtracks + 1):
            line_search_trials += 1
            step = 2.0**-backtrack
            proposed = coefficients - step * direction
            update = base + features @ proposed
            with torch.no_grad():
                offset = proposed - coefficients
                descent = -(difference @ offset).item()
                curvature = _centered_log_moment(log_prob, centered @ offset)
                accepted = (
                    0 < descent < float("inf")
                    and bool(torch.isfinite(update).all())
                    and curvature.item() <= (1 - 1e-4) * descent
                )
            if accepted:
                coefficients, logits = proposed, update
                break
        else:
            status = "stalled"
            break
        iteration += 1
    return NgramProjection(
        status,
        iteration,
        log_prob,
        coefficients,
        mean,
        fit,
        error,
        target @ (target_log_prob - log_prob),
        line_search_trials,
    )

project_penalized

project_penalized(tilted_log_weights: Tensor, *, penalty: float, base_log_weights: Tensor | None = None, tolerance: float = 1e-09, max_iterations: int = 512) -> PenalizedNgramProjection

Project with a positive tree-group penalty on all n-gram coefficients.

Each group contains the features sharing a given prefix, including that prefix when it is a feature. The empty prefix is a group. The objective adds penalty times the sum of group norms to inclusive KL. The residual measures the proximal gradient mapping in the infinity norm.

Source code in src/quivers/core/relations/projection.py
def project_penalized(
    self,
    tilted_log_weights: torch.Tensor,
    *,
    penalty: float,
    base_log_weights: torch.Tensor | None = None,
    tolerance: float = 1e-9,
    max_iterations: int = 512,
) -> PenalizedNgramProjection:
    """Project with a positive tree-group penalty on all n-gram coefficients.

    Each group contains the features sharing a given prefix, including
    that prefix when it is a feature. The empty prefix is a group.
    The objective adds `penalty` times the sum of group norms to
    inclusive KL. The residual measures the proximal gradient
    mapping in the infinity norm.
    """
    _validate_projection_settings(tolerance, max_iterations, 0)
    if not 0 < penalty < float("inf"):
        raise ValueError("tree-group penalty must be positive and finite")
    base, target_log_prob, target = _projection_inputs(
        self.words, tilted_log_weights, base_log_weights
    )
    features = base.new_tensor(self._full_matrix)
    # A common shift of every row leaves all fitted probabilities
    # fixed and gives a global covariance operator-norm bound.
    features = features - features[0]
    radius = features.square().sum(dim=1).max().item()
    step = 1.0 / radius if 0 < radius < float("inf") else 1.0
    if not radius < float("inf") or not 0 < step * penalty < float("inf"):
        raise OverflowError("tree-group objective exceeds the evaluation precision")
    groups = tuple(
        torch.tensor(group, dtype=torch.long, device=base.device)
        for group in self._penalty_groups
    )
    coefficients = base.new_zeros(len(self._vocabulary))
    mean = target @ features
    iteration = 0
    status: Literal["converged", "limit", "stalled"] = "limit"
    while True:
        fitted = (base + features @ coefficients).log_softmax(dim=0)
        probs = fitted.exp()
        gradient = probs @ features - mean
        proposed = _prefix_prox(
            coefficients - step * gradient, groups, step * penalty
        )
        mapping = (coefficients - proposed) / step
        error = mapping.abs().max().item() if mapping.numel() else 0.0
        if not (
            bool(torch.isfinite(fitted).all() & (probs > 0).all())
            and error < float("inf")
        ):
            status = "stalled"
            break
        if error <= tolerance:
            status = "converged"
            break
        if iteration == max_iterations:
            break
        coefficients = proposed
        iteration += 1
    norm_sum = sum(
        (
            torch.linalg.vector_norm(coefficients.index_select(0, group))
            for group in groups
        ),
        base.new_zeros(()),
    )
    return PenalizedNgramProjection(
        status,
        iteration,
        self._vocabulary,
        fitted,
        coefficients,
        error,
        target @ (target_log_prob - fitted),
        penalty * norm_sum,
    )

NgramMessagePlan

NgramMessagePlan(base: RationalRelation, features: tuple[tuple[int, ...], ...], *, max_states: int, max_work: int)

A deterministic n-gram score on a weighted regular language.

The message multiplies the weight of each word by the exponential of its linear n-gram score. Every original path emits that same word score, including paths with epsilon arcs or shared slots. The resulting relation retains the original alphabet and support.

PARAMETER DESCRIPTION
base

A one-tape relation with LogProb weights. The topology and original weight source are retained.

TYPE: RationalRelation

features

Distinct, nonempty n-grams in coefficient order. Symbols are integers from the base tape's alphabet.

TYPE: tuple[tuple[int, ...], ...]

max_states

Maximum product states reached from initial marks.

TYPE: int

max_work

Maximum trie and failure-link work, original transition examinations, and feature emissions in the reached product.

TYPE: int

Source code in src/quivers/core/relations/ngram_message.py
def __init__(
    self,
    base: RationalRelation,
    features: tuple[tuple[int, ...], ...],
    *,
    max_states: int,
    max_work: int,
) -> None:
    topology = base.topology
    if len(topology.tapes) != 1 or base.algebra is not LOG_PROB:
        raise TypeError("an n-gram message requires a one-tape LogProb relation")
    if max_states is None or max_work is None:
        raise ValueError("an n-gram message requires explicit construction limits")
    _validate_limits(max_states, max_work)
    size = topology.tapes[0].alphabet.cardinality
    features = tuple(map(tuple, features))
    if len(features) != len(set(features)) or any(
        not gram
        or any(type(symbol) is not int or not 0 <= symbol < size for symbol in gram)
        for gram in features
    ):
        raise ValueError(
            "n-gram message features must be distinct nonempty words in the base alphabet"
        )
    self._base = base
    self._features = features
    self._topology, self._slots, self._construction_work = _compile(
        topology, features, max_states, max_work
    )

features property

features: tuple[tuple[int, ...], ...]

Active feature identities in coefficient order.

n_states property

n_states: int

Reached product states in the compiled representation.

bind

bind(coefficients: Tensor | Module) -> RationalRelation

Expose the message relation with the original live coefficient source.

A leaf tensor can be supplied directly. A module must return a vector on the base weight device and dtype. Query normalization applies the ordinary finite-state closure contract.

Source code in src/quivers/core/relations/ngram_message.py
def bind(self, coefficients: torch.Tensor | nn.Module) -> RationalRelation:
    """Expose the message relation with the original live coefficient source.

    A leaf tensor can be supplied directly. A module must return a
    vector on the base weight device and dtype. Query normalization
    applies the ordinary finite-state closure contract.
    """
    if isinstance(coefficients, torch.Tensor):
        coefficients = _TensorWeights(coefficients)
    if not isinstance(coefficients, nn.Module):
        raise TypeError("n-gram coefficients require a tensor or weight module")
    source = _NgramMessageWeights(
        self._base, coefficients, len(self.features), self._slots
    )
    return RationalRelation(self._topology, source, algebra=LOG_PROB)

NgramProjection dataclass

NgramProjection(status: Literal['converged', 'limit', 'stalled'], iterations: int, log_probabilities: Tensor, coefficients: Tensor, target_moments: Tensor, fitted_moments: Tensor, moment_residual: float, divergence: Tensor, line_search_trials: int = 0)

An inclusive KL projection and its local optimizer diagnostics.

Iterations count accepted Newton updates. Line-search trials include rejected candidates and any terminal stalled search.

PathStatisticRightAction dataclass

PathStatisticRightAction(value: Tensor, tangent: Tensor | None, missing: str | None = None)

A scalar path statistic and its action along an explicit affine ray.

At an entropy support opening of first order, the value is defined and the right derivative is positive infinity. The reason is given in missing and the finite tangent is absent.

PARAMETER DESCRIPTION
value

The scalar statistic at the base point.

TYPE: Tensor

tangent

The finite directional action, if available.

TYPE: Tensor | None

missing

The reason that the direction has no finite action, if any.

TYPE: str | None DEFAULT: None

PathStatistics dataclass

PathStatistics(log_normalizer: Tensor, entropy: Tensor, expected_cost: Tensor | None)

Statistics of the conditional distribution over accepting paths.

The entropy is in nats. The normalizer is represented in log space for both input algebras. The expected cost sums the supplied feature or loss tensors along each path, including boundary marks.

PathWeightCertificate dataclass

PathWeightCertificate(weight: Tensor, lower: Fraction, upper: Fraction, absolute_error: Fraction, relative_error: Fraction | None, exact_work: int, exact_bits: int, closure_cells: int)

A scalar Markov weight and forward-error evidence for its input snapshot.

The weight is the normal differentiable packed result. The exact interval concerns the mathematical path sum of its evaluated binary weight vector. The error bounds apply to the returned scalar value. The relative bound is reported when requested. They give no assurance about its derivative or about computations that produced the input vector.

LogPathWeightCertificate dataclass

LogPathWeightCertificate(weight: Tensor, lower: Fraction | None, upper: Fraction | None, absolute_log_error: Fraction, decimal_work: int, exact_work: int, exact_bits: int)

A packed LogProb value and exact forward-error bounds in log units.

A verified zero mass has two absent log endpoints, a score of negative infinity, and zero error by convention. For positive mass, the two rational endpoints enclose its mathematical log weight. The bounds concern the evaluated binary64 slots and carry no derivative assurance.

PenalizedNgramProjection dataclass

PenalizedNgramProjection(status: Literal['converged', 'limit', 'stalled'], iterations: int, features: tuple[_Word, ...], log_probabilities: Tensor, coefficients: Tensor, optimality_residual: float, divergence: Tensor, regularization: Tensor)

Finite tree-group projection with its composite optimality residual.

ProductiveEpsilonCycleError

Bases: ValueError

The observation has a productive cycle outside the supported closure.

PrunedStringBeliefCertificate dataclass

PrunedStringBeliefCertificate(result: PrunedStringBeliefResult, total_variation: Mapping[str, Fraction], maximum_influence: Fraction, conditional_cells: int, boundary_pairs: int, exact_work: int, exact_bits: int, decimal_work: int)

The returned pruned beliefs and rational true marginal error bounds.

Each total variation bound compares the exact normalization of the corresponding returned binary64 log scores with the exact marginal on the effective finite model. The model uses the same evaluated binary64 Markov weight slots as the belief run. The maximum influence is the exact maximum Dobrushin row sum. The conditional cell count counts normalized single-site conditional entries across blankets. Boundary pairs count one-coordinate comparisons in those blankets. Exact and Decimal counters count verification arithmetic only.

PrunedStringBeliefResult dataclass

PrunedStringBeliefResult(log_marginals: Mapping[str, Tensor] | None, status: Literal['converged', 'limit', 'empty_support'], sweeps: int, message_residual: float | None, log_messages: _Messages, proposals: tuple[tuple[StringCandidateMessage, ...], ...], truncated: bool, diagnostic: str | None = None, exact: Literal[False] = False)

Approximate finite beliefs and diagnostics from a beam-limited schedule.

The log messages use the plan's declared candidate axes. A pruned coordinate has log weight negative infinity. The proposal records use factor and tape order and report raw masses before restriction and renormalization. If an attempted support has no normalized beliefs, the result records its messages and the support failure.

RelationLimitError

Bases: ValueError

The available construction budget does not suffice.

RelationAccuracyError

Bases: ArithmeticError

The available evaluation does not establish the requested accuracy.

RelationPath dataclass

RelationPath(initial_state: int, arc_ids: tuple[int, ...], final_state: int, weight: Tensor)

An accepting path, including its original arc occurrence IDs.

The initial and final states distinguish paths with no arcs. The weight is in the relation's algebra, with floating-point rounding at the input dtype, and retains its derivatives.

StringAlignment dataclass

StringAlignment(words: Words, start: int, arc_ids: tuple[int, ...], stop: int, base_score: Fraction, adjusted_score: Fraction)

One local maximizing path with original relation occurrence identities.

StringAlignmentCertificate dataclass

StringAlignmentCertificate(alignments: tuple[StringAlignment, ...], multipliers: _FrozenMultipliers)

Agreeing local maximizing paths and their exact n-gram potentials.

Alignments and multiplier groups are listed in factor order. One multiplier table per tape maps n-grams to exact rational weights. Symbols -1 and -2 mark the beginning and end of a word.

StringAlignmentMapResult dataclass

StringAlignmentMapResult(status: Literal['optimal', 'infeasible', 'gap', 'limit'], iterations: int, assignment: _Assignment | None, score: Fraction | None, upper_bound: Fraction | None, active_features: tuple[tuple[str, tuple[_Ngram, ...]], ...], max_local_states: int, local_arc_examinations: int, certificate: StringAlignmentCertificate | None = None, gap_target_met: bool = False, max_verification_states: int = 0, verification_arc_examinations: int = 0, feature_window_examinations: int = 0, feature_prefix_probes: int = 0, feature_count_symbol_visits: int = 0, feature_verification_symbol_visits: int = 0, peak_feature_cells: int = 0)

A joint alignment optimum, infeasibility, or a bounded search.

The score is from a feasible complete word assignment. The upper bound is the smallest adjusted score sum observed so far. Feature sets apply to the named variables. Local work includes both adjusted maximization and exact primal feasibility checks. Reaching a requested objective gap has status gap when the local paths have not agreed. Only optimal carries the agreement certificate. Verification counts cover the independent bound checks and original trace examinations, separately from the search. Feature counters distinguish ranked candidate windows, active prefix probes, direct update counts and independent witness counts. Peak feature cells give a charged bound on the associated buffers.

absolute_gap property

absolute_gap: Fraction | None

The exact upper bound on the feasible score's suboptimality.

relative_gap property

relative_gap: Fraction | None

The relative suboptimality bound when the objective scale permits it.

StringAlignmentTrace dataclass

StringAlignmentTrace(words: Words, start: int, arc_ids: tuple[int, ...], stop: int, score: Fraction)

One original factor's path and exact log score before dual shifts.

PairedAlignmentMapResult dataclass

PairedAlignmentMapResult(groups: _Groups, search: StringAlignmentMapResult, factor_traces: tuple[StringAlignmentTrace, ...] | None, product_shapes: tuple[tuple[int, int] | None, ...])

Grouped search and a feasible walk in each original factor.

search carries the verified local certificate in group order, with multipliers on the group's retained tape positions. An available factor_traces tuple follows original factor order, including on an uncertified returned primal. product_shapes gives the constructed state and arc counts of each pair in group order. Singleton groups have no product shape.

StringBeliefResult dataclass

StringBeliefResult(log_marginals: Mapping[str, Tensor], status: Literal['converged', 'limit'], sweeps: int, message_residual: float, log_messages: _Messages)

The marginal estimates and measured fixed-point residual of a sweep.

StringEPResult dataclass

StringEPResult(log_marginals: Mapping[str, Tensor], status: Literal['converged', 'limit', 'projection_failed'], sweeps: int, message_residual: float | None, log_messages: _Messages, site_projections: tuple[StringSiteProjection, ...], projection_attempts: int = 0, projection_iterations: int = 0, line_search_trials: int = 0)

Finite string beliefs and separate outer and local diagnostics.

Site projections retain the final pass. The three cumulative work counts include all passes and any failing attempt.

StringSiteProjection dataclass

StringSiteProjection(factor: int, variable: str, log_tilt_mass: Tensor, fit: NgramProjection | PenalizedNgramProjection | None, diagnostic: str | None = None)

The tilted normalization and fit for one factor-to-variable site.

StringFactor dataclass

StringFactor(variables: tuple[str, ...], relation: RationalRelation)

A relation with one distinct named variable assigned to each tape.

StringFactorGraph

StringFactorGraph(variables: tuple[StringVariable, ...], factors: tuple[StringFactor, ...])

A checked graph of typed variables and weighted rational factors.

Factors share one Markov or LogProb algebra. Exact tree inference accepts forests whose intermediate relation joins and closure calculations meet the supplied limits.

Source code in src/quivers/core/relations/graph.py
def __init__(
    self, variables: tuple[StringVariable, ...], factors: tuple[StringFactor, ...]
) -> None:
    self._variables = {variable.name: variable for variable in variables}
    if len(self._variables) != len(variables):
        raise ValueError("string variable names must be distinct")
    if not factors:
        raise ValueError("a string factor graph requires at least one factor")
    self._factors = tuple(factors)
    algebra = factors[0].relation.algebra
    if algebra is not MARKOV and algebra is not LOG_PROB:
        raise TypeError("exact string factors require Markov or LogProb algebra")
    self._neighbours: dict[_Vertex, list[_Vertex]] = {
        name: [] for name in self._variables
    }
    for factor_id, factor in enumerate(factors):
        if factor.relation.algebra is not algebra:
            raise TypeError("string factors require one shared algebra")
        self._neighbours[factor_id] = list(factor.variables)
        for name, tape in zip(
            factor.variables, factor.relation.topology.tapes, strict=True
        ):
            variable = self._variables.get(name)
            if variable is None or variable.tape != tape:
                raise TypeError(
                    f"unknown or mistyped variable {name!r} at factor {factor_id}"
                )
            self._neighbours[name].append(factor_id)

tree_marginal

tree_marginal(variable: str, *, max_states: int, max_work: int, max_closure_size: int | None = None) -> TreeStringMarginal

Compile exact factor-to-variable and variable-to-factor messages.

Each edge of each component is used once toward its chosen root. The state and work limits apply separately to the sparse products and marginal path plans. A productive cycle within a relation still requires star and a local closure size limit.

Source code in src/quivers/core/relations/graph.py
def tree_marginal(
    self,
    variable: str,
    *,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
) -> TreeStringMarginal:
    """Compile exact factor-to-variable and variable-to-factor messages.

    Each edge of each component is used once toward its chosen
    root. The state and work limits apply separately to the sparse
    products and marginal path plans. A productive cycle within a
    relation still requires star and a local closure size limit.
    """
    if variable not in self._variables:
        raise ValueError(f"unknown string variable {variable!r}")
    bounds = _TreeBounds(max_states, max_work, max_closure_size)
    visited: set[_Vertex] = set()
    orders = [self._tree_order(variable, visited)]
    orders.extend(
        self._tree_order(name, visited)
        for name in self._variables
        if name not in visited
    )
    marginal, *others = (self._eliminate(order, bounds) for order in orders)
    return TreeStringMarginal(
        marginal,
        tuple(others),
        max_states=max_states,
        max_work=max_work,
        max_closure_size=max_closure_size,
    )

StringMapCertificate dataclass

StringMapCertificate(local_words: tuple[Words, ...], adjusted_scores: tuple[Fraction, ...], potentials: tuple[tuple[tuple[tuple[_Word, Fraction], ...], ...], ...])

Local optima and potentials at an agreeing set of maximizers.

Entries of local_words, adjusted_scores and potentials follow factor order, with words and potentials in each factor's variable order. Unlisted word potentials are zero.

StringMapResult dataclass

StringMapResult(status: Literal['optimal', 'infeasible', 'limit'], iterations: int, assignment: _Global | None, score: Fraction | None, upper_bound: Fraction | None, certificate: StringMapCertificate | None = None)

A certified optimum, infeasibility, or a bounded unsuccessful search.

StringCandidateMessage dataclass

StringCandidateMessage(tape: StringSet, words: tuple[_Word, ...], log_weights: Tensor, log_total_mass: Tensor, log_omitted_mass: Tensor, status: Literal['exact', 'truncated'], boundary_tie: bool)

A restricted weighted message and its exact full-language scale.

The selected words and log weights use the order of the supplied candidates. The omitted mass includes every other word. Status records whether that omitted mass is zero. A positive-weight tie across the selection boundary is reported separately.

normalized_log_weights

normalized_log_weights() -> Tensor

Normalize the retained candidates in their centered log gauge.

A zero candidate stays at log zero. A finite candidate whose normalized log weight overflows raises OverflowError.

Source code in src/quivers/core/relations/messages.py
def normalized_log_weights(self) -> torch.Tensor:
    """Normalize the retained candidates in their centered log gauge.

    A zero candidate stays at log zero. A finite candidate whose
    normalized log weight overflows raises `OverflowError`.
    """
    weights = self.log_weights
    maximum = (
        weights.amax(dim=0) if weights.numel() else weights.new_full((), -torch.inf)
    )
    _require_normalizer(maximum, LOG_PROB)
    normalized = torch.log_softmax(weights, dim=0)
    if bool((torch.isfinite(weights) & ~torch.isfinite(normalized)).any()):
        raise OverflowError(
            "a centered string candidate log weight is outside the evaluation precision"
        )
    return normalized

StringCandidatePlan

StringCandidatePlan(relation: RationalRelation, words: tuple[_Word, ...], *, max_states: int, max_work: int, max_closure_size: int | None = None)

Compile a finite candidate view of a unary LogProb relation.

A deterministic complement of the candidate language sums the mass of all other words. An optional beam ranks the supplied candidates by their marginal word weights, with lexicographic ties. The beam selection is discrete. Differentiation follows the scores and the full and omitted masses for the selected support.

PARAMETER DESCRIPTION
relation

A unary weighted relation supplying the original message.

TYPE: RationalRelation

words

Distinct candidate words on that relation's tape.

TYPE: tuple of words

max_states

State limit for each construction and query.

TYPE: int

max_work

Work limit for each construction and query.

TYPE: int

max_closure_size

Maximum productive local closure size, if admitted.

TYPE: int or None DEFAULT: None

Source code in src/quivers/core/relations/messages.py
def __init__(
    self,
    relation: RationalRelation,
    words: tuple[_Word, ...],
    *,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
) -> None:
    if relation.algebra is not LOG_PROB or len(relation.topology.tapes) != 1:
        raise TypeError("a string candidate plan requires one LogProb tape")
    if max_states is None or max_work is None:
        raise ValueError("string candidates require explicit state and work limits")
    _validate_limits(max_states, max_work, max_closure_size)
    if len(set(words)) != len(words):
        raise ValueError("string message candidates must be distinct")
    self._words = tuple(words)
    self._tape = relation.topology.tapes[0]
    complementary = intersect(
        relation,
        _complement(relation, self._words, max_states, max_work),
        max_states=max_states,
        max_work=max_work,
    )
    self._complement = complementary._total_query(
        max_states, max_work, max_closure_size
    )
    self._scores = tuple(
        relation.query(
            (word,),
            max_states=max_states,
            max_work=max_work,
            max_closure_size=max_closure_size,
        )
        for word in self._words
    )

evaluate

evaluate(*, beam: int | None = None) -> StringCandidateMessage

Return a typed candidate message, including the full and omitted masses.

PARAMETER DESCRIPTION
beam

The number of highest-weight words to retain from the supplied list. None retains the complete list.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
StringCandidateMessage

The scores, scale, and truncation diagnostics for live weights.

RAISES DESCRIPTION
ValueError

If the beam is invalid or the full message has no finite positive normalizer.

Source code in src/quivers/core/relations/messages.py
def evaluate(self, *, beam: int | None = None) -> StringCandidateMessage:
    """Return a typed candidate message, including the full and omitted masses.

    Parameters
    ----------
    beam : int or None
        The number of highest-weight words to retain from the
        supplied list. None retains the complete list.

    Returns
    -------
    StringCandidateMessage
        The scores, scale, and truncation diagnostics for live weights.

    Raises
    ------
    ValueError
        If the beam is invalid or the full message has no finite
        positive normalizer.
    """
    if beam is not None and (type(beam) is not int or beam < 0):
        raise ValueError("the string message beam must be a nonnegative integer")
    with _weight_snapshot():
        outside = self._complement.weight()
        scores = (
            torch.stack([query.weight() for query in self._scores])
            if self._scores
            else outside.new_empty((0,))
        )
    return _restrict_candidates(self._tape, self._words, scores, outside, beam)[1]

StringVariable dataclass

StringVariable(name: str, tape: StringSet, observed: tuple[int, ...] | None = None)

A typed string variable, optionally observed as one word.

TreeStringMarginal

TreeStringMarginal(relation: RationalRelation, other_components: tuple[RationalRelation, ...] = (), *, max_states: int, max_work: int, max_closure_size: int | None = None)

An exact marginal compiled by eliminating the other string variables.

The unary relation represents the unnormalized mass in the queried variable's own connected component. The partition includes every component. Each evaluation reads the original weight sources afresh.

Source code in src/quivers/core/relations/graph.py
def __init__(
    self,
    relation: RationalRelation,
    other_components: tuple[RationalRelation, ...] = (),
    *,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
) -> None:
    if relation.algebra is not MARKOV and relation.algebra is not LOG_PROB:
        raise TypeError("exact tree marginals require Markov or LogProb algebra")
    components = (relation, *other_components)
    if any(
        len(component.topology.tapes) != 1
        or component.algebra is not relation.algebra
        for component in components
    ):
        raise TypeError(
            "tree marginals require unary relations with one shared algebra"
        )
    self._relation = relation
    self._bounds = _TreeBounds(max_states, max_work, max_closure_size)
    self._normalizers = tuple(
        component._total_query(max_states, max_work, max_closure_size)
        for component in components
    )

relation property

relation: RationalRelation

The unnormalized unary relation for the queried component.

partition

partition() -> Tensor

Return total mass in the factor algebra, with its scale.

Source code in src/quivers/core/relations/graph.py
def partition(self) -> torch.Tensor:
    """Return total mass in the factor algebra, with its scale."""
    algebra = self.relation.algebra
    with _weight_snapshot():
        masses = [query.weight() for query in self._normalizers]
    total = masses[0]
    for mass in masses[1:]:
        if total.dtype != mass.dtype or total.device != mass.device:
            raise ValueError(
                "string factors require a common weight dtype and device"
            )
        total = algebra.tensor_op(total, mass)
    if not algebra.contains(total).item():
        raise OverflowError("string partition is outside the evaluation precision")
    return total

log_prob

log_prob(word: tuple[int, ...]) -> Tensor

Return the log probability of one word under the full graph.

Source code in src/quivers/core/relations/graph.py
def log_prob(self, word: tuple[int, ...]) -> torch.Tensor:
    """Return the log probability of one word under the full graph."""
    return self.query(word)()

query

query(word: tuple[int, ...]) -> Callable[[], Tensor]

Compile a reusable normalized score for one word.

The query retains the word's sparse plan and the component normalizers. Each evaluation reads the current weight sources.

PARAMETER DESCRIPTION
word

The fixed word on this marginal's tape.

TYPE: tuple of int

RETURNS DESCRIPTION
Callable

A callable returning the word's normalized log probability.

Source code in src/quivers/core/relations/graph.py
def query(self, word: tuple[int, ...]) -> Callable[[], torch.Tensor]:
    """Compile a reusable normalized score for one word.

    The query retains the word's sparse plan and the component
    normalizers. Each evaluation reads the current weight sources.

    Parameters
    ----------
    word : tuple of int
        The fixed word on this marginal's tape.

    Returns
    -------
    Callable
        A callable returning the word's normalized log probability.
    """
    bounds = self._bounds
    plan = self.relation.query(
        (word,),
        max_states=bounds.max_states,
        max_work=bounds.max_work,
        max_closure_size=bounds.max_closure_size,
    )

    def evaluate() -> torch.Tensor:
        algebra = self.relation.algebra
        with _weight_snapshot():
            masses = [query.weight() for query in self._normalizers]
            for mass in masses[1:]:
                _require_normalizer(mass, algebra)
            score = plan.weight()
        return _conditional_log_ratio(score, masses[0], algebra)

    return evaluate

centered_query

centered_query(word: tuple[int, ...], *, max_center_occurrences: int, max_dyadic_work: int) -> Callable[[], CenteredStringLogScore]

Compile a centered binary64 LogProb query in the root component.

The queried component's productive observations must be acyclic. Disconnected components still require a positive normalizer under their existing closure and precision contract. Work in the returned report concerns the centered component.

Source code in src/quivers/core/relations/graph.py
def centered_query(
    self,
    word: tuple[int, ...],
    *,
    max_center_occurrences: int,
    max_dyadic_work: int,
) -> Callable[[], CenteredStringLogScore]:
    """Compile a centered binary64 LogProb query in the root component.

    The queried component's productive observations must be
    acyclic. Disconnected components still require a positive
    normalizer under their existing closure and precision contract.
    Work in the returned report concerns the centered component.
    """
    plan, weights = self._centered_binding(
        word,
        max_center_occurrences=max_center_occurrences,
        max_dyadic_work=max_dyadic_work,
    )

    def evaluate() -> CenteredStringLogScore:
        return plan.evaluate(weights())

    return evaluate

StaticMinimizationWork dataclass

StaticMinimizationWork(input_records: int, active_states: int, active_arcs: int, splitter_states: int, predecessor_examinations: int)

Input, positive-support, and refinement counts for static minimization.

input_records counts original arc, boundary and weight-slot entries. active_states and active_arcs count the trimmed positive support. splitter_states and predecessor_examinations count state visits and incoming arc visits during refinement, including revisits. Their sum with input_records is the work charge.

auto_intersect

auto_intersect(relation: RationalRelation, first: int, second: int, *, max_states: int, max_work: int) -> RationalRelation

Keep only paths realizing the same word on two same-type tapes.

The tapes and primitive weight sources stay in place. Productive paths may pass through cycles with nonzero signed length difference of a common sign. Opposite signs on the same path are refused. The resulting finite graph tracks the suffix of whichever tape is ahead. Every created arc consumes exactly one original occurrence.

After structural trimming, the limits bound the reached residual configurations, signed relaxations, and examined arc occurrences.

Source code in src/quivers/core/relations/equality.py
def auto_intersect(
    relation: RationalRelation,
    first: int,
    second: int,
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Keep only paths realizing the same word on two same-type tapes.

    The tapes and primitive weight sources stay in place. Productive
    paths may pass through cycles with nonzero signed length difference
    of a common sign. Opposite signs on the same path are refused.
    The resulting finite graph tracks the suffix of whichever tape is
    ahead. Every created arc consumes exactly one original occurrence.

    After structural trimming, the limits bound the reached residual
    configurations, signed relaxations, and examined arc occurrences.
    """
    topology = relation.topology
    if (
        type(first) is not int
        or type(second) is not int
        or not 0 <= first < len(topology.tapes)
        or not 0 <= second < len(topology.tapes)
        or first == second
    ):
        raise ValueError("auto-intersection requires two distinct valid tape positions")
    if topology.tapes[first] != topology.tapes[second]:
        raise TypeError("auto-intersection requires the same type on both tapes")
    if max_states is None or max_work is None:
        raise ValueError("auto-intersection requires explicit state and work limits")
    _validate_limits(max_states, max_work)
    topology = trim(relation).topology
    if len(topology.initial) > max_states:
        raise RelationLimitError("auto-intersection exceeds max_states")
    delay, remaining = _certify_delay(topology, first, second, max_work)
    native: dict[int, list[Arc]] = defaultdict(list)
    for arc in topology.arcs:
        native[arc.source].append(arc)

    states: list[_State] = [(mark.state, (), ()) for mark in topology.initial]
    indexes = {state: i for i, state in enumerate(states)}
    initial = tuple(Boundary(i, mark.weight) for i, mark in enumerate(topology.initial))
    final: list[Boundary] = []
    arcs: list[Arc] = []
    for source, (state, a, b) in enumerate(states):
        if not a and not b and (slot := topology._final_slots.get(state)) is not None:
            final.append(Boundary(source, slot))
        for arc in native.get(state, ()):
            if remaining == 0:
                raise RelationLimitError("auto-intersection exceeds max_work")
            remaining -= 1
            left, right = arc.labels[first], arc.labels[second]
            a_suffix = a if left is None else (*a, left)
            b_suffix = b if right is None else (*b, right)
            if abs(len(a_suffix) - len(b_suffix)) > delay:
                continue
            common = min(len(a_suffix), len(b_suffix))
            if a_suffix[:common] != b_suffix[:common]:
                continue
            config = arc.target, a_suffix[common:], b_suffix[common:]
            target = indexes.get(config)
            if target is None:
                target = len(states)
                if target == max_states:
                    raise RelationLimitError("auto-intersection exceeds max_states")
                indexes[config] = target
                states.append(config)
            arcs.append(Arc(source, target, arc.labels, arc.weight))
    checked = RelationTopology(
        topology.tapes,
        topology.input_tapes,
        len(states),
        tuple(arcs),
        initial,
        tuple(final),
        topology.weight_names,
    )
    return RationalRelation(checked, relation.module(), algebra=relation.algebra)

backoff_query

backoff_query(relation: RationalRelation, failures: tuple[FailureArc, ...], word: tuple[int, ...], *, max_states: int, max_work: int) -> FixedStringQuery

Compile one word against an epsilon-free deterministic acceptor.

An explicit transition takes precedence even if its current weight is zero. For a missing symbol, the query multiplies the weights of successive failure arcs and then the explicit matching weight, in that order. A failure arc never consumes a symbol or acts as a final transition.

The source stays live. Only the selected path is built. Once the deterministic topology and acyclic failure links are checked, the work limit counts symbol probes and the state limit counts visited path configurations.

Source code in src/quivers/core/relations/backoff.py
def backoff_query(
    relation: RationalRelation,
    failures: tuple[FailureArc, ...],
    word: tuple[int, ...],
    *,
    max_states: int,
    max_work: int,
) -> FixedStringQuery:
    """Compile one word against an epsilon-free deterministic acceptor.

    An explicit transition takes precedence even if its current weight
    is zero. For a missing symbol, the query multiplies the weights of
    successive failure arcs and then the explicit matching weight, in
    that order. A failure arc never consumes a symbol or acts as a
    final transition.

    The source stays live. Only the selected path is built. Once the
    deterministic topology and acyclic failure links are checked, the
    work limit counts symbol probes and the state limit counts visited
    path configurations.
    """
    topology = relation.topology
    if len(topology.tapes) != 1 or len(topology.initial) > 1:
        raise TypeError(
            "backoff requires a one-tape acceptor with at most one initial state"
        )
    topology._validate_words((word,))
    if max_states is None or max_work is None:
        raise ValueError("backoff requires explicit state and work limits")
    _validate_limits(max_states, max_work)
    by_symbol = _ordinary_index(topology)
    failure_index = _failure_index(topology, failures)

    n_states = 0
    marks: tuple[Boundary, ...] = ()
    finals: tuple[Boundary, ...] = ()
    arcs: list[Arc] = []
    if topology.initial:
        initial = topology.initial[0]
        state = initial.state
        marks = (Boundary(0, initial.weight),)
        n_states = 1
        if max_states == 0:
            raise RelationLimitError("backoff exceeds max_states")
        offset = 0
        work = 0
        while offset < len(word):
            if work == max_work:
                raise RelationLimitError("backoff exceeds max_work")
            work += 1
            label: Label
            move: Arc | FailureArc | None = by_symbol.get((state, word[offset]))
            if move is not None:
                label = word[offset]
                offset += 1
            else:
                move = failure_index.get(state)
                label = EPSILON
            if move is None:
                break
            if n_states == max_states:
                raise RelationLimitError("backoff exceeds max_states")
            arcs.append(Arc(n_states - 1, n_states, (label,), move.weight))
            n_states += 1
            state = move.target
        if (
            offset == len(word)
            and (weight := topology._final_slots.get(state)) is not None
        ):
            finals = (Boundary(n_states - 1, weight),)

    observed = RelationTopology(
        topology.tapes,
        topology.input_tapes,
        n_states,
        tuple(arcs),
        marks,
        finals,
        topology.weight_names,
    )
    return RationalRelation(
        observed, relation.module(), algebra=relation.algebra
    ).query((word,))

backoff_total_weight

backoff_total_weight(relation: RationalRelation, failures: tuple[FailureArc, ...], *, max_states: int, max_work: int) -> Tensor

Sum all accepted word weights of an acyclic deterministic backoff acceptor.

An explicit symbol transition takes precedence over the fallback, including at zero weight. A state can finish only by its own final mark. The union of reachable ordinary and failure edges must be acyclic. The transition and boundary values come from the original weight source.

PARAMETER DESCRIPTION
relation

An epsilon-free deterministic acceptor with at most one initial state and an established scalar semiring.

TYPE: RationalRelation

failures

The weighted fallback at each state, with at most one per state.

TYPE: tuple[FailureArc, ...]

max_states

Maximum states reached in the combined transition graph.

TYPE: int

max_work

Maximum examined reachable base edges and persistent sum-tree node updates.

TYPE: int

RETURNS DESCRIPTION
Tensor

The total weight in the original semiring, with live derivatives where the algebra supports autograd.

RAISES DESCRIPTION
TypeError

If the tapes, starting boundary, or scalar algebra are unsupported.

ValueError

If the graph is cyclic or its transition records are invalid.

RelationLimitError

If an explicit construction limit is exceeded.

Source code in src/quivers/core/relations/backoff.py
def backoff_total_weight(
    relation: RationalRelation,
    failures: tuple[FailureArc, ...],
    *,
    max_states: int,
    max_work: int,
) -> torch.Tensor:
    """Sum all accepted word weights of an acyclic deterministic backoff acceptor.

    An explicit symbol transition takes precedence over the fallback,
    including at zero weight. A state can finish only by its own final
    mark. The union of reachable ordinary and failure edges must be
    acyclic. The transition and boundary values come from the original
    weight source.

    Parameters
    ----------
    relation : RationalRelation
        An epsilon-free deterministic acceptor with at most one
        initial state and an established scalar semiring.
    failures : tuple[FailureArc, ...]
        The weighted fallback at each state, with at most one per state.
    max_states : int
        Maximum states reached in the combined transition graph.
    max_work : int
        Maximum examined reachable base edges and persistent sum-tree
        node updates.

    Returns
    -------
    torch.Tensor
        The total weight in the original semiring, with live derivatives
        where the algebra supports autograd.

    Raises
    ------
    TypeError
        If the tapes, starting boundary, or scalar algebra are unsupported.
    ValueError
        If the graph is cyclic or its transition records are invalid.
    RelationLimitError
        If an explicit construction limit is exceeded.
    """
    topology = relation.topology
    algebra = relation.algebra
    if len(topology.tapes) != 1 or len(topology.initial) > 1:
        raise TypeError(
            "backoff requires a one-tape acceptor with at most one initial state"
        )
    if not algebra.establishes(*SEMIRING_LAWS):
        raise TypeError("backoff total weight requires an established scalar semiring")
    if max_states is None or max_work is None:
        raise ValueError("backoff requires explicit state and work limits")
    _validate_limits(max_states, max_work)
    ordinary = _ordinary_index(topology)
    fallback = _failure_index(topology, failures)
    outgoing: dict[int, list[tuple[int, Arc]]] = defaultdict(list)
    for (state, symbol), arc in ordinary.items():
        outgoing[state].append((symbol, arc))
    weights = relation._weights()
    zero = algebra.zero_like((), weights)
    if not topology.initial:
        return zero

    initial = topology.initial[0]
    remaining = max_work

    def charge(work: int) -> None:
        nonlocal remaining
        remaining -= work
        if remaining < 0:
            raise RelationLimitError("backoff total weight exceeds max_work")

    states = [initial.state]
    reached = set(states)
    dependencies: dict[int, list[int]] = {}
    if max_states == 0:
        raise RelationLimitError("backoff total weight exceeds max_states")
    for state in states:
        children = [arc.target for _, arc in outgoing[state]]
        if (failure := fallback.get(state)) is not None:
            children.append(failure.target)
        charge(len(children))
        dependencies[state] = children
        for target in children:
            if target not in reached:
                if len(states) == max_states:
                    raise RelationLimitError("backoff total weight exceeds max_states")
                reached.add(target)
                states.append(target)
    try:
        order = tuple(TopologicalSorter(dependencies).static_order())
    except CycleError as error:
        raise ValueError(
            "backoff total weight requires acyclic ordinary and failure edges"
        ) from error

    positions = dict.fromkeys(symbol for q in states for symbol, _ in outgoing[q])
    symbol_indices = {symbol: index for index, symbol in enumerate(positions)}
    tree = _SymbolTree(algebra, charge)
    roots: dict[int, _SymbolSums | None] = {}
    totals: dict[int, torch.Tensor] = {}
    for state in order:
        failure = fallback.get(state)
        root = (
            None
            if failure is None
            else tree.scale(weights[failure.weight], roots[failure.target])
        )
        for symbol, arc in outgoing[state]:
            weight = algebra.tensor_op(weights[arc.weight], totals[arc.target])
            root = tree.override(
                root, symbol_indices[symbol], weight, 0, len(symbol_indices)
            )
        roots[state] = root
        slot = topology._final_slots.get(state)
        total = tree.add(
            None if root is None else root.total,
            None if slot is None else weights[slot],
        )
        totals[state] = zero if total is None else total
    return algebra.tensor_op(weights[initial.weight], totals[initial.state])

best_marginal_output

best_marginal_output(relation: RationalRelation, inputs: Words, candidates: tuple[Words, ...], *, max_states: int, max_work: int) -> MarginalOutputChoice | None

Maximize the total alignment weight over explicit output candidates.

With inputs held fixed, maximizing pair weight is equivalent to maximizing conditional probability whenever its normalizer exists and is positive. This operation returns an unnormalized pair score.

PARAMETER DESCRIPTION
relation

A Markov relation with at least one input and one output tape.

TYPE: RationalRelation

inputs

One fixed word per input tape in tape order.

TYPE: Words

candidates

Word tuples for the output tapes. The first maximum wins ties.

TYPE: tuple[Words, ...]

max_states

Total reached configurations across the candidate queries.

TYPE: int

max_work

Total examined transitions across the candidate queries.

TYPE: int

RETURNS DESCRIPTION
MarginalOutputChoice or None

The candidate with greatest positive alignment sum, or None if all candidates have zero mass. Exact rational comparison uses the original binary coefficients. The selected pair's log sum uses a packed log-space evaluation with live gradients.

RAISES DESCRIPTION
TypeError

If the relation is outside the supported algebra, tape, or weight domains.

ValueError

If the words or limits are invalid.

RelationLimitError

If cumulative candidate observation exceeds a construction limit.

ProductiveEpsilonCycleError

If a candidate has a productive cyclic observation graph.

Source code in src/quivers/core/relations/marginal_map.py
def best_marginal_output(
    relation: RationalRelation,
    inputs: Words,
    candidates: tuple[Words, ...],
    *,
    max_states: int,
    max_work: int,
) -> MarginalOutputChoice | None:
    """Maximize the total alignment weight over explicit output candidates.

    With inputs held fixed, maximizing pair weight is equivalent to
    maximizing conditional probability whenever its normalizer exists
    and is positive. This operation returns an unnormalized pair score.

    Parameters
    ----------
    relation : RationalRelation
        A Markov relation with at least one input and one output tape.
    inputs : Words
        One fixed word per input tape in tape order.
    candidates : tuple[Words, ...]
        Word tuples for the output tapes. The first maximum wins ties.
    max_states : int
        Total reached configurations across the candidate queries.
    max_work : int
        Total examined transitions across the candidate queries.

    Returns
    -------
    MarginalOutputChoice or None
        The candidate with greatest positive alignment sum, or None if
        all candidates have zero mass. Exact rational comparison uses
        the original binary coefficients. The selected pair's log sum
        uses a packed log-space evaluation with live gradients.

    Raises
    ------
    TypeError
        If the relation is outside the supported algebra, tape, or
        weight domains.
    ValueError
        If the words or limits are invalid.
    RelationLimitError
        If cumulative candidate observation exceeds a construction
        limit.
    ProductiveEpsilonCycleError
        If a candidate has a productive cyclic observation graph.
    """
    topology = relation.topology
    if relation.algebra is not MARKOV:
        raise TypeError("exact marginal output ranking requires Markov weights")
    if not 0 < topology.input_tapes < len(topology.tapes):
        raise TypeError("marginal output ranking requires input and output tapes")
    if max_states is None or max_work is None:
        raise ValueError(
            "marginal output ranking requires explicit state and work limits"
        )
    _validate_limits(max_states, max_work)
    if len(inputs) != topology.input_tapes:
        raise ValueError("marginal output ranking requires one word per input tape")
    topology._validate_words((*inputs, *((),) * (len(topology.tapes) - len(inputs))))
    if not candidates:
        return None

    weights = relation._weights()
    if not weights.is_floating_point():
        raise TypeError("marginal output ranking requires floating-point weights")
    values = tuple(map(Fraction, weights.detach().tolist()))
    best: tuple[Words, _Observation, _ProductiveGraph] | None = None
    best_weight = Fraction(0)
    for output in candidates:
        words = (*inputs, *output)
        topology._validate_words(words)
        observation = _observe(
            topology,
            words,
            max_states=max_states,
            max_work=max_work,
        )
        max_states -= len(observation.states)
        max_work -= observation.examined
        graph = _productive_graph(
            observation.arcs, observation.initial, observation.final
        )
        if len(graph.order) != len(graph.states):
            raise ProductiveEpsilonCycleError(
                "exact marginal output ranking requires acyclic productive observations"
            )
        total = _weight(graph, observation.final, values)
        if total > best_weight:
            best = tuple(map(tuple, output)), observation, graph
            best_weight = total
    if best is None:
        return None

    output, observation, graph = best
    plan = _pack_paths(graph.order, graph.arcs, graph.initial, observation.final)
    log_score = plan.evaluate(_markov_log_weights(weights), LOG_PROB)
    if not bool(torch.isfinite(log_score)):
        raise OverflowError(
            "selected log pair weight is outside the evaluation precision"
        )
    return MarginalOutputChoice(output, best_weight, log_score)

certify_markov_path_weight

certify_markov_path_weight(relation: RationalRelation, words: Words, *, max_states: int, max_work: int, max_exact_bits: int, max_exact_work: int, max_closure_cells: int, max_closure_size: int | None = None, absolute_tolerance: Fraction | int | None = None, relative_tolerance: Fraction | int | None = None) -> PathWeightCertificate

Certify an absolute or relative error bound for a Markov pair weight.

The certificate describes the exact path sum at the evaluated binary64 weight vector. It uses exact sparse reverse recurrences on acyclic states. Cyclic components reuse the packed evaluator's local star matrices as proposals and check their error against original sparse rows in rational arithmetic.

PARAMETER DESCRIPTION
relation

A Markov relation with binary64 scalar weights.

TYPE: RationalRelation

words

One observed word per original tape.

TYPE: Words

max_states

Fixed-word observation state and arc budgets.

TYPE: int

max_work

Fixed-word observation state and arc budgets.

TYPE: int

max_exact_bits

Maximum conservative integer bit bound per exact operation and number of conversions, arithmetic operations, or comparisons.

TYPE: int

max_exact_work

Maximum conservative integer bit bound per exact operation and number of conversions, arithmetic operations, or comparisons.

TYPE: int

max_closure_cells

Aggregate cell bound before constructing closure expansion or matrices.

TYPE: int

max_closure_size

Maximum local star order. None requires an acyclic observation.

TYPE: int or None DEFAULT: None

absolute_tolerance

Requested error bounds, each required if supplied. Relative error needs a positive lower bound or certified exact zero.

TYPE: Fraction or int or None DEFAULT: None

relative_tolerance

Requested error bounds, each required if supplied. Relative error needs a positive lower bound or certified exact zero.

TYPE: Fraction or int or None DEFAULT: None

RETURNS DESCRIPTION
PathWeightCertificate

The usual packed weight and exact bounds at the evaluated input.

RAISES DESCRIPTION
TypeError

The algebra or scalar dtype has no supported accuracy contract.

ValueError

A limit, observation, or tolerance is invalid.

RelationAccuracyError

A finite witness or requested forward-error bound was not established.

RelationLimitError

A resource bound is exceeded.

Source code in src/quivers/core/relations/accuracy.py
def certify_markov_path_weight(
    relation: RationalRelation,
    words: Words,
    *,
    max_states: int,
    max_work: int,
    max_exact_bits: int,
    max_exact_work: int,
    max_closure_cells: int,
    max_closure_size: int | None = None,
    absolute_tolerance: Fraction | int | None = None,
    relative_tolerance: Fraction | int | None = None,
) -> PathWeightCertificate:
    """Certify an absolute or relative error bound for a Markov pair weight.

    The certificate describes the exact path sum at the evaluated
    binary64 weight vector. It uses exact sparse reverse recurrences
    on acyclic states. Cyclic components reuse the packed evaluator's
    local star matrices as proposals and check their error against
    original sparse rows in rational arithmetic.

    Parameters
    ----------
    relation : RationalRelation
        A Markov relation with binary64 scalar weights.
    words : Words
        One observed word per original tape.
    max_states, max_work : int
        Fixed-word observation state and arc budgets.
    max_exact_bits, max_exact_work : int
        Maximum conservative integer bit bound per exact operation and
        number of conversions, arithmetic operations, or comparisons.
    max_closure_cells : int
        Aggregate cell bound before constructing closure expansion or matrices.
    max_closure_size : int or None
        Maximum local star order. None requires an acyclic observation.
    absolute_tolerance, relative_tolerance : Fraction or int or None
        Requested error bounds, each required if supplied. Relative
        error needs a positive lower bound or certified exact zero.

    Returns
    -------
    PathWeightCertificate
        The usual packed weight and exact bounds at the evaluated input.

    Raises
    ------
    TypeError
        The algebra or scalar dtype has no supported accuracy contract.
    ValueError
        A limit, observation, or tolerance is invalid.
    RelationAccuracyError
        A finite witness or requested forward-error bound was not established.
    RelationLimitError
        A resource bound is exceeded.
    """
    evaluate = _markov_accuracy_plan(
        relation,
        words,
        max_states=max_states,
        max_work=max_work,
        max_exact_bits=max_exact_bits,
        max_exact_work=max_exact_work,
        max_closure_cells=max_closure_cells,
        max_closure_size=max_closure_size,
        absolute_tolerance=absolute_tolerance,
        relative_tolerance=relative_tolerance,
    )
    return evaluate()

certify_pruned_string_beliefs

certify_pruned_string_beliefs(plan: FiniteStringBeliefPlan, *, beam: int, max_sweeps: int, max_conditional_cells: int, max_exact_work: int, max_exact_bits: int, decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, tolerance: float | None = 1e-09, damping: float = 0.0) -> PrunedStringBeliefCertificate

Certify the actual finite pruned scores against true marginals.

Uses exact path sums of one live binary64 Markov snapshot on acyclic observed-word queries. All factor entries must be positive. Each site uses its untruncated effective blanket and the exact worst change of its conditional for one changed neighbor. A maximum row sum strictly below one admits Gibbs comparison.

PARAMETER DESCRIPTION
plan

The original finite graph, observations, and ordered word axes.

TYPE: FiniteStringBeliefPlan

beam

The existing pruned schedule and its own convergence settings.

TYPE: int

max_sweeps

The existing pruned schedule and its own convergence settings.

TYPE: int

tolerance

The existing pruned schedule and its own convergence settings.

TYPE: int

damping

The existing pruned schedule and its own convergence settings.

TYPE: int

max_conditional_cells

Cumulative bound on local conditional entries.

TYPE: int

max_exact_work

Bound exact arithmetic operations and unreduced intermediate bits.

TYPE: int

max_exact_bits

Bound exact arithmetic operations and unreduced intermediate bits.

TYPE: int

decimal_precision

Bounds for directed exponentiation of the actual emitted log scores.

TYPE: int

max_decimal_exponent

Bounds for directed exponentiation of the actual emitted log scores.

TYPE: int

max_decimal_work

Bounds for directed exponentiation of the actual emitted log scores.

TYPE: int

RETURNS DESCRIPTION
PrunedStringBeliefCertificate

The approximate run and exact rational total variation bounds. The certificate concerns values. Scores retain the derivative of the executed pruned schedule.

RAISES DESCRIPTION
TypeError

A factor uses a different algebra or evaluation precision.

ProductiveEpsilonCycleError

A factor-table query contains a productive cycle.

RelationLimitError

A declared resource limit is insufficient.

RelationAccuracyError

Full positive model support, the contraction condition, or the returned belief cannot be verified.

Source code in src/quivers/core/relations/belief_accuracy.py
def certify_pruned_string_beliefs(
    plan: FiniteStringBeliefPlan,
    *,
    beam: int,
    max_sweeps: int,
    max_conditional_cells: int,
    max_exact_work: int,
    max_exact_bits: int,
    decimal_precision: int,
    max_decimal_exponent: int,
    max_decimal_work: int,
    tolerance: float | None = 1e-9,
    damping: float = 0.0,
) -> PrunedStringBeliefCertificate:
    """Certify the actual finite pruned scores against true marginals.

    Uses exact path sums of one live binary64 Markov snapshot on
    acyclic observed-word queries. All factor entries must be positive.
    Each site uses its untruncated effective blanket and the exact
    worst change of its conditional for one changed neighbor. A
    maximum row sum strictly below one admits Gibbs comparison.

    Parameters
    ----------
    plan : FiniteStringBeliefPlan
        The original finite graph, observations, and ordered word axes.
    beam, max_sweeps, tolerance, damping
        The existing pruned schedule and its own convergence settings.
    max_conditional_cells : int
        Cumulative bound on local conditional entries.
    max_exact_work, max_exact_bits : int
        Bound exact arithmetic operations and unreduced intermediate bits.
    decimal_precision, max_decimal_exponent, max_decimal_work : int
        Bounds for directed exponentiation of the actual emitted log scores.

    Returns
    -------
    PrunedStringBeliefCertificate
        The approximate run and exact rational total variation bounds.
        The certificate concerns values. Scores retain the derivative of
        the executed pruned schedule.

    Raises
    ------
    TypeError
        A factor uses a different algebra or evaluation precision.
    ProductiveEpsilonCycleError
        A factor-table query contains a productive cycle.
    RelationLimitError
        A declared resource limit is insufficient.
    RelationAccuracyError
        Full positive model support, the contraction condition, or
        the returned belief cannot be verified.
    """
    _validate_pruned_settings(beam, max_sweeps, tolerance, damping)
    _validate_decimal_settings(decimal_precision, max_decimal_exponent)
    for name, limit in (
        ("max_conditional_cells", max_conditional_cells),
        ("max_exact_work", max_exact_work),
        ("max_exact_bits", max_exact_bits),
        ("max_decimal_work", max_decimal_work),
    ):
        if type(limit) is not int or limit < 0:
            raise ValueError(f"{name} must be a nonnegative integer")
    if decimal_precision > max_exact_bits:
        raise RelationLimitError("belief Decimal precision exceeds max_exact_bits")
    if any(factor.relation.algebra is not MARKOV for factor in plan._tables):
        raise TypeError("finite string belief certification requires Markov factors")
    if any(query._plan.closures for factor in plan._tables for query in factor.queries):
        raise ProductiveEpsilonCycleError(
            "finite string belief certification requires acyclic queries"
        )
    blankets, cells = _blankets(plan, max_conditional_cells)
    slots = sum(len(factor.relation.topology.weight_names) for factor in plan._tables)
    if slots > max_exact_work:
        raise RelationLimitError(
            "finite string beliefs exceed max_exact_work reading weights"
        )

    with _weight_snapshot():
        weights = tuple(factor.relation._weights().clone() for factor in plan._tables)
    if any(values.dtype != torch.float64 for values in weights):
        raise _UnsupportedAccuracyPrecision(
            "finite string belief certification requires float64 weights"
        )
    budget = _RationalBudget(max_exact_bits, max_exact_work)
    decimal = _DirectedDecimal(
        decimal_precision, max_decimal_exponent, max_decimal_work
    )
    tables = tuple(
        (factor.variables, _exact_table(factor, values, budget))
        for factor, values in zip(plan._tables, weights, strict=True)
    )
    result = plan._run_pruned(
        *plan._start(weights),
        beam=beam,
        max_sweeps=max_sweeps,
        tolerance=tolerance,
        damping=damping,
    )
    if result.log_marginals is None:
        raise RelationAccuracyError(
            "finite string beliefs have no returned probability rows"
        )
    references = {}
    conversions = {}
    for name, scores in result.log_marginals.items():
        references[name], conversions[name] = _reference(scores, decimal, budget)

    maximum = defect = _ZERO
    local = {}
    pairs = 0
    for name, neighbors in blankets.items():
        factors = tuple(tables[index] for index, _ in plan._occurrences[name])
        expected, worst, influence, compared = _local_comparison(
            name, neighbors, factors, references, budget
        )
        maximum = budget.maximum(maximum, influence)
        if not budget.less(maximum, _ONE):
            raise RelationAccuracyError(
                "finite string beliefs do not certify Dobrushin contraction"
            )
        defect = budget.maximum(defect, expected)
        local[name] = expected, worst, influence
        pairs += compared
    global_bound = _minimum(
        _ONE, budget.divide(defect, budget.add(_ONE, maximum, subtract=True)), budget
    )
    bounds = {}
    for name, (expected, worst, influence) in local.items():
        mismatch = budget.add(expected, budget.multiply(influence, global_bound))
        tv = budget.add(_minimum(worst, mismatch, budget), conversions[name])
        bounds[name] = _minimum(_ONE, tv, budget)
    return PrunedStringBeliefCertificate(
        result,
        MappingProxyType(bounds),
        maximum,
        cells,
        pairs,
        budget.work,
        budget.bits,
        decimal.work,
    )

certify_cyclic_logprob_path_weight

certify_cyclic_logprob_path_weight(relation: RationalRelation, words: Words, *, absolute_log_tolerance: Fraction | int, max_states: int, max_work: int, max_closure_size: int, max_closure_cells: int, decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int) -> LogPathWeightCertificate

Certify absolute log error with explicitly bounded productive epsilon stars.

Each structurally productive cyclic component must admit a finite upper-enclosure star under exact rational elimination. The resulting enclosure concerns the evaluated binary64 slots. The returned tensor has the ordinary LogProb derivative. The certificate covers its value.

PARAMETER DESCRIPTION
relation

A LogProb relation with float64 weights.

TYPE: RationalRelation

words

One observed word per original tape.

TYPE: Words

absolute_log_tolerance

The required nonnegative absolute error in log units.

TYPE: Fraction or int

max_states

Observation state and candidate arc limits.

TYPE: int

max_work

Observation state and candidate arc limits.

TYPE: int

max_closure_size

Local star order and aggregate cell limits, including auxiliaries.

TYPE: int

max_closure_cells

Local star order and aggregate cell limits, including auxiliaries.

TYPE: int

decimal_precision

Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact input conversions.

TYPE: int

max_decimal_exponent

Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact input conversions.

TYPE: int

max_decimal_work

Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact input conversions.

TYPE: int

max_exact_bits

Bit and operation limits for the exact cyclic solves and error test.

TYPE: int

max_exact_work

Bit and operation limits for the exact cyclic solves and error test.

TYPE: int

RETURNS DESCRIPTION
LogPathWeightCertificate

The usual score and exact log endpoints or verified zero mass.

RAISES DESCRIPTION
TypeError

The algebra or evaluated dtype is outside the supported domain.

ValueError

The words, tolerance, or resource declaration is invalid.

RelationLimitError

A structural, range, work, or exact bit limit is exhausted.

RelationAccuracyError

The directed upper star cannot be proved finite or the score's error cannot be certified at the requested tolerance.

DivergentClosureError

A directed lower endpoint proves a local productive star diverges.

UndecidedClosureError

The ordinary numerical LogProb evaluator cannot establish closure.

Source code in src/quivers/core/relations/log_accuracy.py
def certify_cyclic_logprob_path_weight(
    relation: RationalRelation,
    words: Words,
    *,
    absolute_log_tolerance: Fraction | int,
    max_states: int,
    max_work: int,
    max_closure_size: int,
    max_closure_cells: int,
    decimal_precision: int,
    max_decimal_exponent: int,
    max_decimal_work: int,
    max_exact_bits: int,
    max_exact_work: int,
) -> LogPathWeightCertificate:
    """Certify absolute log error with explicitly bounded productive epsilon stars.

    Each structurally productive cyclic component must admit a finite
    upper-enclosure star under exact rational elimination. The resulting
    enclosure concerns the evaluated binary64 slots. The returned tensor
    has the ordinary LogProb derivative. The certificate covers its value.

    Parameters
    ----------
    relation : RationalRelation
        A LogProb relation with float64 weights.
    words : Words
        One observed word per original tape.
    absolute_log_tolerance : Fraction or int
        The required nonnegative absolute error in log units.
    max_states, max_work : int
        Observation state and candidate arc limits.
    max_closure_size, max_closure_cells : int
        Local star order and aggregate cell limits, including auxiliaries.
    decimal_precision, max_decimal_exponent, max_decimal_work : int
        Decimal significant digits, symmetric adjusted exponent bound,
        and maximum primitive calls and exact input conversions.
    max_exact_bits, max_exact_work : int
        Bit and operation limits for the exact cyclic solves and error test.

    Returns
    -------
    LogPathWeightCertificate
        The usual score and exact log endpoints or verified zero mass.

    Raises
    ------
    TypeError
        The algebra or evaluated dtype is outside the supported domain.
    ValueError
        The words, tolerance, or resource declaration is invalid.
    RelationLimitError
        A structural, range, work, or exact bit limit is exhausted.
    RelationAccuracyError
        The directed upper star cannot be proved finite or the score's
        error cannot be certified at the requested tolerance.
    DivergentClosureError
        A directed lower endpoint proves a local productive star diverges.
    UndecidedClosureError
        The ordinary numerical LogProb evaluator cannot establish closure.
    """
    for name, limit in (
        ("max_closure_size", max_closure_size),
        ("max_closure_cells", max_closure_cells),
    ):
        if type(limit) is not int or limit < 0:
            raise ValueError(f"{name} must be a nonnegative integer")
    return _logprob_accuracy_plan(
        relation,
        words,
        absolute_log_tolerance=absolute_log_tolerance,
        max_states=max_states,
        max_work=max_work,
        decimal_precision=decimal_precision,
        max_decimal_exponent=max_decimal_exponent,
        max_decimal_work=max_decimal_work,
        max_exact_bits=max_exact_bits,
        max_exact_work=max_exact_work,
        max_closure_size=max_closure_size,
        max_closure_cells=max_closure_cells,
    )()

certify_centered_cyclic_log_ratio

certify_centered_cyclic_log_ratio(relation: RationalRelation, input_words: Words, output_words: Words, *, absolute_log_tolerance: Fraction | int, max_states: int, max_work: int, max_center_occurrences: int, max_dyadic_work: int, max_closure_size: int, max_closure_cells: int, decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int) -> LogPathWeightCertificate

Certify a centered fixed-input cyclic LogProb likelihood.

Each productive component keeps its original internal log factors. The value certificate uses finite directed upper stars and compares the delivered score to bounds for the evaluated binary64 model. The returned score retains ordinary autograd through bounded numerical closure. Only the value error is certified.

PARAMETER DESCRIPTION
relation

The typed relation with original live LogProb weights.

TYPE: RationalRelation

input_words

Fixed words in the relation's input and output tape order.

TYPE: Words

output_words

Fixed words in the relation's input and output tape order.

TYPE: Words

absolute_log_tolerance

Nonnegative absolute error target in log units.

TYPE: Fraction or int

max_states

Per-observation state and candidate arc caps.

TYPE: int

max_work

Per-observation state and candidate arc caps.

TYPE: int

max_center_occurrences

Aggregate lifted occurrence and graph visit preflights.

TYPE: int

max_dyadic_work

Aggregate lifted occurrence and graph visit preflights.

TYPE: int

max_closure_size

Local numeric order and combined cell caps, including auxiliaries.

TYPE: int

max_closure_cells

Local numeric order and combined cell caps, including auxiliaries.

TYPE: int

decimal_precision

Directed precision, symmetric exponent bound and shared work cap.

TYPE: int

max_decimal_exponent

Directed precision, symmetric exponent bound and shared work cap.

TYPE: int

max_decimal_work

Directed precision, symmetric exponent bound and shared work cap.

TYPE: int

max_exact_bits

Bit and work limits on the gauges, finite stars and value check.

TYPE: int

max_exact_work

Bit and work limits on the gauges, finite stars and value check.

TYPE: int

RETURNS DESCRIPTION
LogPathWeightCertificate

The live numerical score and exact endpoint error witness.

RAISES DESCRIPTION
RelationLimitError

A graph, cell or arithmetic resource limit is exhausted.

RelationAccuracyError

The upper star or the requested accuracy cannot be established.

DivergentClosureError

A directed lower endpoint proves divergent productive closure.

UndecidedClosureError

The bounded numerical star is unavailable.

OverflowError

A required reduced factor or reported score exceeds binary64 range.

ValueError

The model, bounds or normalization domain is invalid.

TypeError

The evaluated algebra or dtype is outside this certificate's scope.

Source code in src/quivers/core/relations/centered_cyclic.py
def certify_centered_cyclic_log_ratio(
    relation: RationalRelation,
    input_words: Words,
    output_words: Words,
    *,
    absolute_log_tolerance: Fraction | int,
    max_states: int,
    max_work: int,
    max_center_occurrences: int,
    max_dyadic_work: int,
    max_closure_size: int,
    max_closure_cells: int,
    decimal_precision: int,
    max_decimal_exponent: int,
    max_decimal_work: int,
    max_exact_bits: int,
    max_exact_work: int,
) -> LogPathWeightCertificate:
    """Certify a centered fixed-input cyclic LogProb likelihood.

    Each productive component keeps its original internal log factors.
    The value certificate uses finite directed upper stars and compares
    the delivered score to bounds for the evaluated binary64 model.
    The returned score retains ordinary autograd through bounded
    numerical closure. Only the value error is certified.

    Parameters
    ----------
    relation : RationalRelation
        The typed relation with original live LogProb weights.
    input_words, output_words : Words
        Fixed words in the relation's input and output tape order.
    absolute_log_tolerance : Fraction or int
        Nonnegative absolute error target in log units.
    max_states, max_work : int
        Per-observation state and candidate arc caps.
    max_center_occurrences, max_dyadic_work : int
        Aggregate lifted occurrence and graph visit preflights.
    max_closure_size, max_closure_cells : int
        Local numeric order and combined cell caps, including auxiliaries.
    decimal_precision, max_decimal_exponent, max_decimal_work : int
        Directed precision, symmetric exponent bound and shared work cap.
    max_exact_bits, max_exact_work : int
        Bit and work limits on the gauges, finite stars and value check.

    Returns
    -------
    LogPathWeightCertificate
        The live numerical score and exact endpoint error witness.

    Raises
    ------
    RelationLimitError
        A graph, cell or arithmetic resource limit is exhausted.
    RelationAccuracyError
        The upper star or the requested accuracy cannot be established.
    DivergentClosureError
        A directed lower endpoint proves divergent productive closure.
    UndecidedClosureError
        The bounded numerical star is unavailable.
    OverflowError
        A required reduced factor or reported score exceeds binary64 range.
    ValueError
        The model, bounds or normalization domain is invalid.
    TypeError
        The evaluated algebra or dtype is outside this certificate's scope.
    """
    return _centered_cyclic_accuracy_plan(
        relation,
        input_words,
        output_words,
        absolute_log_tolerance=absolute_log_tolerance,
        max_states=max_states,
        max_work=max_work,
        max_center_occurrences=max_center_occurrences,
        max_dyadic_work=max_dyadic_work,
        max_closure_size=max_closure_size,
        max_closure_cells=max_closure_cells,
        decimal_precision=decimal_precision,
        max_decimal_exponent=max_decimal_exponent,
        max_decimal_work=max_decimal_work,
        max_exact_bits=max_exact_bits,
        max_exact_work=max_exact_work,
    )()

certify_logprob_path_weight

certify_logprob_path_weight(relation: RationalRelation, words: Words, *, absolute_log_tolerance: Fraction | int, max_states: int, max_work: int, decimal_precision: int, max_decimal_exponent: int, max_decimal_work: int, max_exact_bits: int, max_exact_work: int) -> LogPathWeightCertificate

Certify absolute log error for a float64 fixed-word LogProb DAG score.

The ordinary packed score and the directed verifier use the same evaluated binary64 slot snapshot. The returned tensor keeps its ordinary derivative. The certificate covers its value.

PARAMETER DESCRIPTION
relation

A LogProb relation with float64 weights.

TYPE: RationalRelation

words

One observed word per original tape.

TYPE: Words

absolute_log_tolerance

The required nonnegative absolute error in log units.

TYPE: Fraction or int

max_states

Observation state and candidate arc budgets.

TYPE: int

max_work

Observation state and candidate arc budgets.

TYPE: int

decimal_precision

Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact binary64 conversions.

TYPE: int

max_decimal_exponent

Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact binary64 conversions.

TYPE: int

max_decimal_work

Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact binary64 conversions.

TYPE: int

max_exact_bits

Bit and operation bounds for the final rational error test.

TYPE: int

max_exact_work

Bit and operation bounds for the final rational error test.

TYPE: int

RETURNS DESCRIPTION
LogPathWeightCertificate

The usual score and exact log endpoints or verified zero mass.

RAISES DESCRIPTION
TypeError

The algebra or evaluated dtype lacks the supported contract.

ValueError

The words, tolerance, or resource declaration is invalid.

ProductiveEpsilonCycleError

The structurally productive observation has a cycle.

RelationLimitError

A state, work, range, or bit limit is exceeded.

RelationAccuracyError

The packed value's error could not be certified at this tolerance.

Source code in src/quivers/core/relations/log_accuracy.py
def certify_logprob_path_weight(
    relation: RationalRelation,
    words: Words,
    *,
    absolute_log_tolerance: Fraction | int,
    max_states: int,
    max_work: int,
    decimal_precision: int,
    max_decimal_exponent: int,
    max_decimal_work: int,
    max_exact_bits: int,
    max_exact_work: int,
) -> LogPathWeightCertificate:
    """Certify absolute log error for a float64 fixed-word LogProb DAG score.

    The ordinary packed score and the directed verifier use the same
    evaluated binary64 slot snapshot. The returned tensor keeps its
    ordinary derivative. The certificate covers its value.

    Parameters
    ----------
    relation : RationalRelation
        A LogProb relation with float64 weights.
    words : Words
        One observed word per original tape.
    absolute_log_tolerance : Fraction or int
        The required nonnegative absolute error in log units.
    max_states, max_work : int
        Observation state and candidate arc budgets.
    decimal_precision, max_decimal_exponent, max_decimal_work : int
        Decimal significant digits, symmetric adjusted exponent bound,
        and maximum primitive calls and exact binary64 conversions.
    max_exact_bits, max_exact_work : int
        Bit and operation bounds for the final rational error test.

    Returns
    -------
    LogPathWeightCertificate
        The usual score and exact log endpoints or verified zero mass.

    Raises
    ------
    TypeError
        The algebra or evaluated dtype lacks the supported contract.
    ValueError
        The words, tolerance, or resource declaration is invalid.
    ProductiveEpsilonCycleError
        The structurally productive observation has a cycle.
    RelationLimitError
        A state, work, range, or bit limit is exceeded.
    RelationAccuracyError
        The packed value's error could not be certified at this tolerance.
    """
    return _logprob_accuracy_plan(
        relation,
        words,
        absolute_log_tolerance=absolute_log_tolerance,
        max_states=max_states,
        max_work=max_work,
        decimal_precision=decimal_precision,
        max_decimal_exponent=max_decimal_exponent,
        max_decimal_work=max_decimal_work,
        max_exact_bits=max_exact_bits,
        max_exact_work=max_exact_work,
    )()

closure

closure(relation: RationalRelation) -> RationalRelation

Build the relation of all finite repetitions, including zero.

Every return to the new boundary state completes one accepting operand path. The topology leaves all repetition counts available. A fixed-word query must request a closure bound when a productive cycle exists, and its algebra must license the resulting sum.

Source code in src/quivers/core/relations/expressions.py
def closure(relation: RationalRelation) -> RationalRelation:
    """Build the relation of all finite repetitions, including zero.

    Every return to the new boundary state completes one accepting
    operand path. The topology leaves all repetition counts available.
    A fixed-word query must request a closure bound when a productive
    cycle exists, and its algebra must license the resulting sum.
    """
    topology = relation.topology
    bridge = topology.n_states
    unit = len(topology.weight_names)
    # The fresh slot name must stay distinct even if the input uses
    # "unit" or any names introduced by earlier transforms.
    marks = (Boundary(bridge, unit),)
    labels = (EPSILON,) * len(topology.tapes)
    entries = tuple(
        Arc(bridge, mark.state, labels, mark.weight) for mark in topology.initial
    )
    exits = tuple(
        Arc(mark.state, bridge, labels, mark.weight) for mark in topology.final
    )
    repeated = replace(
        topology,
        n_states=bridge + 1,
        arcs=topology.arcs + entries + exits,
        initial=marks,
        final=marks,
        weight_names=tuple(f"operand:{name}" for name in topology.weight_names)
        + ("unit",),
    )
    return RationalRelation(
        repeated, _ExpressionWeights(relation), algebra=relation.algebra
    )

compile_ranked_ot

compile_ranked_ot(relation: RationalRelation, violations: Sequence[tuple[int, ...]], caps: tuple[int, ...], *, max_states: int, max_work: int) -> RationalRelation

Compile all-input optimum candidates for capped ranked constraints.

A candidate path sums its violations and caps each coordinate separately. Among paths for the same input, all lexicographically minimum profiles survive. The finite caps are part of the model.

PARAMETER DESCRIPTION
relation

A candidate generator with one input tape and one output tape.

TYPE: RationalRelation

violations

A vector of nonnegative integers per original arc occurrence.

TYPE: Sequence[tuple[int, ...]]

caps

A finite nonnegative cap for each rank. A cap of one makes a constraint binary, and a cap of zero ignores that coordinate.

TYPE: tuple[int, ...]

max_states

Maximum reached states in the weighted product.

TYPE: int

max_work

Maximum product states, original arc examinations and competitor configurations examined by the compilation.

TYPE: int

RETURNS DESCRIPTION
RationalRelation

A transducer with the original tape types and live weight source. Every winning original path occurs exactly once. Ranking is independent of numerical path weights.

RAISES DESCRIPTION
TypeError

If there is no one-input, one-output tape split.

ValueError

If the caps, violation vectors or limits are invalid.

RelationLimitError

If the weighted product or competitor tracker exceeds a limit.

Source code in src/quivers/core/relations/ranked.py
def compile_ranked_ot(
    relation: RationalRelation,
    violations: Sequence[tuple[int, ...]],
    caps: tuple[int, ...],
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Compile all-input optimum candidates for capped ranked constraints.

    A candidate path sums its violations and caps each coordinate
    separately. Among paths for the same input, all lexicographically
    minimum profiles survive. The finite caps are part of the model.

    Parameters
    ----------
    relation : RationalRelation
        A candidate generator with one input tape and one output tape.
    violations : Sequence[tuple[int, ...]]
        A vector of nonnegative integers per original arc occurrence.
    caps : tuple[int, ...]
        A finite nonnegative cap for each rank. A cap of one makes a
        constraint binary, and a cap of zero ignores that coordinate.
    max_states : int
        Maximum reached states in the weighted product.
    max_work : int
        Maximum product states, original arc examinations and
        competitor configurations examined by the compilation.

    Returns
    -------
    RationalRelation
        A transducer with the original tape types and live weight
        source. Every winning original path occurs exactly once.
        Ranking is independent of numerical path weights.

    Raises
    ------
    TypeError
        If there is no one-input, one-output tape split.
    ValueError
        If the caps, violation vectors or limits are invalid.
    RelationLimitError
        If the weighted product or competitor tracker exceeds a limit.
    """
    topology = relation.topology
    _validate_ranks(topology, violations, len(caps))
    if any(type(cap) is not int or cap < 0 for cap in caps):
        raise ValueError("supply one nonnegative integer cap per rank")
    if max_states is None or max_work is None:
        raise ValueError("ranked compilation requires explicit state and work limits")
    _validate_limits(max_states, max_work)
    compiler = _RankedCompiler(topology, violations, caps, max_work)
    winning = compiler.weighted_product(max_states)
    return trim(RationalRelation(winning, relation.module(), algebra=relation.algebra))

concatenate

concatenate(left: RationalRelation, right: RationalRelation) -> RationalRelation

Sum over path pairs whose tape words concatenate to the result.

Each tape reads its left word followed by its right word. A common connecting state takes one left final weight and one right initial weight, preserving them as separate factors. Distinct decompositions of the same word tuple contribute separately. The operands have identical tape types and one shared scalar semiring.

Source code in src/quivers/core/relations/expressions.py
def concatenate(left: RationalRelation, right: RationalRelation) -> RationalRelation:
    """Sum over path pairs whose tape words concatenate to the result.

    Each tape reads its left word followed by its right word. A common
    connecting state takes one left final weight and one right initial
    weight, preserving them as separate factors. Distinct decompositions
    of the same word tuple contribute separately. The operands have
    identical tape types and one shared scalar semiring.
    """
    return _binary_expression(left, right, serial=True)

condition

condition(relation: RationalRelation, tape: int, word: tuple[int, ...], *, max_states: int, max_work: int) -> RationalRelation

Fix the word on one tape and return the relation on the remaining tapes.

A path contributes its original weight when it realizes the given word on the chosen tape. The result preserves the mass of that slice. At least one other tape must remain. The limits bound visits to state and position configurations and examinations of matching arcs.

Source code in src/quivers/core/relations/transforms.py
def condition(
    relation: RationalRelation,
    tape: int,
    word: tuple[int, ...],
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Fix the word on one tape and return the relation on the remaining tapes.

    A path contributes its original weight when it realizes the given
    word on the chosen tape. The result preserves the mass of that
    slice. At least one other tape must remain. The limits bound visits
    to state and position configurations and examinations of matching arcs.
    """
    conditioned = _condition_topology(
        relation.topology, tape, word, max_states=max_states, max_work=max_work
    )
    return RationalRelation(conditioned, relation.module(), algebra=relation.algebra)

dual_alignment_map

dual_alignment_map(graph: StringFactorGraph, *, max_iterations: int, max_ngram_order: int, max_features: int, max_states: int, max_work: int, step_size: Fraction | int = Fraction(1), absolute_gap: Fraction | int | None = None, relative_gap: Fraction | int | None = None, step_schedule: Literal['harmonic', 'constant'] = 'harmonic', max_feature_work: int | None = None, max_feature_cells: int | None = None) -> StringAlignmentMapResult

Maximize joint string and local alignment scores by dual decomposition.

The graph must use LogProb and each factor must have acyclic productive positive support. A factor's score adds the original log weights on its path, including both boundary marks. Original weights are read once per shared source and interpreted as exact binary rationals. Decoding has no gradient contract.

Each factor receives an independent copy of its incident string variables. Updates keep each shared n-gram's multipliers centered across those copies. In case of disagreement, a new distinguishing feature can be added within the configured order and count limits.

PARAMETER DESCRIPTION
graph

The typed variables, observations and weighted relation factors.

TYPE: StringFactorGraph

max_iterations

Positive limit on the number of dual iterations.

TYPE: int

max_ngram_order

Positive maximum order of a newly selected distinguishing feature.

TYPE: int

max_features

Maximum number of selected variable and feature pairs.

TYPE: int

max_states

Maximum reached configurations per local decoding.

TYPE: int

max_work

Maximum examined candidate transitions per local decoding or individual verification scan. Each independently verified local witness has two scans and an additional original trace check.

TYPE: int

step_size

Positive scale for the multiplier step.

TYPE: Fraction or int DEFAULT: Fraction(1)

absolute_gap

A nonnegative target for dual upper bound minus feasible score.

TYPE: Fraction or int or None DEFAULT: None

relative_gap

A nonnegative target for suboptimality divided by the magnitude of the unknown optimum. A finite bound is unavailable when the feasible score is negative and the upper bound is nonnegative. If both targets are supplied, both must be established.

TYPE: Fraction or int or None DEFAULT: None

step_schedule

Divide the step scale by the current iteration, or use it directly. Both schedules preserve the zero sum of each feature's multipliers.

TYPE: Literal['harmonic', 'constant'] DEFAULT: 'harmonic'

max_feature_work

Cumulative cap on adaptive windows, active prefix probes and direct count symbol visits, including witness verification.

TYPE: int or None DEFAULT: None

max_feature_cells

Cap on charged storage for active feature symbols and the temporary buffers for feature selection and direct word counts.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
StringAlignmentMapResult

The best feasible assignment found, exact upper bound, and an optimum certificate only if all incident copies agree on their full words. A proved gap target permits early stopping without that certificate. Budget-limited runs can remain uncertified.

RAISES DESCRIPTION
TypeError

If the graph does not use LogProb weights.

ValueError

If variables are isolated, the solver settings are invalid, or a factor has a productive positive cycle.

RelationLimitError

If exact local decoding or feature processing exceeds a budget.

Source code in src/quivers/core/relations/alignment_dual.py
def dual_alignment_map(
    graph: StringFactorGraph,
    *,
    max_iterations: int,
    max_ngram_order: int,
    max_features: int,
    max_states: int,
    max_work: int,
    step_size: Fraction | int = Fraction(1),
    absolute_gap: Fraction | int | None = None,
    relative_gap: Fraction | int | None = None,
    step_schedule: Literal["harmonic", "constant"] = "harmonic",
    max_feature_work: int | None = None,
    max_feature_cells: int | None = None,
) -> StringAlignmentMapResult:
    """Maximize joint string and local alignment scores by dual decomposition.

    The graph must use LogProb and each factor must have acyclic
    productive positive support. A factor's score adds the original
    log weights on its path, including both boundary marks. Original
    weights are read once per shared source and interpreted as exact
    binary rationals. Decoding has no gradient contract.

    Each factor receives an independent copy of its incident string
    variables. Updates keep each shared n-gram's multipliers centered
    across those copies. In case of disagreement, a new distinguishing
    feature can be added within the configured order and count limits.

    Parameters
    ----------
    graph : StringFactorGraph
        The typed variables, observations and weighted relation factors.
    max_iterations : int
        Positive limit on the number of dual iterations.
    max_ngram_order : int
        Positive maximum order of a newly selected distinguishing feature.
    max_features : int
        Maximum number of selected variable and feature pairs.
    max_states : int
        Maximum reached configurations per local decoding.
    max_work : int
        Maximum examined candidate transitions per local decoding or
        individual verification scan. Each independently verified local
        witness has two scans and an additional original trace check.
    step_size : Fraction or int
        Positive scale for the multiplier step.
    absolute_gap : Fraction or int or None
        A nonnegative target for dual upper bound minus feasible score.
    relative_gap : Fraction or int or None
        A nonnegative target for suboptimality divided by the magnitude
        of the unknown optimum. A finite bound is unavailable when the
        feasible score is negative and the upper bound is nonnegative.
        If both targets are supplied, both must be established.
    step_schedule : Literal["harmonic", "constant"]
        Divide the step scale by the current iteration, or use it directly.
        Both schedules preserve the zero sum of each feature's multipliers.
    max_feature_work : int or None
        Cumulative cap on adaptive windows, active prefix probes and
        direct count symbol visits, including witness verification.
    max_feature_cells : int or None
        Cap on charged storage for active feature symbols and the
        temporary buffers for feature selection and direct word counts.

    Returns
    -------
    StringAlignmentMapResult
        The best feasible assignment found, exact upper bound, and an
        optimum certificate only if all incident copies agree on their
        full words. A proved gap target permits early stopping without
        that certificate. Budget-limited runs can remain uncertified.

    Raises
    ------
    TypeError
        If the graph does not use LogProb weights.
    ValueError
        If variables are isolated, the solver settings are invalid, or
        a factor has a productive positive cycle.
    RelationLimitError
        If exact local decoding or feature processing exceeds a budget.
    """
    settings = _AlignmentSettings(
        max_iterations,
        max_ngram_order,
        max_features,
        max_states,
        max_work,
        step_size,
        absolute_gap,
        relative_gap,
        step_schedule,
        max_feature_work,
        max_feature_cells,
    )
    decoders, scopes, observations = _alignment_inputs(graph)
    run = _DualAlignmentRun(decoders, scopes, max_states, max_work)
    result, _ = _run_alignment_map(run, observations, settings)
    return result

paired_dual_alignment_map

paired_dual_alignment_map(graph: StringFactorGraph, *, groups: _Groups, max_group_states: int, max_group_work: int, max_iterations: int, max_ngram_order: int, max_features: int, max_states: int, max_work: int, step_size: Fraction | int = Fraction(1), absolute_gap: Fraction | int | None = None, relative_gap: Fraction | int | None = None, step_schedule: Literal['harmonic', 'constant'] = 'harmonic', max_feature_work: int | None = None, max_feature_cells: int | None = None) -> PairedAlignmentMapResult

Run exact local alignment MAP with a declared singleton/pair partition.

A pair shares exactly one nominal tape variable. An epsilon-filtered join enforces that variable's equality inside the pair. Other copies coordinate across groups using the same centered n-gram multipliers. Local search and independent verification use exact rational scores.

PARAMETER DESCRIPTION
graph

The unchanged typed LogProb graph with positive productive DAG factors.

TYPE: StringFactorGraph

groups

Ordered singleton or paired groups partitioning original factor positions.

TYPE: tuple of tuples of int

max_group_states

State and construction work limits for each filtered pair join.

TYPE: int

max_group_work

State and construction work limits for each filtered pair join.

TYPE: int

max_iterations

Iteration and adaptive-feature limits for the common dual search.

TYPE: int

max_ngram_order

Iteration and adaptive-feature limits for the common dual search.

TYPE: int

max_features

Iteration and adaptive-feature limits for the common dual search.

TYPE: int

max_states

Local state and per-pass arc limits for each decode and verification.

TYPE: int

max_work

Local state and per-pass arc limits for each decode and verification.

TYPE: int

step_size

Positive scale for the multiplier step.

TYPE: Fraction or int DEFAULT: Fraction(1)

absolute_gap

Optional exact objective gap targets with the ordinary solver's meaning.

TYPE: Fraction or int or None DEFAULT: None

relative_gap

Optional exact objective gap targets with the ordinary solver's meaning.

TYPE: Fraction or int or None DEFAULT: None

step_schedule

The same centered update schedules as the ordinary solver.

TYPE: Literal['harmonic', 'constant'] DEFAULT: 'harmonic'

max_feature_work

Cumulative feature work and charged storage limits for the common dual search, as in the singleton solver.

TYPE: int or None DEFAULT: None

max_feature_cells

Cumulative feature work and charged storage limits for the common dual search, as in the singleton solver.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
PairedAlignmentMapResult

Verified grouped search with feasible original factor paths when found.

RAISES DESCRIPTION
TypeError

The graph does not have the supported LogProb capability.

ValueError

A group or limit is invalid, a pair has a different number of shared tapes, or a factor has cyclic positive support.

RelationLimitError

Grouped construction, local decoding, or feature processing exceeds its budget.

Source code in src/quivers/core/relations/alignment_groups.py
def paired_dual_alignment_map(
    graph: StringFactorGraph,
    *,
    groups: _Groups,
    max_group_states: int,
    max_group_work: int,
    max_iterations: int,
    max_ngram_order: int,
    max_features: int,
    max_states: int,
    max_work: int,
    step_size: Fraction | int = Fraction(1),
    absolute_gap: Fraction | int | None = None,
    relative_gap: Fraction | int | None = None,
    step_schedule: Literal["harmonic", "constant"] = "harmonic",
    max_feature_work: int | None = None,
    max_feature_cells: int | None = None,
) -> PairedAlignmentMapResult:
    """Run exact local alignment MAP with a declared singleton/pair partition.

    A pair shares exactly one nominal tape variable. An epsilon-filtered
    join enforces that variable's equality inside the pair. Other copies
    coordinate across groups using the same centered n-gram multipliers.
    Local search and independent verification use exact rational scores.

    Parameters
    ----------
    graph : StringFactorGraph
        The unchanged typed LogProb graph with positive productive DAG factors.
    groups : tuple of tuples of int
        Ordered singleton or paired groups partitioning original factor positions.
    max_group_states, max_group_work : int
        State and construction work limits for each filtered pair join.
    max_iterations, max_ngram_order, max_features : int
        Iteration and adaptive-feature limits for the common dual search.
    max_states, max_work : int
        Local state and per-pass arc limits for each decode and verification.
    step_size : Fraction or int
        Positive scale for the multiplier step.
    absolute_gap, relative_gap : Fraction or int or None
        Optional exact objective gap targets with the ordinary solver's meaning.
    step_schedule : Literal["harmonic", "constant"]
        The same centered update schedules as the ordinary solver.
    max_feature_work, max_feature_cells : int or None
        Cumulative feature work and charged storage limits for the
        common dual search, as in the singleton solver.

    Returns
    -------
    PairedAlignmentMapResult
        Verified grouped search with feasible original factor paths when found.

    Raises
    ------
    TypeError
        The graph does not have the supported LogProb capability.
    ValueError
        A group or limit is invalid, a pair has a different number of shared
        tapes, or a factor has cyclic positive support.
    RelationLimitError
        Grouped construction, local decoding, or feature processing
        exceeds its budget.
    """
    indices = _validate_groups(groups)
    if set(indices) != set(range(len(graph._factors))):
        raise ValueError("alignment decomposition must partition all original factors")
    if max_group_states is None or max_group_work is None:
        raise ValueError(
            "alignment pair construction requires explicit state and work limits"
        )
    _validate_limits(max_group_states, max_group_work)
    settings = _AlignmentSettings(
        max_iterations,
        max_ngram_order,
        max_features,
        max_states,
        max_work,
        step_size,
        absolute_gap,
        relative_gap,
        step_schedule,
        max_feature_work,
        max_feature_cells,
    )
    decoders, scopes, observations = _alignment_inputs(graph)
    grouped = []
    layouts = []
    origins = []
    shapes = []
    for group in groups:
        left = group[0]
        if len(group) == 1:
            grouped.append(decoders[left])
            layouts.append(scopes[left])
            origins.append(None)
            shapes.append(None)
            continue
        right = group[1]
        try:
            local, scope, origin = _factor_pair(
                decoders[left],
                decoders[right],
                scopes[left],
                scopes[right],
                max_states=max_group_states,
                max_work=max_group_work,
            )
        except RelationLimitError as error:
            raise RelationLimitError(
                f"alignment pair {group} product: {error}"
            ) from error
        grouped.append(local)
        layouts.append(scope)
        origins.append(origin)
        shapes.append((local._topology.n_states, len(local._topology.arcs)))
    run = _DualAlignmentRun(tuple(grouped), tuple(layouts), max_states, max_work)
    search, paths = _run_alignment_map(run, observations, settings)
    original = None
    if paths is not None:
        assert search.assignment is not None
        original = _expand_paths(
            groups, paths, tuple(origins), decoders, scopes, search.assignment
        )
    return PairedAlignmentMapResult(groups, search, original, tuple(shapes))

dual_string_map

dual_string_map(variables: tuple[StringVariable, ...], factors: tuple[FiniteStringScore, ...], *, max_iterations: int, step_size: Fraction | int = Fraction(1)) -> StringMapResult

Maximize the sum of finite-support factors with exact local bounds.

A multiplier is attached to each copy of a variable and word. Each update preserves zero total multiplier for every word. Thus the sum of independent adjusted maxima bounds every feasible joint score from above. Agreement on complete strings gives a feasible solution with that score. Iteration exhaustion reports bounds and no certificate.

The declared supports are scanned independently on each iteration. The centered update is linear in the number of variable occurrences and uses exact rationals. The update step is step_size / iteration starting at iteration one.

Source code in src/quivers/core/relations/dual.py
def dual_string_map(
    variables: tuple[StringVariable, ...],
    factors: tuple[FiniteStringScore, ...],
    *,
    max_iterations: int,
    step_size: Fraction | int = Fraction(1),
) -> StringMapResult:
    """Maximize the sum of finite-support factors with exact local bounds.

    A multiplier is attached to each copy of a variable and word. Each
    update preserves zero total multiplier for every word. Thus the sum
    of independent adjusted maxima bounds every feasible joint score
    from above. Agreement on complete strings gives a feasible solution
    with that score. Iteration exhaustion reports bounds and no certificate.

    The declared supports are scanned independently on each iteration.
    The centered update is linear in the number of variable occurrences
    and uses exact rationals. The update step is `step_size / iteration` starting at iteration one.
    """
    if type(max_iterations) is not int or max_iterations < 1:
        raise ValueError("max_iterations must be a positive integer")
    if type(step_size) not in (Fraction, int) or step_size <= 0:
        raise ValueError("step_size must be a positive rational")
    prepared = _validate_problem(variables, factors)
    if any(not factor.scores for factor in prepared):
        return StringMapResult("infeasible", 0, None, None, None)
    means: dict[str, _WordScores] = {variable.name: {} for variable in variables}
    shifts: tuple[_Adjustment, ...] = tuple(
        tuple(_Potential(means[name], {}) for name in factor.variables)
        for factor in prepared
    )
    upper: Fraction | None = None
    best: Fraction | None = None
    best_words: _Global | None = None
    for iteration in range(1, max_iterations + 1):
        local = tuple(
            _decode(factor, shift)
            for factor, shift in zip(prepared, shifts, strict=True)
        )
        bound = sum((score for score, _ in local), Fraction(0))
        upper = bound if upper is None else min(upper, bound)
        copies: dict[str, list[tuple[_Word, _Potential]]] = defaultdict(list)
        for factor, shift, (_, words) in zip(prepared, shifts, local, strict=True):
            for name, word, potential in zip(
                factor.variables, words, shift, strict=True
            ):
                copies[name].append((word, potential))
        agrees, proposed = _agreed_candidate(copies)
        score = _score(prepared, proposed)
        if score is not None and (best is None or best < score):
            best = score
            best_words = tuple((v.name, proposed[v.name]) for v in variables)
        if agrees:
            if score != bound:
                raise ArithmeticError(
                    "agreeing local string maximizers must attain the bound"
                )
            certificate = StringMapCertificate(
                tuple(words for _, words in local),
                tuple(value for value, _ in local),
                tuple(
                    tuple(p.freeze() for p in local_shifts) for local_shifts in shifts
                ),
            )
            assignment = tuple((v.name, proposed[v.name]) for v in variables)
            return StringMapResult(
                "optimal", iteration, assignment, score, bound, certificate
            )
        _update(copies, Fraction(step_size) / iteration)
    return StringMapResult("limit", max_iterations, best_words, best, upper)

intersect

intersect(left: RationalRelation, right: RationalRelation, *, max_states: int, max_work: int) -> RationalRelation

Multiply the weights of two weighted languages on their common tape.

Each operand has one tape, of the same type and on the same side of the relation. At each word, the result sums the products of all pairs of accepting paths that realize that word. The bounds apply to the sparse product construction.

Source code in src/quivers/core/relations/transforms.py
def intersect(
    left: RationalRelation,
    right: RationalRelation,
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Multiply the weights of two weighted languages on their common tape.

    Each operand has one tape, of the same type and on the same side of
    the relation. At each word, the result sums the products of all
    pairs of accepting paths that realize that word. The bounds apply
    to the sparse product construction.
    """
    if any(len(operand.topology.tapes) != 1 for operand in (left, right)):
        raise TypeError("weighted-language intersection requires one tape per operand")
    if left.topology.input_tapes != right.topology.input_tapes:
        raise TypeError(
            "weighted-language intersection requires the same tape orientation"
        )
    return join(
        left,
        right,
        left_tape=0,
        right_tape=0,
        keep_shared=True,
        max_states=max_states,
        max_work=max_work,
    )

invert

invert(relation: RationalRelation) -> RationalRelation

Exchange the input and output tapes of a relation.

The order within each side and all arc and boundary weights are preserved. Each path realizes the exchanged word tuple.

Source code in src/quivers/core/relations/transforms.py
def invert(relation: RationalRelation) -> RationalRelation:
    """Exchange the input and output tapes of a relation.

    The order within each side and all arc and boundary weights are
    preserved. Each path realizes the exchanged word tuple.
    """
    topology = relation.topology
    split = topology.input_tapes
    count = len(topology.tapes)
    positions = (*range(split, count), *range(split))
    return _select_tapes(relation, positions, count - split)

join

join(left: RationalRelation, right: RationalRelation, *, left_tape: int, right_tape: int, max_states: int, max_work: int, keep_shared: bool = False) -> RationalRelation

Join the operands on one common-type tape.

Each pair of accepting paths whose words agree on the selected tapes contributes once. Surviving input tapes precede output tapes, with left tapes before right tapes on either side. With keep_shared, the common tape occurs once at its left position. The weight sources must use the same established commutative semiring. At least one tape must remain.

The limits bound the states, shared-label probes and constructed arcs of the sparse product before trimming to accepting paths. A join synchronizes a single tape.

Source code in src/quivers/core/relations/joins.py
def join(
    left: RationalRelation,
    right: RationalRelation,
    *,
    left_tape: int,
    right_tape: int,
    max_states: int,
    max_work: int,
    keep_shared: bool = False,
) -> RationalRelation:
    """Join the operands on one common-type tape.

    Each pair of accepting paths whose words agree on the selected
    tapes contributes once. Surviving input tapes precede output tapes,
    with left tapes before right tapes on either side. With
    `keep_shared`, the common tape occurs once at its left position.
    The weight sources must use the same established commutative
    semiring. At least one tape must remain.

    The limits bound the states, shared-label probes and constructed
    arcs of the sparse product before trimming to accepting paths.
    A join synchronizes a single tape.
    """
    if type(keep_shared) is not bool:
        raise TypeError("keep_shared must be a boolean")
    a, b = left.topology, right.topology
    if (
        type(left_tape) is not int
        or not 0 <= left_tape < len(a.tapes)
        or type(right_tape) is not int
        or not 0 <= right_tape < len(b.tapes)
    ):
        raise ValueError("a relation join requires one valid tape position per operand")
    if a.tapes[left_tape] != b.tapes[right_tape]:
        raise TypeError("a relation join requires the same shared tape type")
    if left.algebra is not right.algebra or not left.algebra.establishes(
        *SEMIRING_LAWS, TIMES_COMMUTATIVE
    ):
        raise TypeError("a relation join requires an established commutative semiring")
    if max_states is None or max_work is None:
        raise ValueError("a relation join requires explicit state and work limits")
    _validate_limits(max_states, max_work)
    layout = _JoinLayout.build(a, b, left_tape, right_tape, keep_shared=keep_shared)
    topology, pairs = _materialize_product(a, b, layout, max_states, max_work)
    return RationalRelation(
        topology, _MaterializedWeights(left, right, pairs), algebra=left.algebra
    )

penalized_regular_ngram_projection

penalized_regular_ngram_projection(base: RationalRelation, likelihood: RationalRelation, features: tuple[tuple[int, ...], ...], *, penalty: float, tolerance: float = 1e-09, max_iterations: int = 512, max_states: int, max_work: int, max_closure_size: int | None = None, optimizer: _ProjectionOptimizer = 'backtracking', max_moment_evaluations: int | None = None, max_prefix_group_cells: int | None = None, frontier_seed: tuple[tuple[int, ...], ...] | None = None) -> RegularNgramProjection

Fit an active n-gram family to a regular tilted distribution.

The target multiplies the base by the supplied likelihood. The fitted exponential tilt minimizes forward KL from that target plus a sum of prefix-group coefficient norms. Complete string tables are unnecessary: moments are derivatives of sparse log path sums.

PARAMETER DESCRIPTION
base

One float64 LogProb language with acyclic productive support.

TYPE: RationalRelation

likelihood

One float64 LogProb language on the same tape. The product with the base must have positive finite mass.

TYPE: RationalRelation

features

Candidate feature vocabulary in coefficient order.

TYPE: tuple[tuple[int, ...], ...]

penalty

Nonnegative finite coefficient on the sum of prefix norms. Zero uses the unpenalized forward-KL objective.

TYPE: float

tolerance

Tolerance on the proximal gradient mapping's infinity norm.

TYPE: float DEFAULT: 1e-09

max_iterations

Upper bound on accepted proximal gradient steps.

TYPE: int DEFAULT: 512

max_states

Reached state limit for each sparse relation and query.

TYPE: int

max_work

Work limit for each sparse relation and query.

TYPE: int

max_closure_size

Explicit component limit if the tilted likelihood has productive epsilon cycles.

TYPE: int or None DEFAULT: None

optimizer

Convex proximal gradient with adaptive majorization tests or with the global feature-covariance step bound.

TYPE: ('backtracking', 'fixed_lipschitz') DEFAULT: "backtracking"

max_moment_evaluations

Cap on target, base and trial moment evaluations in this fit.

TYPE: int or None DEFAULT: None

max_prefix_group_cells

Cap on stored coefficient indices across all prefix groups, including the root. With a frontier it covers the full and restricted groups allocated together. Applies at positive penalty.

TYPE: int or None DEFAULT: None

frontier_seed

Ordered starting subset of the full dictionary, which may be empty. With a fixed Lipschitz step, restrict each fit stage to that subset and expand it after a full-domain residual check. None uses the full dictionary at every fit step.

TYPE: tuple or None DEFAULT: None

RETURNS DESCRIPTION
RegularNgramProjection

The optimizer status and current fit. The returned relation includes only active features. Inputs are read once and snapshotted and the optimizer is not differentiated.

RAISES DESCRIPTION
RelationLimitError

If the moment or prefix-group budget is exhausted.

ValueError

If the declared frontier or optimizer policy is invalid.

Source code in src/quivers/core/relations/regular_projection.py
@torch.inference_mode(False)
def penalized_regular_ngram_projection(
    base: RationalRelation,
    likelihood: RationalRelation,
    features: tuple[tuple[int, ...], ...],
    *,
    penalty: float,
    tolerance: float = 1e-9,
    max_iterations: int = 512,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
    optimizer: _ProjectionOptimizer = "backtracking",
    max_moment_evaluations: int | None = None,
    max_prefix_group_cells: int | None = None,
    frontier_seed: tuple[tuple[int, ...], ...] | None = None,
) -> RegularNgramProjection:
    """Fit an active n-gram family to a regular tilted distribution.

    The target multiplies the base by the supplied likelihood. The
    fitted exponential tilt minimizes forward KL from that target plus
    a sum of prefix-group coefficient norms. Complete string tables
    are unnecessary: moments are derivatives of sparse log path sums.

    Parameters
    ----------
    base : RationalRelation
        One float64 LogProb language with acyclic productive support.
    likelihood : RationalRelation
        One float64 LogProb language on the same tape. The product
        with the base must have positive finite mass.
    features : tuple[tuple[int, ...], ...]
        Candidate feature vocabulary in coefficient order.
    penalty : float
        Nonnegative finite coefficient on the sum of prefix norms.
        Zero uses the unpenalized forward-KL objective.
    tolerance : float
        Tolerance on the proximal gradient mapping's infinity norm.
    max_iterations : int
        Upper bound on accepted proximal gradient steps.
    max_states : int
        Reached state limit for each sparse relation and query.
    max_work : int
        Work limit for each sparse relation and query.
    max_closure_size : int or None
        Explicit component limit if the tilted likelihood has
        productive epsilon cycles.
    optimizer : {"backtracking", "fixed_lipschitz"}
        Convex proximal gradient with adaptive majorization tests or
        with the global feature-covariance step bound.
    max_moment_evaluations : int or None
        Cap on target, base and trial moment evaluations in this fit.
    max_prefix_group_cells : int or None
        Cap on stored coefficient indices across all prefix groups,
        including the root. With a frontier it covers the full and
        restricted groups allocated together. Applies at positive penalty.
    frontier_seed : tuple or None
        Ordered starting subset of the full dictionary, which may be
        empty. With a fixed Lipschitz step, restrict each fit stage to
        that subset and expand it after a full-domain residual check.
        None uses the full dictionary at every fit step.

    Returns
    -------
    RegularNgramProjection
        The optimizer status and current fit. The returned relation
        includes only active features. Inputs are read once and
        snapshotted and the optimizer is not differentiated.

    Raises
    ------
    RelationLimitError
        If the moment or prefix-group budget is exhausted.
    ValueError
        If the declared frontier or optimizer policy is invalid.
    """
    if base.algebra is not LOG_PROB or likelihood.algebra is not LOG_PROB:
        raise TypeError("regular n-gram projection requires LogProb relations")
    if (
        len(base.topology.tapes) != 1
        or base.topology.tapes != likelihood.topology.tapes
    ):
        raise TypeError(
            "regular n-gram projection requires matching one-tape languages"
        )
    if max_states is None or max_work is None:
        raise ValueError(
            "regular n-gram projection requires explicit state and work limits"
        )
    _validate_limits(max_states, max_work, max_closure_size)
    _validate_projection_settings(tolerance, max_iterations, 0)
    _validate_regular_optimizer(optimizer)
    _validate_projection_resources(max_moment_evaluations, max_prefix_group_cells)
    if frontier_seed is not None and optimizer != "fixed_lipschitz":
        raise ValueError("the feature frontier requires the fixed_lipschitz optimizer")
    if not 0 <= penalty < float("inf"):
        raise ValueError("n-gram projection penalty must be nonnegative and finite")
    length = _maximum_length(base)
    with _weight_snapshot(), torch.no_grad():
        base = _snapshot(base)
        likelihood = _snapshot(likelihood)
    anchor = base._weights()
    other = likelihood._weights()
    if (
        anchor.dtype != torch.float64
        or other.dtype != anchor.dtype
        or other.device != anchor.device
    ):
        raise TypeError(
            "regular n-gram projection requires float64 weights on a common device"
        )

    base_plan = NgramMessagePlan(
        base, features, max_states=max_states, max_work=max_work
    )
    features = base_plan.features
    frontier = (
        None if frontier_seed is None else _frontier_indices(features, frontier_seed)
    )
    if (
        penalty
        and max_prefix_group_cells is not None
        and sum(len(gram) + 1 for gram in features) > max_prefix_group_cells
    ):
        raise RelationLimitError("regular projection exceeds max_prefix_group_cells")
    tilted = intersect(base, likelihood, max_states=max_states, max_work=max_work)
    tilt_plan = NgramMessagePlan(
        tilted, features, max_states=max_states, max_work=max_work
    )
    evaluate_base = _MomentPlan(
        base_plan, anchor, max_states, max_work, None, distribution="regular reference"
    )
    evaluate_tilt = _MomentPlan(
        tilt_plan,
        anchor,
        max_states,
        max_work,
        max_closure_size,
        distribution="tilted distribution",
    )
    moment_evaluations = 0
    restricted_moment_evaluations = 0

    def evaluate(
        plan: _MomentPlan, coefficients: torch.Tensor, *, restricted: bool = False
    ) -> tuple[torch.Tensor, torch.Tensor]:
        nonlocal moment_evaluations, restricted_moment_evaluations
        if (
            max_moment_evaluations is not None
            and moment_evaluations == max_moment_evaluations
        ):
            raise RelationLimitError(
                "regular projection exceeds max_moment_evaluations"
            )
        moment_evaluations += 1
        restricted_moment_evaluations += int(restricted)
        return plan(coefficients)

    coefficients = anchor.new_zeros(len(features))
    tilt_mass, target = evaluate(evaluate_tilt, coefficients)
    del evaluate_tilt, tilt_plan, tilted
    base_mass, fitted = evaluate(evaluate_base, coefficients)
    # The variance of each count is at most one quarter of its
    # squared range. Their sum bounds the covariance operator norm.
    range_squares = sum(max(0, length - len(gram) + 1) ** 2 for gram in features)
    denominator = max(4, range_squares)
    guaranteed_step = 4 / denominator
    numerator, divisor = guaranteed_step.as_integer_ratio()
    if numerator * denominator > 4 * divisor:
        guaranteed_step = nextafter(guaranteed_step, 0.0)
    if guaranteed_step == 0 or (penalty and guaranteed_step * penalty == 0):
        raise OverflowError(
            "regular n-gram projection step exceeds the evaluation precision"
        )
    groups = _groups(features, anchor.device, penalty)

    def full(value: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        return evaluate(evaluate_base, value)

    frontier_sizes: tuple[int, ...] = ()
    frontier_checks = 0
    if frontier is None:
        optimum = _fit_coefficients(
            coefficients,
            base_mass,
            fitted,
            target,
            full,
            groups,
            penalty=penalty,
            tolerance=tolerance,
            max_iterations=max_iterations,
            guaranteed_step=guaranteed_step,
            optimizer=optimizer,
        )
    else:

        def restrict(
            active: tuple[_Feature, ...],
        ) -> Callable[[torch.Tensor], tuple[torch.Tensor, torch.Tensor]]:
            plan = NgramMessagePlan(
                base, active, max_states=max_states, max_work=max_work
            )
            evaluate_active = _MomentPlan(
                plan,
                anchor,
                max_states,
                max_work,
                None,
                distribution="regular reference",
            )
            return lambda value: evaluate(evaluate_active, value, restricted=True)

        optimum, frontier_sizes, frontier_checks = _fit_frontier(
            coefficients,
            base_mass,
            fitted,
            target,
            features=features,
            indices=frontier,
            full=full,
            restrict=restrict,
            groups=groups,
            penalty=penalty,
            tolerance=tolerance,
            max_iterations=max_iterations,
            max_prefix_group_cells=max_prefix_group_cells,
            step=guaranteed_step,
        )
    coefficients, normalizer, fitted = (
        optimum.coefficients,
        optimum.normalizer,
        optimum.moments,
    )
    norms = sum(
        (
            torch.linalg.vector_norm(coefficients.index_select(0, group))
            for group in groups
        ),
        anchor.new_zeros(()),
    )
    regularization = penalty * norms
    objective = normalizer - base_mass - coefficients @ target + regularization
    active = tuple(i for i, value in enumerate(coefficients.tolist()) if value)
    retained = tuple(features[i] for i in active)
    compact = NgramMessagePlan(base, retained, max_states=max_states, max_work=max_work)
    active_ids = torch.tensor(active, dtype=torch.long, device=anchor.device)
    message = compact.bind(coefficients.index_select(0, active_ids))
    return RegularNgramProjection(
        optimum.status,
        optimum.iterations,
        coefficients,
        retained,
        target,
        fitted,
        base_mass,
        tilt_mass,
        normalizer,
        objective,
        regularization,
        optimum.residual,
        message,
        base_plan.n_states,
        compact.n_states,
        optimizer,
        moment_evaluations,
        frontier_sizes,
        frontier_checks,
        restricted_moment_evaluations,
    )

minimize_static_acceptor

minimize_static_acceptor(relation: RationalRelation) -> RationalRelation

Minimize an epsilon-free deterministic acceptor on its acyclic positive support.

Each reachable nonzero residual series is factored by the rational gcd of its coefficients. Two states share a class exactly when the resulting primitive series coincide. The resulting class count is minimal among epsilon-free deterministic acceptors with one initial state.

PARAMETER DESCRIPTION
relation

A one-tape Markov acceptor with at most one initial state and nontrainable floating-point weights.

TYPE: RationalRelation

RETURNS DESCRIPTION
RationalRelation

A static snapshot in the input dtype and on the same device. Original floating-point coefficients are interpreted as their exact binary rationals.

RAISES DESCRIPTION
TypeError

If the relation has an incompatible algebra, tape or initial boundary count, or unsupported weight type.

ValueError

If the relation has epsilon arcs, duplicate symbol transitions, or a cycle on productive positive support, or if a canonical quotient coefficient is unrepresentable.

Source code in src/quivers/core/relations/minimization.py
def minimize_static_acceptor(relation: RationalRelation) -> RationalRelation:
    """Minimize an epsilon-free deterministic acceptor on its acyclic positive support.

    Each reachable nonzero residual series is factored by the rational
    gcd of its coefficients. Two states share a class exactly when the
    resulting primitive series coincide. The resulting class count
    is minimal among epsilon-free deterministic acceptors with one
    initial state.

    Parameters
    ----------
    relation : RationalRelation
        A one-tape Markov acceptor with at most one initial state and
        nontrainable floating-point weights.

    Returns
    -------
    RationalRelation
        A static snapshot in the input dtype and on the same device.
        Original floating-point coefficients are interpreted as their
        exact binary rationals.

    Raises
    ------
    TypeError
        If the relation has an incompatible algebra, tape or initial
        boundary count, or unsupported weight type.
    ValueError
        If the relation has epsilon arcs, duplicate symbol
        transitions, or a cycle on productive positive support, or
        if a canonical quotient coefficient is unrepresentable.
    """
    positive, values, weights = _static_support(relation)
    classes, class_of, divisors = _residual_classes(positive, values)
    return _quotient(positive, classes, class_of, divisors, values, weights)

minimize_static_acceptor_with_work

minimize_static_acceptor_with_work(relation: RationalRelation, *, max_states: int | None = None, max_work: int | None = None) -> tuple[RationalRelation, StaticMinimizationWork]

Find the smallest static deterministic Markov acceptor, with work counts.

Every productive state is scaled by the exact weight of its shortest accepted suffix, breaking ties by symbol order. A sparse smaller-half refinement identifies states whose scaled series coincide. Each finite word has the same weight in the quotient, even when the sum over all accepted lengths is infinite.

PARAMETER DESCRIPTION
relation

A static one-tape Markov acceptor with at most one initial mark, epsilon-free deterministic symbols, and floating-point weights.

TYPE: RationalRelation

max_states

Limit on the number of states in the positive productive support.

TYPE: int or None DEFAULT: None

max_work

Limit on the input records plus state and incoming arc visits during refinement. The counters measure structural work, with exact rational arithmetic costs dependent on coefficient lengths.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
tuple[RationalRelation, StaticMinimizationWork]

The detached minimal quotient and the structural work counts. Coefficients use the original dtype and device. Comparisons and scaling treat source floats as exact binary rationals.

RAISES DESCRIPTION
TypeError

If the algebra, tape or initial boundary count, or weight type is unsupported, or parameters are trainable.

ValueError

If limits are invalid, symbol transitions are ambiguous or use epsilon, or a shortest-suffix quotient coefficient cannot be represented exactly in the original dtype.

RelationLimitError

If a state or work limit is exhausted.

Source code in src/quivers/core/relations/minimization.py
def minimize_static_acceptor_with_work(
    relation: RationalRelation,
    *,
    max_states: int | None = None,
    max_work: int | None = None,
) -> tuple[RationalRelation, StaticMinimizationWork]:
    """Find the smallest static deterministic Markov acceptor, with work counts.

    Every productive state is scaled by the exact weight of its shortest
    accepted suffix, breaking ties by symbol order. A sparse smaller-half
    refinement identifies states whose scaled series coincide. Each
    finite word has the same weight in the quotient, even when the sum
    over all accepted lengths is infinite.

    Parameters
    ----------
    relation : RationalRelation
        A static one-tape Markov acceptor with at most one initial mark,
        epsilon-free deterministic symbols, and floating-point weights.
    max_states : int or None
        Limit on the number of states in the positive productive support.
    max_work : int or None
        Limit on the input records plus state and incoming arc visits
        during refinement. The counters measure structural work, with
        exact rational arithmetic costs dependent on coefficient lengths.

    Returns
    -------
    tuple[RationalRelation, StaticMinimizationWork]
        The detached minimal quotient and the structural work counts.
        Coefficients use the original dtype and device. Comparisons and
        scaling treat source floats as exact binary rationals.

    Raises
    ------
    TypeError
        If the algebra, tape or initial boundary count, or weight type
        is unsupported, or parameters are trainable.
    ValueError
        If limits are invalid, symbol transitions are ambiguous or use
        epsilon, or a shortest-suffix quotient coefficient cannot be
        represented exactly in the original dtype.
    RelationLimitError
        If a state or work limit is exhausted.
    """
    _validate_limits(max_states, max_work)
    source = relation.topology
    records = (
        len(source.arcs)
        + len(source.initial)
        + len(source.final)
        + len(source.weight_names)
    )
    if max_work is not None and records > max_work:
        raise RelationLimitError("static acceptor minimization exceeds max_work")
    topology, values, weights = _static_support(relation)
    final = {mark.state: values[mark.weight] for mark in topology.final}
    states = dict.fromkeys(final)
    for arc in topology.arcs:
        states[arc.source] = states[arc.target] = None
    if max_states is not None and len(states) > max_states:
        raise RelationLimitError("static acceptor minimization exceeds max_states")

    outgoing: dict[int, list[Arc]] = {state: [] for state in states}
    incoming: dict[int, list[Arc]] = {state: [] for state in states}
    for arc in topology.arcs:
        outgoing[arc.source].append(arc)
        incoming[arc.target].append(arc)
    scales = _shortlex_scales(outgoing, incoming, final, values)
    accept = {state: final.get(state, Fraction(0)) / scales[state] for state in states}
    pushed: dict[int, list[tuple[int, Fraction, int]]] = {state: [] for state in states}
    predecessors: dict[int, list[tuple[int, int]]] = {state: [] for state in states}
    labels: dict[tuple[int, Fraction], int] = {}
    for arc in topology.arcs:
        symbol = arc.labels[0]
        assert symbol is not None
        weight = values[arc.weight] * scales[arc.target] / scales[arc.source]
        label = labels.setdefault((symbol, weight), len(labels))
        pushed[arc.source].append((symbol, weight, arc.target))
        predecessors[arc.target].append((arc.source, label))

    remaining = None if max_work is None else max_work - records
    blocks, class_of, splitter_states, predecessor_examinations = _refine(
        accept, predecessors, remaining
    )
    representatives = tuple(map(min, blocks))
    classes = tuple(
        (
            accept[state],
            tuple(
                (symbol, value, class_of[target])
                for symbol, value, target in pushed[state]
            ),
        )
        for state in representatives
    )
    work = StaticMinimizationWork(
        records,
        len(states),
        len(topology.arcs),
        splitter_states,
        predecessor_examinations,
    )
    return _quotient(topology, classes, class_of, scales, values, weights), work

project

project(relation: RationalRelation, positions: tuple[int, ...]) -> RationalRelation

Retain the supplied original tape positions in increasing order.

Each arc retains its occurrence and weight. Erasing a tape sums over the words realized on it, so projection can expose a productive epsilon cycle on the retained tapes. At least one tape must remain.

Source code in src/quivers/core/relations/transforms.py
def project(relation: RationalRelation, positions: tuple[int, ...]) -> RationalRelation:
    """Retain the supplied original tape positions in increasing order.

    Each arc retains its occurrence and weight. Erasing a tape sums over
    the words realized on it, so projection can expose a productive
    epsilon cycle on the retained tapes. At least one tape must remain.
    """
    topology = relation.topology
    if not positions or any(
        type(index) is not int or not 0 <= index < len(topology.tapes)
        for index in positions
    ):
        raise ValueError("projection requires at least one valid retained tape")
    if any(right <= left for left, right in zip(positions, positions[1:])):
        raise ValueError("projection requires strictly increasing tape positions")
    input_tapes = sum(index < topology.input_tapes for index in positions)
    return _select_tapes(relation, positions, input_tapes)

regular_string_ep

regular_string_ep(graph: StringFactorGraph, bases: Mapping[str, RationalRelation], features: Mapping[str, tuple[tuple[int, ...], ...]], *, 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, 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

Approximate sum-product over finite regular reference languages.

Factor scores are multiplied against the supplied base languages. A base gives one reference weight per word, with observed variables additionally restricted to their observed words. A factor tape may occur on either side of a relation because the site reads its unary score at the same word. Sites are exponentiated n-gram scores with separate log scales. No table over all words or assignments is built.

PARAMETER DESCRIPTION
graph

The typed graph with float64 LogProb factor weights.

TYPE: StringFactorGraph

bases

One acyclic productive reference language per variable.

TYPE: Mapping[str, RationalRelation]

features

One finite candidate n-gram vocabulary per variable.

TYPE: Mapping[str, tuple[tuple[int, ...], ...]]

penalty

Nonnegative weight on the local n-gram prefix-group penalty.

TYPE: float

max_sweeps

Maximum synchronous sweeps accepted by the outer solver.

TYPE: int

max_states

Reached state limit for each relation product or query.

TYPE: int

max_work

Work limit for each relation product or query.

TYPE: int

max_closure_size

Bound for productive epsilon closure in tilted factors.

TYPE: int or None DEFAULT: None

tolerance

Upper bound on a site's undamped change in log score, including its scale. None uses the full sweep budget.

TYPE: float or None DEFAULT: 1e-08

damping

Fraction of the previous site retained in log-space damping.

TYPE: float DEFAULT: 0.0

projection_tolerance

Local proximal gradient tolerance.

TYPE: float DEFAULT: 1e-08

projection_max_iterations

Maximum accepted iterations per local projection.

TYPE: int DEFAULT: 512

projection_optimizer

The local proximal optimizer and step policy.

TYPE: ('backtracking', 'fixed_lipschitz') DEFAULT: "backtracking"

initial_sites

Optional initial site records in factor and argument order. Each record gives the factor position, variable, candidate features in order, finite float coefficients, and finite float log scale. None initializes unit sites.

TYPE: tuple or None DEFAULT: None

max_moment_evaluations

Total number of target, base and trial moment evaluations, across all attempted site fits and the final diagnostic pass.

TYPE: int or None DEFAULT: None

max_prefix_group_cells

Maximum stored coefficient indices across prefix groups in one penalized site fit.

TYPE: int or None DEFAULT: None

projection_frontiers

Variable names paired with initial subsets of their candidate n-grams in candidate order. Each listed site's fixed-step fit may expand its subset after a full residual check. Unlisted variables fit their full dictionaries at every step.

TYPE: tuple or None DEFAULT: None

RETURNS DESCRIPTION
RegularStringEPResult

Approximate marginals at the last accepted sweep. Local optimizer failure has a separate status, and relation resource errors propagate. Weights are snapshotted and the schedule is not differentiated.

RAISES DESCRIPTION
RelationLimitError

If sparse construction, moment evaluations, or prefix-group storage exceeds its declared limit.

Source code in src/quivers/core/relations/regular_ep.py
@torch.inference_mode(False)
def regular_string_ep(
    graph: StringFactorGraph,
    bases: Mapping[str, RationalRelation],
    features: Mapping[str, tuple[tuple[int, ...], ...]],
    *,
    penalty: float,
    max_sweeps: int,
    max_states: int,
    max_work: int,
    max_closure_size: int | None = None,
    tolerance: float | None = 1e-8,
    damping: float = 0.0,
    projection_tolerance: float = 1e-8,
    projection_max_iterations: int = 512,
    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:
    """Approximate sum-product over finite regular reference languages.

    Factor scores are multiplied against the supplied base languages.
    A base gives one reference weight per word, with observed variables
    additionally restricted to their observed words. A factor tape
    may occur on either side of a relation because the site reads its
    unary score at the same word. Sites are exponentiated n-gram
    scores with separate log scales. No table over all words or
    assignments is built.

    Parameters
    ----------
    graph : StringFactorGraph
        The typed graph with float64 LogProb factor weights.
    bases : Mapping[str, RationalRelation]
        One acyclic productive reference language per variable.
    features : Mapping[str, tuple[tuple[int, ...], ...]]
        One finite candidate n-gram vocabulary per variable.
    penalty : float
        Nonnegative weight on the local n-gram prefix-group penalty.
    max_sweeps : int
        Maximum synchronous sweeps accepted by the outer solver.
    max_states : int
        Reached state limit for each relation product or query.
    max_work : int
        Work limit for each relation product or query.
    max_closure_size : int or None
        Bound for productive epsilon closure in tilted factors.
    tolerance : float or None
        Upper bound on a site's undamped change in log score,
        including its scale. None uses the full sweep budget.
    damping : float
        Fraction of the previous site retained in log-space damping.
    projection_tolerance : float
        Local proximal gradient tolerance.
    projection_max_iterations : int
        Maximum accepted iterations per local projection.
    projection_optimizer : {"backtracking", "fixed_lipschitz"}
        The local proximal optimizer and step policy.
    initial_sites : tuple or None
        Optional initial site records in factor and argument order. Each
        record gives the factor position, variable, candidate features in
        order, finite float coefficients, and finite float log scale.
        None initializes unit sites.
    max_moment_evaluations : int or None
        Total number of target, base and trial moment evaluations,
        across all attempted site fits and the final diagnostic pass.
    max_prefix_group_cells : int or None
        Maximum stored coefficient indices across prefix groups in
        one penalized site fit.
    projection_frontiers : tuple or None
        Variable names paired with initial subsets of their candidate
        n-grams in candidate order. Each listed site's fixed-step fit
        may expand its subset after a full residual check. Unlisted
        variables fit their full dictionaries at every step.

    Returns
    -------
    RegularStringEPResult
        Approximate marginals at the last accepted sweep. Local
        optimizer failure has a separate status, and relation resource
        errors propagate. Weights are snapshotted and the schedule is
        not differentiated.

    Raises
    ------
    RelationLimitError
        If sparse construction, moment evaluations, or prefix-group
        storage exceeds its declared limit.
    """
    _validate_sweeps(max_sweeps, tolerance, damping)
    _validate_projection_settings(projection_tolerance, projection_max_iterations, 0)
    _validate_regular_optimizer(projection_optimizer)
    frontiers = _validate_frontier_seeds(
        projection_frontiers, features, projection_optimizer
    )
    _validate_projection_resources(max_moment_evaluations, max_prefix_group_cells)
    _validate_initial_values(initial_sites)
    if not 0 <= penalty < float("inf"):
        raise ValueError("n-gram projection penalty must be nonnegative and finite")
    if set(graph._variables) != set(bases) or set(graph._variables) != set(features):
        raise ValueError(
            "regular string EP requires bases and feature vocabularies for every variable"
        )
    _validate_initial_scope(
        tuple(f.variables for f in graph._factors), features, initial_sites
    )
    for name, variable in graph._variables.items():
        base = bases[name]
        if base.algebra is not LOG_PROB or base.topology.tapes != (variable.tape,):
            raise TypeError(
                f"regular string EP has a mistyped LogProb base for {name!r}"
            )
    if any(factor.relation.algebra is not LOG_PROB for factor in graph._factors):
        raise TypeError("regular string EP requires LogProb factors")
    bounds = _TreeBounds(max_states, max_work, max_closure_size)
    with _weight_snapshot(), torch.no_grad():
        frozen_bases = {name: _snapshot(base) for name, base in bases.items()}
        factors = tuple(
            StringFactor(factor.variables, _snapshot(factor.relation))
            for factor in graph._factors
        )
    sources = [relation._weights() for relation in frozen_bases.values()]
    sources.extend(factor.relation._weights() for factor in factors)
    if any(
        weights.dtype != torch.float64 or weights.device != sources[0].device
        for weights in sources
    ):
        raise TypeError("regular string EP requires float64 weights on a common device")
    references = {}
    for name, base in frozen_bases.items():
        variable = graph._variables[name]
        if variable.observed is not None:
            base = bounds.product(base, bounds.one_word(variable, base), keep=True)
        references[name] = _ReferenceLanguage(base, features[name], bounds)

    initial = iter(initial_sites) if initial_sites is not None else None
    rows = []
    for factor in factors:
        row = []
        for name in factor.variables:
            zeros = references[name].zeros
            if initial is None:
                row.append(_Site(zeros, zeros.new_zeros(())))
            else:
                _, _, _, coefficients, scale = next(initial)
                row.append(
                    _Site(zeros.new_tensor(coefficients), zeros.new_tensor(scale))
                )
        rows.append(tuple(row))
    sites = tuple(rows)
    sweeps = 0
    moment_evaluations = 0
    while True:
        marginals, cavity = _beliefs(references, factors, sites)
        updates: list[RegularStringSiteUpdate] = []
        report: list[RegularStringSite] = []
        for index, (factor, row) in enumerate(zip(factors, sites, strict=True)):
            for name, site in zip(factor.variables, row, strict=True):
                active, coefficients = references[name].active(site.coefficients)
                report.append(
                    RegularStringSite(index, name, active, coefficients, site.scale)
                )
        proposed: list[tuple[_Site, ...]] = []
        residual = 0.0
        for index, (factor, row) in enumerate(zip(factors, sites, strict=True)):
            incoming = tuple(cavity[index, axis] for axis in range(len(row)))
            next_row: list[_Site] = []
            for axis, (name, current) in enumerate(
                zip(factor.variables, row, strict=True)
            ):
                reference = references[name]
                fit, scale, mass = _projection(
                    factor,
                    axis,
                    incoming,
                    reference,
                    penalty=penalty,
                    tolerance=projection_tolerance,
                    max_iterations=projection_max_iterations,
                    optimizer=projection_optimizer,
                    max_moment_evaluations=(
                        None
                        if max_moment_evaluations is None
                        else max_moment_evaluations - moment_evaluations
                    ),
                    max_prefix_group_cells=max_prefix_group_cells,
                    frontier_seed=frontiers.get(name),
                )
                moment_evaluations += fit.moment_evaluations
                updates.append(RegularStringSiteUpdate(index, name, mass, fit))
                if fit.status != "converged":
                    return RegularStringEPResult(
                        MappingProxyType(marginals),
                        tuple(report),
                        "projection_failed",
                        sweeps,
                        None,
                        tuple(updates),
                        moment_evaluations,
                    )
                candidate = _Site(fit.coefficients, scale)
                difference = (
                    candidate.scale - current.scale
                ).abs() + reference.length * (
                    candidate.coefficients - current.coefficients
                ).abs().sum()
                if not bool(torch.isfinite(difference)):
                    raise OverflowError(
                        "regular string EP residual is outside the evaluation precision"
                    )
                residual = max(residual, difference.item())
                next_row.append(
                    current.damp(candidate, damping) if damping else candidate
                )
            proposed.append(tuple(next_row))
        converged = tolerance is not None and residual <= tolerance
        if converged or sweeps == max_sweeps:
            return RegularStringEPResult(
                MappingProxyType(marginals),
                tuple(report),
                "converged" if converged else "limit",
                sweeps,
                residual,
                tuple(updates),
                moment_evaluations,
            )
        sites = tuple(proposed)
        sweeps += 1

ranked_output_candidates

ranked_output_candidates(relation: RationalRelation, input_word: tuple[int, ...], violations: Sequence[tuple[int, ...]], *, max_states: int, max_work: int) -> RationalRelation

Restrict a fixed input to its lexicographically optimal candidate paths.

A path sums the violation vectors of its arcs. Initial and final marks contribute zero. Earlier coordinates take priority over all later coordinates. Ranking is independent of numerical path weights.

PARAMETER DESCRIPTION
relation

The candidate generator, with one input tape and one output tape.

TYPE: RationalRelation

input_word

The input whose candidates compete.

TYPE: tuple[int, ...]

violations

One vector of nonnegative integers per original arc occurrence. All vectors must have the same length.

TYPE: Sequence[tuple[int, ...]]

max_states

Maximum reachable state and input position configurations.

TYPE: int

max_work

Maximum arcs compatible with the fixed input that the planner examines.

TYPE: int

RETURNS DESCRIPTION
RationalRelation

An acceptor on the output tape. All and only optimal original paths contribute with their original live weights. Zero-vector cycles can remain, so scoring may require an algebraic closure.

RAISES DESCRIPTION
TypeError

If the generator does not have one input and one output tape.

ValueError

If the input word, violation table, or construction limits are invalid.

RelationLimitError

If the fixed-input graph exceeds the state or arc budget.

Source code in src/quivers/core/relations/ranked.py
def ranked_output_candidates(
    relation: RationalRelation,
    input_word: tuple[int, ...],
    violations: Sequence[tuple[int, ...]],
    *,
    max_states: int,
    max_work: int,
) -> RationalRelation:
    """Restrict a fixed input to its lexicographically optimal candidate paths.

    A path sums the violation vectors of its arcs. Initial and final
    marks contribute zero. Earlier coordinates take priority over all
    later coordinates. Ranking is independent of numerical path weights.

    Parameters
    ----------
    relation : RationalRelation
        The candidate generator, with one input tape and one output tape.
    input_word : tuple[int, ...]
        The input whose candidates compete.
    violations : Sequence[tuple[int, ...]]
        One vector of nonnegative integers per original arc occurrence.
        All vectors must have the same length.
    max_states : int
        Maximum reachable state and input position configurations.
    max_work : int
        Maximum arcs compatible with the fixed input that the planner
        examines.

    Returns
    -------
    RationalRelation
        An acceptor on the output tape. All and only optimal original
        paths contribute with their original live weights. Zero-vector
        cycles can remain, so scoring may require an algebraic closure.

    Raises
    ------
    TypeError
        If the generator does not have one input and one output tape.
    ValueError
        If the input word, violation table, or construction limits
        are invalid.
    RelationLimitError
        If the fixed-input graph exceeds the state or arc budget.
    """
    topology = relation.topology
    width = len(violations[0]) if violations else 0
    _validate_ranks(topology, violations, width)

    origins: list[int] = []
    fixed = _condition_topology(
        topology,
        0,
        input_word,
        max_states=max_states,
        max_work=max_work,
        origins=origins,
    )
    ranks = [violations[index] for index in origins]
    best = _suffix_ranks(fixed, ranks, (0,) * width)
    optimum = min(
        (best[mark.state] for mark in fixed.initial if mark.state in best),
        default=None,
    )

    # Each retained arc attains equality in the suffix bound. A path
    # starting at an optimal initial and ending at any final telescopes
    # to the optimum. Any optimum must have equality at every step.
    winning = replace(
        fixed,
        initial=tuple(
            mark
            for mark in fixed.initial
            if mark.state in best and best[mark.state] == optimum
        ),
        arcs=tuple(
            arc
            for arc, rank in zip(fixed.arcs, ranks, strict=True)
            if arc.target in best
            and best[arc.source] == tuple(map(add, rank, best[arc.target]))
        ),
    )
    return trim(RationalRelation(winning, relation.module(), algebra=relation.algebra))

trim

Retain the arcs and boundary marks on structurally accepting walks.

The retained arcs keep their original relative order and distinct occurrences. State IDs and weight slots are retained. Structural reachability is independent of the current weights.

Source code in src/quivers/core/relations/transforms.py
def trim(relation: RationalRelation) -> RationalRelation:
    """Retain the arcs and boundary marks on structurally accepting walks.

    The retained arcs keep their original relative order and distinct
    occurrences. State IDs and weight slots are retained. Structural
    reachability is independent of the current weights.
    """
    topology = relation.topology
    forward: dict[int, list[int]] = defaultdict(list)
    backward: dict[int, list[int]] = defaultdict(list)
    for arc in topology.arcs:
        forward[arc.source].append(arc.target)
        backward[arc.target].append(arc.source)
    productive = _reached((mark.state for mark in topology.initial), forward)
    productive &= _reached((mark.state for mark in topology.final), backward)
    trimmed = replace(
        topology,
        arcs=tuple(
            arc
            for arc in topology.arcs
            if arc.source in productive and arc.target in productive
        ),
        initial=tuple(mark for mark in topology.initial if mark.state in productive),
        final=tuple(mark for mark in topology.final if mark.state in productive),
    )
    return RationalRelation(trimmed, relation.module(), algebra=relation.algebra)

union

Add the weight of the operands at each tuple of words.

The operands have the same ordered tape types and scalar semiring. Their disjoint state sets preserve each original path as a separate occurrence. Construction is linear in the topology records, apart from compiling the ordinary label indexes.

Source code in src/quivers/core/relations/expressions.py
def union(left: RationalRelation, right: RationalRelation) -> RationalRelation:
    """Add the weight of the operands at each tuple of words.

    The operands have the same ordered tape types and scalar semiring.
    Their disjoint state sets preserve each original path as a separate
    occurrence. Construction is linear in the topology records, apart
    from compiling the ordinary label indexes.
    """
    return _binary_expression(left, right, serial=False)