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
¶
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:
|
codomain
|
Target object.
TYPE:
|
algebra
|
The enrichment algebra. Defaults to PRODUCT_FUZZY.
TYPE:
|
Source code in src/quivers/core/morphisms.py
tensor_shape
property
¶
Expected shape for a morphism with a finite tensor.
dagger
property
¶
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 |
__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:
|
| RETURNS | DESCRIPTION |
|---|---|
ComposedMorphism
|
The composed morphism. |
Source code in src/quivers/core/morphisms.py
__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:
|
| RETURNS | DESCRIPTION |
|---|---|
ProductMorphism
|
The product morphism. |
Source code in src/quivers/core/morphisms.py
change_base
¶
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
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TransformedMorphism
|
A morphism over |
Source code in src/quivers/core/morphisms.py
refactor
¶
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
TYPE:
|
codomain
|
New codomain. Same numel constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ObservedMorphism
|
The reshape of |
Source code in src/quivers/core/morphisms.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
MarginalizedMorphism
|
The marginalized morphism. |
Source code in src/quivers/core/morphisms.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
ObservedMorphism
|
Morphism |
Source code in src/quivers/core/morphisms.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | |
FiniteMorphism
¶
Bases: Morphism
Morphism with a finite tensor in the carrier of its algebra.
Source code in src/quivers/core/morphisms.py
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:
|
transform
|
Pure function applied to |
domain
|
Target domain (may differ from
TYPE:
|
codomain
|
Target codomain.
TYPE:
|
algebra
|
Target algebra. Defaults to the source's algebra.
TYPE:
|
Source code in src/quivers/core/morphisms.py
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:
|
codomain
|
Target object.
TYPE:
|
data
|
Fixed tensor of shape (*domain.shape, *codomain.shape).
TYPE:
|
algebra
|
The enrichment algebra. Defaults to PRODUCT_FUZZY.
TYPE:
|
Source code in src/quivers/core/morphisms.py
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:
|
codomain
|
Target object.
TYPE:
|
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:
|
algebra
|
The enrichment algebra. Defaults to PRODUCT_FUZZY.
TYPE:
|
Source code in src/quivers/core/morphisms.py
ComposedMorphism
¶
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:
|
right
|
Right morphism (applied second).
TYPE:
|
Source code in src/quivers/core/morphisms.py
ProductMorphism
¶
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:
|
right
|
Right morphism.
TYPE:
|
Source code in src/quivers/core/morphisms.py
MarginalizedMorphism
¶
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:
|
sets_to_marginalize
|
Codomain components to marginalize over.
TYPE:
|
Source code in src/quivers/core/morphisms.py
FunctorMorphism
¶
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:
|
inner
|
The original morphism being mapped.
TYPE:
|
domain
|
The image of the inner morphism's domain under the functor.
TYPE:
|
codomain
|
The image of the inner morphism's codomain under the functor.
TYPE:
|
Source code in src/quivers/core/morphisms.py
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:
|
n
|
Initial number of repetitions (default 1). Can be changed
later via the
TYPE:
|
| 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
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
TYPE:
|
direction
|
Which factor is kept as the domain.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
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
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
TYPE:
|
direction
|
Where the first codomain factor is placed in the new domain:
last (
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/quivers/core/morphisms.py
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:
|
codomain
|
Target object.
TYPE:
|
init_scale
|
Initialization scale for unconstrained parameters.
TYPE:
|
algebra
|
The enrichment algebra. Defaults to PRODUCT_FUZZY.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LatentMorphism
|
A learnable morphism. |
Source code in src/quivers/core/morphisms.py
observed
¶
observed(domain: SetObject, codomain: SetObject, data: Tensor, algebra: Algebra | None = None) -> ObservedMorphism
Create an observed (fixed) morphism.
| PARAMETER | DESCRIPTION |
|---|---|
domain
|
Source object.
TYPE:
|
codomain
|
Target object.
TYPE:
|
data
|
Fixed tensor.
TYPE:
|
algebra
|
The enrichment algebra. Defaults to PRODUCT_FUZZY.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ObservedMorphism
|
A fixed morphism. |
Source code in src/quivers/core/morphisms.py
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:
|
algebra
|
The enrichment algebra. Defaults to PRODUCT_FUZZY.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ObservedMorphism
|
The identity morphism. |
Source code in src/quivers/core/morphisms.py
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:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Module
|
A module whose parameters / buffers are exactly the
morphism's, suitable for |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
|
Source code in src/quivers/core/morphisms.py
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 | |
extract_morphism
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Morphism or None
|
The wrapped morphism, or |
Source code in src/quivers/core/morphisms.py
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:
|
algebra
|
Override the default (ProductFuzzyAlgebra) algebra.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ObservedMorphism
|
Morphism |
Source code in src/quivers/core/morphisms.py
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
TYPE:
|
algebra
|
Override the default (ProductFuzzyAlgebra) algebra.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ObservedMorphism
|
Morphism |
Source code in src/quivers/core/morphisms.py
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
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
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
¶
An arc with epsilon on a tape consumes no symbol on that tape.
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:
|
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. |
algebra
|
The scalar algebra for path multiplication and addition. Defaults to real weights. |
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
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:
|
max_states
|
Limit on visited state and offset configurations.
TYPE:
|
max_work
|
Limit on candidate arc examinations, including rejected matches.
TYPE:
|
max_closure_size
|
Maximum order of each local star matrix, including auxiliary vertices for parallel arcs. None requires an acyclic productive graph.
TYPE:
|
| 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
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
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
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:
|
max_entries
|
Maximum number of tensor entries, checked before allocation.
TYPE:
|
max_states
|
Total product states that may be visited across the bounded table.
TYPE:
|
max_work
|
Total candidate arc examinations across the bounded table.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteRelationRestriction
|
A differentiable view over the bounded string carriers. |
Source code in src/quivers/core/relations/__init__.py
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.
RegularStringBelief
dataclass
¶
RegularStringBelief(relation: RationalRelation, log_normalizer: Tensor, max_states: int, max_work: int)
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
¶
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
¶
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:
|
words
|
One word per tape in tape order.
TYPE:
|
max_states
|
Limit on visited state and offset configurations.
TYPE:
|
max_work
|
Limit on candidate arc examinations.
TYPE:
|
max_closure_size
|
Maximum order of each local star matrix. None requires an acyclic productive graph.
TYPE:
|
Source code in src/quivers/core/relations/__init__.py
max_path_length
property
¶
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
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
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
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
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
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
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
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
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:
|
initial_costs
|
Optional fixed float64 scalar costs in the original occurrence order, on the weight device.
TYPE:
|
arc_costs
|
Optional fixed float64 scalar costs in the original occurrence order, on the weight device.
TYPE:
|
final_costs
|
Optional fixed float64 scalar costs in the original occurrence order, on the weight device.
TYPE:
|
| 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
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:
|
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:
|
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:
|
allow_cyclic
|
Use the marked-occurrence evaluator for a productive cycle. The query must also have an explicit closure size limit.
TYPE:
|
| 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
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
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
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
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
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
log_prob
¶
Return the log probability of the supplied output word tuple.
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
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:
|
output_tape
|
The type of output words.
TYPE:
|
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:
|
max_insertions
|
Maximum consecutive insertions. A consuming edit resets the count. The same bound applies at the end of the input.
TYPE:
|
Source code in src/quivers/core/relations/contextual_edit.py
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
¶
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
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
forward
¶
Return one alignment-marginal log probability per input-output pair.
Source code in src/quivers/core/relations/contextual_edit.py
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:
|
input_words
|
A nonempty batch of fixed input words.
TYPE:
|
output_words
|
One observed output word per input word.
TYPE:
|
max_states
|
Maximum total observation configurations across the batch. Global normalization includes the padded all-output suffix positions.
TYPE:
|
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:
|
normalization
|
Normalize each action row, or normalize the sum of raw path scores over all outputs for each input. Global normalization uses binary64.
TYPE:
|
Source code in src/quivers/core/relations/contextual_edit.py
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
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
¶
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:
|
max_lengths
|
Inclusive bounds for tape lengths, in tape order.
TYPE:
|
max_entries
|
Maximum number of entries in the resulting tensor.
TYPE:
|
max_states
|
Total product states visited across the bounded table.
TYPE:
|
max_work
|
Total candidate arc examinations across the bounded table.
TYPE:
|
Source code in src/quivers/core/relations/__init__.py
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
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
supports
property
¶
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
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
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
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 | |
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
¶
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
¶
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
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
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
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
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:
|
features
|
Distinct, nonempty n-grams in coefficient order. Symbols are integers from the base tape's alphabet.
TYPE:
|
max_states
|
Maximum product states reached from initial marks.
TYPE:
|
max_work
|
Maximum trie and failure-link work, original transition examinations, and feature emissions in the reached product.
TYPE:
|
Source code in src/quivers/core/relations/ngram_message.py
features
property
¶
Active feature identities in coefficient order.
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
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
¶
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:
|
tangent
|
The finite directional action, if available.
TYPE:
|
missing
|
The reason that the direction has no finite action, if any.
TYPE:
|
PathStatistics
dataclass
¶
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.
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
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
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
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:
|
words
|
Distinct candidate words on that relation's tape.
TYPE:
|
max_states
|
State limit for each construction and query.
TYPE:
|
max_work
|
Work limit for each construction and query.
TYPE:
|
max_closure_size
|
Maximum productive local closure size, if admitted.
TYPE:
|
Source code in src/quivers/core/relations/messages.py
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:
|
| 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
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
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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable
|
A callable returning the word's normalized log probability. |
Source code in src/quivers/core/relations/graph.py
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
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
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
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
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
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:
|
failures
|
The weighted fallback at each state, with at most one per state.
TYPE:
|
max_states
|
Maximum states reached in the combined transition graph.
TYPE:
|
max_work
|
Maximum examined reachable base edges and persistent sum-tree node updates.
TYPE:
|
| 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
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | |
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:
|
inputs
|
One fixed word per input tape in tape order.
TYPE:
|
candidates
|
Word tuples for the output tapes. The first maximum wins ties.
TYPE:
|
max_states
|
Total reached configurations across the candidate queries.
TYPE:
|
max_work
|
Total examined transitions across the candidate queries.
TYPE:
|
| 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
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
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:
|
words
|
One observed word per original tape.
TYPE:
|
max_states
|
Fixed-word observation state and arc budgets.
TYPE:
|
max_work
|
Fixed-word observation state and arc budgets.
TYPE:
|
max_exact_bits
|
Maximum conservative integer bit bound per exact operation and number of conversions, arithmetic operations, or comparisons.
TYPE:
|
max_exact_work
|
Maximum conservative integer bit bound per exact operation and number of conversions, arithmetic operations, or comparisons.
TYPE:
|
max_closure_cells
|
Aggregate cell bound before constructing closure expansion or matrices.
TYPE:
|
max_closure_size
|
Maximum local star order. None requires an acyclic observation.
TYPE:
|
absolute_tolerance
|
Requested error bounds, each required if supplied. Relative error needs a positive lower bound or certified exact zero.
TYPE:
|
relative_tolerance
|
Requested error bounds, each required if supplied. Relative error needs a positive lower bound or certified exact zero.
TYPE:
|
| 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
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:
|
beam
|
The existing pruned schedule and its own convergence settings.
TYPE:
|
max_sweeps
|
The existing pruned schedule and its own convergence settings.
TYPE:
|
tolerance
|
The existing pruned schedule and its own convergence settings.
TYPE:
|
damping
|
The existing pruned schedule and its own convergence settings.
TYPE:
|
max_conditional_cells
|
Cumulative bound on local conditional entries.
TYPE:
|
max_exact_work
|
Bound exact arithmetic operations and unreduced intermediate bits.
TYPE:
|
max_exact_bits
|
Bound exact arithmetic operations and unreduced intermediate bits.
TYPE:
|
decimal_precision
|
Bounds for directed exponentiation of the actual emitted log scores.
TYPE:
|
max_decimal_exponent
|
Bounds for directed exponentiation of the actual emitted log scores.
TYPE:
|
max_decimal_work
|
Bounds for directed exponentiation of the actual emitted log scores.
TYPE:
|
| 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
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | |
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:
|
words
|
One observed word per original tape.
TYPE:
|
absolute_log_tolerance
|
The required nonnegative absolute error in log units.
TYPE:
|
max_states
|
Observation state and candidate arc limits.
TYPE:
|
max_work
|
Observation state and candidate arc limits.
TYPE:
|
max_closure_size
|
Local star order and aggregate cell limits, including auxiliaries.
TYPE:
|
max_closure_cells
|
Local star order and aggregate cell limits, including auxiliaries.
TYPE:
|
decimal_precision
|
Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact input conversions.
TYPE:
|
max_decimal_exponent
|
Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact input conversions.
TYPE:
|
max_decimal_work
|
Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact input conversions.
TYPE:
|
max_exact_bits
|
Bit and operation limits for the exact cyclic solves and error test.
TYPE:
|
max_exact_work
|
Bit and operation limits for the exact cyclic solves and error test.
TYPE:
|
| 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
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 | |
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:
|
input_words
|
Fixed words in the relation's input and output tape order.
TYPE:
|
output_words
|
Fixed words in the relation's input and output tape order.
TYPE:
|
absolute_log_tolerance
|
Nonnegative absolute error target in log units.
TYPE:
|
max_states
|
Per-observation state and candidate arc caps.
TYPE:
|
max_work
|
Per-observation state and candidate arc caps.
TYPE:
|
max_center_occurrences
|
Aggregate lifted occurrence and graph visit preflights.
TYPE:
|
max_dyadic_work
|
Aggregate lifted occurrence and graph visit preflights.
TYPE:
|
max_closure_size
|
Local numeric order and combined cell caps, including auxiliaries.
TYPE:
|
max_closure_cells
|
Local numeric order and combined cell caps, including auxiliaries.
TYPE:
|
decimal_precision
|
Directed precision, symmetric exponent bound and shared work cap.
TYPE:
|
max_decimal_exponent
|
Directed precision, symmetric exponent bound and shared work cap.
TYPE:
|
max_decimal_work
|
Directed precision, symmetric exponent bound and shared work cap.
TYPE:
|
max_exact_bits
|
Bit and work limits on the gauges, finite stars and value check.
TYPE:
|
max_exact_work
|
Bit and work limits on the gauges, finite stars and value check.
TYPE:
|
| 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
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |
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:
|
words
|
One observed word per original tape.
TYPE:
|
absolute_log_tolerance
|
The required nonnegative absolute error in log units.
TYPE:
|
max_states
|
Observation state and candidate arc budgets.
TYPE:
|
max_work
|
Observation state and candidate arc budgets.
TYPE:
|
decimal_precision
|
Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact binary64 conversions.
TYPE:
|
max_decimal_exponent
|
Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact binary64 conversions.
TYPE:
|
max_decimal_work
|
Decimal significant digits, symmetric adjusted exponent bound, and maximum primitive calls and exact binary64 conversions.
TYPE:
|
max_exact_bits
|
Bit and operation bounds for the final rational error test.
TYPE:
|
max_exact_work
|
Bit and operation bounds for the final rational error test.
TYPE:
|
| 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
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
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:
|
violations
|
A vector of nonnegative integers per original arc occurrence.
TYPE:
|
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:
|
max_states
|
Maximum reached states in the weighted product.
TYPE:
|
max_work
|
Maximum product states, original arc examinations and competitor configurations examined by the compilation.
TYPE:
|
| 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
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
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
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:
|
max_iterations
|
Positive limit on the number of dual iterations.
TYPE:
|
max_ngram_order
|
Positive maximum order of a newly selected distinguishing feature.
TYPE:
|
max_features
|
Maximum number of selected variable and feature pairs.
TYPE:
|
max_states
|
Maximum reached configurations per local decoding.
TYPE:
|
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:
|
step_size
|
Positive scale for the multiplier step.
TYPE:
|
absolute_gap
|
A nonnegative target for dual upper bound minus feasible score.
TYPE:
|
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:
|
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:
|
max_feature_work
|
Cumulative cap on adaptive windows, active prefix probes and direct count symbol visits, including witness verification.
TYPE:
|
max_feature_cells
|
Cap on charged storage for active feature symbols and the temporary buffers for feature selection and direct word counts.
TYPE:
|
| 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
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | |
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:
|
groups
|
Ordered singleton or paired groups partitioning original factor positions.
TYPE:
|
max_group_states
|
State and construction work limits for each filtered pair join.
TYPE:
|
max_group_work
|
State and construction work limits for each filtered pair join.
TYPE:
|
max_iterations
|
Iteration and adaptive-feature limits for the common dual search.
TYPE:
|
max_ngram_order
|
Iteration and adaptive-feature limits for the common dual search.
TYPE:
|
max_features
|
Iteration and adaptive-feature limits for the common dual search.
TYPE:
|
max_states
|
Local state and per-pass arc limits for each decode and verification.
TYPE:
|
max_work
|
Local state and per-pass arc limits for each decode and verification.
TYPE:
|
step_size
|
Positive scale for the multiplier step.
TYPE:
|
absolute_gap
|
Optional exact objective gap targets with the ordinary solver's meaning.
TYPE:
|
relative_gap
|
Optional exact objective gap targets with the ordinary solver's meaning.
TYPE:
|
step_schedule
|
The same centered update schedules as the ordinary solver.
TYPE:
|
max_feature_work
|
Cumulative feature work and charged storage limits for the common dual search, as in the singleton solver.
TYPE:
|
max_feature_cells
|
Cumulative feature work and charged storage limits for the common dual search, as in the singleton solver.
TYPE:
|
| 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
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
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
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
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
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
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:
|
likelihood
|
One float64 LogProb language on the same tape. The product with the base must have positive finite mass.
TYPE:
|
features
|
Candidate feature vocabulary in coefficient order.
TYPE:
|
penalty
|
Nonnegative finite coefficient on the sum of prefix norms. Zero uses the unpenalized forward-KL objective.
TYPE:
|
tolerance
|
Tolerance on the proximal gradient mapping's infinity norm.
TYPE:
|
max_iterations
|
Upper bound on accepted proximal gradient steps.
TYPE:
|
max_states
|
Reached state limit for each sparse relation and query.
TYPE:
|
max_work
|
Work limit for each sparse relation and query.
TYPE:
|
max_closure_size
|
Explicit component limit if the tilted likelihood has productive epsilon cycles.
TYPE:
|
optimizer
|
Convex proximal gradient with adaptive majorization tests or with the global feature-covariance step bound.
TYPE:
|
max_moment_evaluations
|
Cap on target, base and trial moment evaluations in this fit.
TYPE:
|
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:
|
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:
|
| 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
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 | |
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:
|
| 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
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:
|
max_states
|
Limit on the number of states in the positive productive support.
TYPE:
|
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:
|
| 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
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
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
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:
|
bases
|
One acyclic productive reference language per variable.
TYPE:
|
features
|
One finite candidate n-gram vocabulary per variable.
TYPE:
|
penalty
|
Nonnegative weight on the local n-gram prefix-group penalty.
TYPE:
|
max_sweeps
|
Maximum synchronous sweeps accepted by the outer solver.
TYPE:
|
max_states
|
Reached state limit for each relation product or query.
TYPE:
|
max_work
|
Work limit for each relation product or query.
TYPE:
|
max_closure_size
|
Bound for productive epsilon closure in tilted factors.
TYPE:
|
tolerance
|
Upper bound on a site's undamped change in log score, including its scale. None uses the full sweep budget.
TYPE:
|
damping
|
Fraction of the previous site retained in log-space damping.
TYPE:
|
projection_tolerance
|
Local proximal gradient tolerance.
TYPE:
|
projection_max_iterations
|
Maximum accepted iterations per local projection.
TYPE:
|
projection_optimizer
|
The local proximal optimizer and step policy.
TYPE:
|
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:
|
max_moment_evaluations
|
Total number of target, base and trial moment evaluations, across all attempted site fits and the final diagnostic pass.
TYPE:
|
max_prefix_group_cells
|
Maximum stored coefficient indices across prefix groups in one penalized site fit.
TYPE:
|
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:
|
| 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
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | |
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:
|
input_word
|
The input whose candidates compete.
TYPE:
|
violations
|
One vector of nonnegative integers per original arc occurrence. All vectors must have the same length.
TYPE:
|
max_states
|
Maximum reachable state and input position configurations.
TYPE:
|
max_work
|
Maximum arcs compatible with the fixed input that the planner examines.
TYPE:
|
| 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
trim
¶
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.
Source code in src/quivers/core/relations/transforms.py
union
¶
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.