Skip to content

Agenda-based Deduction

DeductionSystem is the agenda-based weighted deduction system that the DSL compiles a deduction to (Shieber et al., 1995; Goodman, 1999). It combines axioms, a rule system, a semiring, and an agenda schedule in a validated model. The agenda is the work list of items still to process: the system adds the axioms, applies rules to the items proved so far, and accumulates weights at their conclusions (Eisner et al., 2005). Calling the system returns a ChartView, a differentiable view of the chart, the weight of each proved item. Different schedules change the cost, and equality of final results requires the semiring laws and, when rules form cycles, convergence of the fixed-point iteration. Fitting, sampling, and the No-U-Turn Sampler (NUTS) wrapper are in the deduction package.

Construct records with keyword arguments and use with_ to update their fields. Updating a deduction retains its live parameter modules and attached loss registries. The modules mapping holds learned parameters under their parameter-name prefixes; item_signature and item_encoder describe structured items. An agenda result retains its chart and differentiable weights, and with_ attaches an encoder or loss without mutating the result record.

Finding rule instances

Each premise of each rule is filed under the form its pattern requires, its head and length, or among the premises any item may fill when its head is a wildcard. An item that arrives is matched only against the premises of its form, once each, and the bindings of each match become a tuple of that premise's relation. For each rule and the premise an arriving item fills, every other premise keeps a trie of its relation keyed in the order that binds the arriving premise's variables first, and the instances the item completes are found by Generic Join over those tries, which shares its intersection step with rule-body joins and the indexed chart. Over a run a rule's comparisons are within the AGM bound of its body, as on the indexed chart.

A run reports its work in AgendaResult.work: its pops, matches, trie accesses and recorded applications, and, through ReportsWork, the sums, dictionary accesses and comparisons of its chart and queue. A counter is measured only when every part that could contribute to it counted it.

Items, patterns, and bindings

Items, patterns, and bindings are plain tuples and dictionaries, and these aliases name their roles in the signatures below.

A* parsing uses a heuristic to prioritize unfinished analyses (Klein and Manning, 2003). Its correctness depends on the heuristic and search conditions. Program transformations can instead reduce the work required to evaluate a deduction system (Eisner and Blatz, 2007).

Viewing parsing as deduction separates inference rules from the algorithm that schedules them (Pereira and Warren, 1983; Klein and Manning, 2001). This supports analyses of weighted derivations (Knuth, 1977; Nederhof, 2003) and of the time needed to evaluate them (McAllester, 2002). Compiling the deduction rules into differentiable computations also connects parsing to parameter estimation (Eisner et al., 2005).

Stochastic morphisms: Markov kernels over finite sets.

This module provides the probabilistic layer for quivers, implementing the category FinStoch of finite sets and stochastic maps (Markov kernels). This is the Kleisli category of the Giry monad restricted to finite sets, where:

  • Objects are finite sets (same as the base category).
  • Morphisms A -> B are stochastic matrices: tensors of shape (|A|, |B|) whose rows sum to 1.
  • Composition is standard matrix multiplication.
  • Identity is the Kronecker delta.

The package also re-exports MarkovAlgebra and its singleton MARKOV from quivers.core.algebras, the algebra these morphisms compose under.

Submodules

morphisms : StochasticMorphism, CategoricalMorphism families : Discretized distribution families transforms : condition, mix, factor, normalize queries : prob, marginal_prob, expectation giry : GiryMonad, FinStoch categories : Category types including atoms, slashes, products, unit, modals semiring : Chart semiring abstractions (LogProb, Viterbi, Boolean, Counting) schema : Composable rule schemas (functors CategorySystem -> RuleSystem) rules : Rule systems and the CCG / Lambek presets span : Span-based CKY components (LexicalAxiom, BinarySpanDeduction, etc.) parsers, ccg, lambek : Chart parsers inside : The inside algorithm over a rule system agenda : The agenda-driven weighted-deduction engine indexed : Charts indexed on the argument positions rule joins look up joins : Worst-case optimal joins and variable elimination for rule bodies planning : Plans for queries over rule presentations forest : Packed forests of derivations and folds over them recursion : Linear cyclic systems solved through the algebra's closure tries : Tries of relations and the intersection step of Generic Join productions : A grammar's productions grouped by left-hand side effect_lifts : Effect-lifted rule schemas for deduction systems deduction : Abstract weighted deductive system framework and its operations stdlib : Pre-registered deduction systems

Item module-attribute

Item = tuple[Any, ...]

An item is a tuple of (constructor_name, *arguments).

The constructor name disambiguates item shapes; the remaining slots are the item's payload. Arguments may be other items (structural), strings (atoms), integers (positions / cardinals), or Wildcard placeholders in patterns.

Pattern module-attribute

Pattern = tuple[Any, ...] | Wildcard

A pattern is an item-shaped tuple with optional Wildcard positions, or a Wildcard matching the whole item. A tuple pattern matches an item if (a) the constructor name matches, (b) the arities match, (c) each non-wildcard slot is structurally equal to the corresponding item slot, and (d) all wildcards with the same name bind to equal values.

Bindings module-attribute

Bindings = dict[str, Any]

A bindings environment maps wildcard variable names to the values they captured during pattern-matching.

agenda

Agenda-based weighted-deduction engine.

A general framework for evaluating weighted deductive systems by agenda-driven semi-naïve enumeration. Subsumes CKY, Earley, Viterbi, A* parsing, Knuth's algorithm, semi-naïve Datalog evaluation, and bidirectional MLTT type-checking under one runtime, parameterized by an Item algebra, a list of arity-n InferenceRule hyperedges, a ChartSemiring, an Agenda data structure, a priority function, and a goal predicate.

The chart maps each item to its accumulated weight. A rule combines premise weights and contributes to its conclusion. On a complete lattice with a monotone rule operator, this has a least fixed-point interpretation. A finite acyclic system can be evaluated in dependency order; cyclic systems need additional convergence or termination assumptions.

The agenda chooses which pending deduction to examine next. Idempotent addition makes repeated identical contributions harmless, but does not alone prove termination or strategy independence. Correct scheduling must reach the required deductions and respect the selected aggregation and stopping rule.

References

Parsing as deduction is developed in Pereira and Warren (1983); Shieber et al. (1995). Weighted interpretations are developed in Goodman (1999), and the hypergraph perspective in Klein and Manning (2001). Priority methods are treated in Knuth (1977); Nederhof (2003); Klein and Manning (2003). For weighted dynamic programs, complexity analysis, and program transformations, see Eisner et al. (2005); McAllester (2002); Eisner and Blatz (2007).

COMPONENT_FIELDS module-attribute

COMPONENT_FIELDS: tuple[WorkField, ...] = measuring({WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.HASH_OPERATIONS, WorkField.KEY_COMPARISONS})

The counters a chart or a queue may contribute to a run's report.

RuleCallback

RuleCallback = Callable[[str, list[tuple[Item, Tensor]], Item, Tensor], None]

A hook called once per rule application with its name, antecedents (each with its chart weight), conclusion, and contribution.

Form

Form = tuple[HeldValue, int]

The head and length of a tuple item or pattern.

Wildcard didactic-model

Wildcard(*, name: str)

Bases: Model

Pattern-position wildcard.

A wildcard matches any value in the corresponding slot and binds it to name for use in the conclusion. Two wildcards with the same name in a single rule's premise list must bind to equal values (variable-sharing).

InferenceRule didactic-model

InferenceRule(*, name: str, premises: tuple[tuple[HeldValue, ...] | Wildcard, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), conclusion: tuple[HeldValue, ...] | Wildcard = field(opaque=True, extras=OPAQUE_BY_VALUE), weight_fn: Callable[[Bindings, tuple[Tensor, ...], ChartSemiring], Tensor] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), side_condition: Callable[[Bindings], bool] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), canonical: Callable[[Item], Item] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

A weighted inference rule, that is, an arity-n hyperedge.

PARAMETER DESCRIPTION
name

Rule identifier (used for diagnostics and provenance).

TYPE: str

premises

Patterns the rule's antecedents must match.

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

conclusion

Pattern of the item the rule produces. Wildcards must appear in the premises (so they are bound by the time the conclusion is constructed).

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

weight_fn

Function (bindings, premise_weights, semiring) -> Weight producing the conclusion's weight from the matched premises. Defaults to the semiring product of premise weights (the standard semiring-parsing aggregation).

TYPE: Callable DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

side_condition

Predicate bindings -> bool. The rule fires only when this returns True. Used for guards like adjacency i < k < j in CKY-style rules.

TYPE: Callable DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

canonical

Function item -> item putting an instantiated conclusion in the chart's canonical form. A rule whose conclusion introduces a binder over matched terms renames bound variables to their levels, so alpha-equivalent conclusions are one item.

TYPE: Callable DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

ReportsWork

Bases: Protocol

A chart or agenda queue that reports the work it has done.

The counts cover everything since the component was made; a run takes the difference across it. The counters it does not return are not measured, and a component that does not implement this leaves all its work unmeasured in the run's report: a declared absence, not a count of zero.

work_counts

work_counts() -> Mapping[WorkField, int]

The work done since the component was made.

RETURNS DESCRIPTION
Mapping of WorkField to int

A count for each counter it measures, of those in COMPONENT_FIELDS.

Source code in src/quivers/stochastic/agenda.py
def work_counts(self) -> Mapping[WorkField, int]:
    """The work done since the component was made.

    Returns
    -------
    Mapping of WorkField to int
        A count for each counter it measures, of those in
        `COMPONENT_FIELDS`.
    """
    ...

Chart

Bases: ABC

A finite map from derived items to their weights in a semiring K.

A chart assigns each item it holds a weight in the semiring's carrier; an item it does not hold has the semiring's zero. A completed chart solves the deduction system's equations value(c) = axiom(c) ⊕ ⨁_{applications e → c} ⊗_j value(a_j); the agenda engine fills it bottom-up.

Concrete subclasses choose a storage strategy: dense tensor-indexed (for CKY-style spans), sparse hash-indexed (for Datalog atoms), or term-structural (for MLTT judgments).

lookup abstractmethod

lookup(pattern: Pattern, bindings: Bindings | None = None) -> Iterable[tuple[Item, Tensor]]

Enumerate the (item, weight) pairs that match a pattern under bindings.

PARAMETER DESCRIPTION
pattern

The pattern to match stored items against.

TYPE: Pattern

bindings

Values of some of the pattern's wildcards; an item matches when it matches the pattern with those wildcards fixed.

TYPE: Bindings or None DEFAULT: None

RETURNS DESCRIPTION
Iterable of (Item, torch.Tensor)

The matching items with their weights.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def lookup(
    self, pattern: Pattern, bindings: Bindings | None = None
) -> Iterable[tuple[Item, torch.Tensor]]:
    """Enumerate the (item, weight) pairs that match a pattern under bindings.

    Parameters
    ----------
    pattern : Pattern
        The pattern to match stored items against.
    bindings : Bindings or None
        Values of some of the pattern's wildcards; an item matches
        when it matches the pattern with those wildcards fixed.

    Returns
    -------
    Iterable of (Item, torch.Tensor)
        The matching items with their weights.
    """
    ...

insert_or_aggregate abstractmethod

insert_or_aggregate(item: Item, weight: Tensor, semiring: ChartSemiring) -> bool

Insert or aggregate an item's weight.

PARAMETER DESCRIPTION
item

The item to store.

TYPE: Item

weight

The weight to insert, or to aggregate with the stored weight under semiring.plus.

TYPE: Tensor

semiring

The semiring whose plus aggregates weights.

TYPE: ChartSemiring

RETURNS DESCRIPTION
bool

True if the item's stored weight changed (so it should be re-enqueued for downstream firings); False if the weight was unchanged (the inference was redundant under the semiring's idempotent join).

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def insert_or_aggregate(
    self,
    item: Item,
    weight: torch.Tensor,
    semiring: ChartSemiring,
) -> bool:
    """Insert or aggregate an item's weight.

    Parameters
    ----------
    item : Item
        The item to store.
    weight : torch.Tensor
        The weight to insert, or to aggregate with the stored
        weight under ``semiring.plus``.
    semiring : ChartSemiring
        The semiring whose ``plus`` aggregates weights.

    Returns
    -------
    bool
        ``True`` if the item's stored weight changed (so it
        should be re-enqueued for downstream firings);
        ``False`` if the weight was unchanged (the inference was
        redundant under the semiring's idempotent join).
    """
    ...

propagated

propagated(before: Tensor, item: Item, weight: Tensor, semiring: ChartSemiring) -> Tensor

The increment of an update that its consequences take.

PARAMETER DESCRIPTION
before

The item's weight before the update.

TYPE: Tensor

item

The item, whose stored weight the update changed.

TYPE: Item

weight

The increment.

TYPE: Tensor

semiring

The semiring.

TYPE: ChartSemiring

RETURNS DESCRIPTION
Tensor

The increment itself.

Source code in src/quivers/stochastic/agenda.py
def propagated(
    self,
    before: torch.Tensor,
    item: Item,
    weight: torch.Tensor,
    semiring: ChartSemiring,
) -> torch.Tensor:
    """The increment of an update that its consequences take.

    Parameters
    ----------
    before : torch.Tensor
        The item's weight before the update.
    item : Item
        The item, whose stored weight the update changed.
    weight : torch.Tensor
        The increment.
    semiring : ChartSemiring
        The semiring.

    Returns
    -------
    torch.Tensor
        The increment itself.
    """
    del before, item, semiring
    return weight

get abstractmethod

get(item: Item) -> Tensor | None

Return the chart's weight at an item, or None if absent.

PARAMETER DESCRIPTION
item

The item to look up.

TYPE: Item

RETURNS DESCRIPTION
Tensor or None

The stored weight, or None if the item is absent.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def get(self, item: Item) -> torch.Tensor | None:
    """Return the chart's weight at an item, or ``None`` if absent.

    Parameters
    ----------
    item : Item
        The item to look up.

    Returns
    -------
    torch.Tensor or None
        The stored weight, or ``None`` if the item is absent.
    """
    ...

items abstractmethod

items() -> Iterable[tuple[Item, Tensor]]

Enumerate all (item, weight) pairs in the chart.

RETURNS DESCRIPTION
Iterable of (Item, torch.Tensor)

Every stored item with its weight.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def items(self) -> Iterable[tuple[Item, torch.Tensor]]:
    """Enumerate all (item, weight) pairs in the chart.

    Returns
    -------
    Iterable of (Item, torch.Tensor)
        Every stored item with its weight.
    """
    ...

HashChart

HashChart(tolerance: float = 0.0)

Bases: Chart

Dictionary-backed chart for arbitrary item algebras.

Stores items as keys in a Python dict, with indexes of the items of each length keyed on the positions a lookup finds bound. Suitable for Datalog atoms, MLTT judgments, and any deduction whose items don't have a dense integer encoding. A lookup costs its key and the items that agree with it on the bound positions, each matched against the whole pattern, so bindings pushed into it select the candidates.

Weights are stored as torch.Tensor values; autograd flows through insert_or_aggregate's semiring.plus(torch.stack([…])) reduction, so the chart's final values carry gradients with respect to any requires_grad=True rule-weight parameters that fed into the agenda.

PARAMETER DESCRIPTION
tolerance

The smallest change in an item's weight that counts as an update; 0.0 treats any change as an update.

TYPE: float DEFAULT: 0.0

Source code in src/quivers/stochastic/agenda.py
def __init__(self, tolerance: float = 0.0) -> None:
    self._store: dict[Item, torch.Tensor] = {}
    self._tolerance: float = float(tolerance)
    self._work = _ComponentWork()
    self._indexes: dict[
        tuple[int, tuple[int, ...]], dict[tuple[HeldValue, ...], list[Item]]
    ] = {}

work_counts

work_counts() -> Mapping[WorkField, int]

The chart's work since it was made.

RETURNS DESCRIPTION
Mapping of WorkField to int

Sums of aggregation, one per element merged; dictionary accesses; the items a lookup matched against its pattern; and no products.

Source code in src/quivers/stochastic/agenda.py
def work_counts(self) -> Mapping[WorkField, int]:
    """The chart's work since it was made.

    Returns
    -------
    Mapping of WorkField to int
        Sums of aggregation, one per element merged; dictionary
        accesses; the items a lookup matched against its pattern; and
        no products.
    """
    return self._work.counts()

lookup

lookup(pattern: Pattern, bindings: Bindings | None = None) -> Iterable[tuple[Item, Tensor]]

The stored items that match a pattern under bindings, by a keyed index.

A tuple pattern of length L is looked up in the index of the items of length L keyed on the positions whose pattern is ground once the bindings are substituted; with no such position the key is empty and the index holds every item of that length. Indexes are built on first use and kept up to date as items arrive, so a lookup costs its key and the items that agree with it, each then matched against the whole pattern.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: Pattern

bindings

Values of some of its wildcards.

TYPE: Bindings or None DEFAULT: None

RETURNS DESCRIPTION
Iterable of (Item, torch.Tensor)

The matching items with their weights.

Source code in src/quivers/stochastic/agenda.py
def lookup(
    self, pattern: Pattern, bindings: Bindings | None = None
) -> Iterable[tuple[Item, torch.Tensor]]:
    """The stored items that match a pattern under bindings, by a keyed index.

    A tuple pattern of length ``L`` is looked up in the index of the
    items of length ``L`` keyed on the positions whose pattern is
    ground once the bindings are substituted; with no such position
    the key is empty and the index holds every item of that length.
    Indexes are built on first use and kept up to date as items
    arrive, so a lookup costs its key and the items that agree with
    it, each then matched against the whole pattern.

    Parameters
    ----------
    pattern : Pattern
        The pattern.
    bindings : Bindings or None
        Values of some of its wildcards.

    Returns
    -------
    Iterable of (Item, torch.Tensor)
        The matching items with their weights.
    """
    fixed = {} if bindings is None else bindings
    if isinstance(pattern, Wildcard) and pattern.name in fixed:
        self._work.hashes += 1
        value = fixed[pattern.name]
        stored = self._store.get(value)
        return [] if stored is None else [(value, stored)]
    if not isinstance(pattern, tuple):
        candidates: Iterable[Item] = list(self._store)
    else:
        positions = tuple(
            index
            for index, element in enumerate(pattern)
            if _ground(element, fixed)
        )
        key = tuple(instantiate(pattern[index], fixed) for index in positions)
        self._work.hashes += 1
        candidates = self._index(len(pattern), positions).get(key, [])
    found: list[tuple[Item, torch.Tensor]] = []
    for item in candidates:
        self._work.comparisons += 1
        if match(pattern, item, fixed) is not None:
            found.append((item, self._store[item]))
    return found

insert_or_aggregate

insert_or_aggregate(item: Item, weight: Tensor, semiring: ChartSemiring) -> bool

Aggregate weight into the chart at item.

For non-idempotent semirings (LogProb, Counting, Inside) with cyclic rule graphs, every re-derivation of an item via a new path increases its weight via semiring.plus, even when the item itself is already in the chart. With an unconstrained cycle weight, this sequence is unbounded: either the cycle is contractive (cycle log-weight :math:< 0), in which case the chart's weight converges to a finite Kleene-star limit; or the cycle is non-contractive (:math:\ge 0), in which case the chart total is :math:+ \infty and the model is mathematically ill-posed.

The chart makes this distinction observable by terminating the agenda when the per-item update falls below the tolerance. The default tolerance 0.0 treats any change as an update; positive tolerances expose convergent cyclic fixed points while still routing divergent systems through the agenda's max_iterations safety net.

PARAMETER DESCRIPTION
item

The item to store.

TYPE: Item

weight

The weight to insert or aggregate.

TYPE: Tensor

semiring

The semiring whose plus aggregates weights.

TYPE: ChartSemiring

RETURNS DESCRIPTION
bool

True if the stored weight changed by more than the tolerance, the item is new, or the update is the zero and carries a derivative in an algebra that is not declared idempotent: such an update leaves the number unchanged and moves its derivative, which its consequences need.

Source code in src/quivers/stochastic/agenda.py
def insert_or_aggregate(
    self,
    item: Item,
    weight: torch.Tensor,
    semiring: ChartSemiring,
) -> bool:
    """Aggregate ``weight`` into the chart at ``item``.

    For non-idempotent semirings (LogProb, Counting, Inside)
    with cyclic rule graphs, every re-derivation of an item via
    a new path increases its weight via `semiring.plus`,
    even when the item itself is already in the chart. With an
    unconstrained cycle weight, this sequence is unbounded:
    either the cycle is contractive (cycle log-weight :math:`<
    0`), in which case the chart's weight converges to a
    finite Kleene-star limit; or the cycle is non-contractive
    (:math:`\\ge 0`), in which case the chart total is :math:`+
    \\infty` and the model is mathematically ill-posed.

    The chart makes this distinction observable by terminating
    the agenda when the per-item update falls below the
    tolerance. The default tolerance ``0.0`` treats any change
    as an update; positive tolerances expose convergent cyclic
    fixed points while still routing divergent systems through
    the agenda's ``max_iterations`` safety net.

    Parameters
    ----------
    item : Item
        The item to store.
    weight : torch.Tensor
        The weight to insert or aggregate.
    semiring : ChartSemiring
        The semiring whose ``plus`` aggregates weights.

    Returns
    -------
    bool
        ``True`` if the stored weight changed by more than the
        tolerance, the item is new, or the update is the zero and
        carries a derivative in an algebra that is not declared
        idempotent: such an update leaves the number unchanged and
        moves its derivative, which its consequences need.
    """
    self._work.hashes += 1
    if item not in self._store:
        self._store[item] = weight
        self._work.hashes += 1
        self._indexed(item)
        return True
    existing = self._store[item]
    stacked = torch.stack([existing, weight])
    merged = semiring.plus(stacked, dim=0)
    self._work.sums += merged.numel()
    self._work.hashes += 2
    self._store[item] = merged
    return anywhere(self._changed(existing, merged) | _carries(weight, semiring))

propagated

propagated(before: Tensor, item: Item, weight: Tensor, semiring: ChartSemiring) -> Tensor

The increment of an update that its consequences take.

PARAMETER DESCRIPTION
before

The item's weight before the update.

TYPE: Tensor

item

The item.

TYPE: Item

weight

The increment.

TYPE: Tensor

semiring

The semiring, whose zero is the increment of no change.

TYPE: ChartSemiring

RETURNS DESCRIPTION
Tensor

The increment. Over many parameter values, it is zero at the values where the stored weight did not change, whose agenda would not have gone on from here.

Source code in src/quivers/stochastic/agenda.py
def propagated(
    self,
    before: torch.Tensor,
    item: Item,
    weight: torch.Tensor,
    semiring: ChartSemiring,
) -> torch.Tensor:
    """The increment of an update that its consequences take.

    Parameters
    ----------
    before : torch.Tensor
        The item's weight before the update.
    item : Item
        The item.
    weight : torch.Tensor
        The increment.
    semiring : ChartSemiring
        The semiring, whose zero is the increment of no change.

    Returns
    -------
    torch.Tensor
        The increment. Over many parameter values, it is zero at the
        values where the stored weight did not change, whose agenda
        would not have gone on from here.
    """
    self._work.hashes += 1
    changed = self._changed(before, self._store[item]) | _carries(weight, semiring)
    if not depends_on_position(changed):
        return weight
    return torch.where(changed, weight, semiring.zero_like((), weight))

get

get(item: Item) -> Tensor | None

Return the stored weight at an item.

PARAMETER DESCRIPTION
item

The item to look up.

TYPE: Item

RETURNS DESCRIPTION
Tensor or None

The stored weight, or None if the item is absent.

Source code in src/quivers/stochastic/agenda.py
def get(self, item: Item) -> torch.Tensor | None:
    """Return the stored weight at an item.

    Parameters
    ----------
    item : Item
        The item to look up.

    Returns
    -------
    torch.Tensor or None
        The stored weight, or ``None`` if the item is absent.
    """
    self._work.hashes += 1
    return self._store.get(item)

items

items() -> Iterable[tuple[Item, Tensor]]

Enumerate all stored (item, weight) pairs.

RETURNS DESCRIPTION
Iterable of (Item, torch.Tensor)

Every stored item with its weight.

Source code in src/quivers/stochastic/agenda.py
def items(self) -> Iterable[tuple[Item, torch.Tensor]]:
    """Enumerate all stored (item, weight) pairs.

    Returns
    -------
    Iterable of (Item, torch.Tensor)
        Every stored item with its weight.
    """
    return self._store.items()

ChartReveal

Bases: ABC

What the items and applications of a run stand for.

A system may run a deduction through an encoding with items and rules of its own, which stand for the deduction's items and applications: an item may stand for several of the deduction's items at once, an item may only mark one of the deduction's items for a few rules, and a rule may stand for another rule applied to particular premises. The reveal is the one map from the encoding back to the deduction, and DeductionSystem.run applies it at the one point where a run's items leave the engine: the result, and each application a rule-attached loss reads. Nothing outside the engine sees the encoding.

item abstractmethod

item(item: Item, weight: Tensor, semiring: ChartSemiring) -> tuple[tuple[Item, Tensor], ...]

The deduction's items a chart item stands for, with their weights.

PARAMETER DESCRIPTION
item

An item of the run.

TYPE: Item

weight

Its weight in the run.

TYPE: Tensor

semiring

The run's semiring.

TYPE: ChartSemiring

RETURNS DESCRIPTION
tuple[tuple[Item, Tensor], ...]

Each item of the deduction the run's item contributes to, with the weight it contributes; empty for an item whose weight another item of the run carries.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def item(
    self, item: Item, weight: torch.Tensor, semiring: ChartSemiring
) -> tuple[tuple[Item, torch.Tensor], ...]:
    """The deduction's items a chart item stands for, with their weights.

    Parameters
    ----------
    item : Item
        An item of the run.
    weight : torch.Tensor
        Its weight in the run.
    semiring : ChartSemiring
        The run's semiring.

    Returns
    -------
    tuple[tuple[Item, torch.Tensor], ...]
        Each item of the deduction the run's item contributes to, with
        the weight it contributes; empty for an item whose weight
        another item of the run carries.
    """
    ...

axiom abstractmethod

axiom(item: Item) -> tuple[Item, ...]

The deduction's axiom occurrences an axiom occurrence of the run stands for.

PARAMETER DESCRIPTION
item

The item of an axiom occurrence of the run.

TYPE: Item

RETURNS DESCRIPTION
tuple[Item, ...]

The items of the deduction's axiom occurrences it stands for.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def axiom(self, item: Item) -> tuple[Item, ...]:
    """The deduction's axiom occurrences an axiom occurrence of the run stands for.

    Parameters
    ----------
    item : Item
        The item of an axiom occurrence of the run.

    Returns
    -------
    tuple[Item, ...]
        The items of the deduction's axiom occurrences it stands for.
    """
    ...

application abstractmethod

application(rule: str, antecedents: Sequence[tuple[Item, Tensor]], conclusion: Item, semiring: ChartSemiring) -> tuple[str, tuple[tuple[Item, Tensor], ...], Item] | None

The deduction's application a rule application of the run stands for.

PARAMETER DESCRIPTION
rule

The applied rule.

TYPE: str

antecedents

Its antecedents with their weights, in premise order.

TYPE: Sequence[tuple[Item, Tensor]]

conclusion

Its conclusion.

TYPE: Item

semiring

The run's semiring.

TYPE: ChartSemiring

RETURNS DESCRIPTION
tuple[str, tuple[tuple[Item, Tensor], ...], Item] | None

The deduction's rule, its antecedents with their weights, and its conclusion; None for an application that is no step of the deduction, whose conclusion is an axiom occurrence.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def application(
    self,
    rule: str,
    antecedents: Sequence[tuple[Item, torch.Tensor]],
    conclusion: Item,
    semiring: ChartSemiring,
) -> tuple[str, tuple[tuple[Item, torch.Tensor], ...], Item] | None:
    """The deduction's application a rule application of the run stands for.

    Parameters
    ----------
    rule : str
        The applied rule.
    antecedents : Sequence[tuple[Item, torch.Tensor]]
        Its antecedents with their weights, in premise order.
    conclusion : Item
        Its conclusion.
    semiring : ChartSemiring
        The run's semiring.

    Returns
    -------
    tuple[str, tuple[tuple[Item, torch.Tensor], ...], Item] | None
        The deduction's rule, its antecedents with their weights, and
        its conclusion; ``None`` for an application that is no step of
        the deduction, whose conclusion is an axiom occurrence.
    """
    ...

result

result(result: AgendaResult, rules: Sequence[InferenceRule], goal: Callable[[Item], bool]) -> AgendaResult

A run's result, read through the reveal.

PARAMETER DESCRIPTION
result

The run's result.

TYPE: AgendaResult

rules

The system's rules; a revealed application is numbered by the first position of its rule.

TYPE: Sequence[InferenceRule]

goal

The run's goal predicate.

TYPE: Callable[[Item], bool]

RETURNS DESCRIPTION
AgendaResult

The result with the deduction's items, their weights, its applications, its axiom occurrences, and its goal items.

Source code in src/quivers/stochastic/agenda.py
def result(
    self,
    result: AgendaResult,
    rules: Sequence[InferenceRule],
    goal: Callable[[Item], bool],
) -> AgendaResult:
    """A run's result, read through the reveal.

    Parameters
    ----------
    result : AgendaResult
        The run's result.
    rules : Sequence[InferenceRule]
        The system's rules; a revealed application is numbered by the
        first position of its rule.
    goal : Callable[[Item], bool]
        The run's goal predicate.

    Returns
    -------
    AgendaResult
        The result with the deduction's items, their weights, its
        applications, its axiom occurrences, and its goal items.
    """
    semiring = result.semiring
    chart = HashChart()
    for item, weight in result.chart.items():
        for shown, contributed in self.item(item, weight, semiring):
            chart.insert_or_aggregate(shown, contributed, semiring)
    positions: dict[str, int] = {}
    for index, rule in enumerate(rules):
        positions.setdefault(rule.name, index)
    weights = dict(result.chart.items())
    applications: list[
        tuple[int, str, tuple[tuple[HeldValue, ...], ...], tuple[HeldValue, ...]]
    ] = []
    axioms = [
        shown
        for occurrence in result.axiom_occurrences
        for shown in self.axiom(occurrence)
    ]
    for _, name, antecedents, conclusion in result.applications:
        shown = self.application(
            name,
            tuple((antecedent, weights[antecedent]) for antecedent in antecedents),
            conclusion,
            semiring,
        )
        if shown is None:
            axioms.extend(self.axiom(conclusion))
            continue
        rule, revealed, concluded = shown
        applications.append(
            (positions[rule], rule, tuple(a for a, _ in revealed), concluded)
        )
    return result.with_(
        chart=chart,
        applications=applications,
        axiom_occurrences=axioms,
        goal_items=[(item, weight) for item, weight in chart.items() if goal(item)],
    )

ChartView

ChartView(result: 'AgendaResult')

A differentiable view onto a completed chart.

Wraps the Chart an agenda run produced, a map from derived items to their weights, and exposes lookups into it:

  • weight: the weight of one ground item, a differentiable torch.Tensor.
  • enumerate: the items matching a pattern, with their weights.
  • derivations: the rule applications that derive an item, the item's incoming hyperedges in the derivation hypergraph.
  • goal_weight: the semiring sum of the goal items' weights.

Gradients flow through these lookups because the stored tensors carry requires_grad from the rule and axiom weights.

PARAMETER DESCRIPTION
result

The agenda run to view.

TYPE: AgendaResult

Source code in src/quivers/stochastic/agenda.py
def __init__(self, result: "AgendaResult") -> None:
    self._result = result

chart property

chart: Chart

The underlying chart.

attached_loss property

attached_loss: Tensor | None

The sum of rule-attached and chart-attached loss values fired during this deduction's run, or None if no losses were declared at those sites.

semiring property

semiring: ChartSemiring

The semiring the chart was computed over.

goal_items property

goal_items: list[tuple[Item, Tensor]]

List of (item, weight) pairs matching the goal predicate.

weight

weight(item: Item) -> Tensor

Return the aggregated weight at a concrete item.

PARAMETER DESCRIPTION
item

A ground item.

TYPE: Item

RETURNS DESCRIPTION
Tensor

The item's differentiable weight.

RAISES DESCRIPTION
KeyError

If the item was never derived.

Source code in src/quivers/stochastic/agenda.py
def weight(self, item: Item) -> torch.Tensor:
    """Return the aggregated weight at a concrete ``item``.

    Parameters
    ----------
    item : Item
        A ground item.

    Returns
    -------
    torch.Tensor
        The item's differentiable weight.

    Raises
    ------
    KeyError
        If the item was never derived.
    """
    w = self._result.chart.get(item)
    if w is None:
        raise KeyError(f"item {item!r} not in chart")
    return w

try_weight

try_weight(item: Item, default: Tensor | None = None) -> Tensor

Return the weight at item, or a fallback if it is absent.

PARAMETER DESCRIPTION
item

A ground item.

TYPE: Item

default

The value to return for an absent item; None means the semiring's zero.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The item's weight, default, or the semiring's zero in the dtype and device of the run's weights.

Source code in src/quivers/stochastic/agenda.py
def try_weight(
    self,
    item: Item,
    default: torch.Tensor | None = None,
) -> torch.Tensor:
    """Return the weight at ``item``, or a fallback if it is absent.

    Parameters
    ----------
    item : Item
        A ground item.
    default : torch.Tensor or None
        The value to return for an absent item; ``None`` means
        the semiring's zero.

    Returns
    -------
    torch.Tensor
        The item's weight, ``default``, or the semiring's zero in the
        dtype and device of the run's weights.
    """
    w = self._result.chart.get(item)
    if w is not None:
        return w
    if default is not None:
        return default
    return self.semiring.zero_like((), self._result.like)

enumerate

enumerate(pattern: Pattern) -> list[tuple[Item, Tensor]]

Enumerate (item, weight) pairs matching pattern.

Wildcards in pattern (instances of Wildcard) match any slot value.

PARAMETER DESCRIPTION
pattern

The pattern to match.

TYPE: Pattern

RETURNS DESCRIPTION
list of (Item, torch.Tensor)

The matching items with their differentiable weights.

Source code in src/quivers/stochastic/agenda.py
def enumerate(self, pattern: Pattern) -> list[tuple[Item, torch.Tensor]]:
    """Enumerate (item, weight) pairs matching ``pattern``.

    Wildcards in ``pattern`` (instances of `Wildcard`)
    match any slot value.

    Parameters
    ----------
    pattern : Pattern
        The pattern to match.

    Returns
    -------
    list of (Item, torch.Tensor)
        The matching items with their differentiable weights.
    """
    return list(self._result.chart.lookup(pattern))

embedding

embedding(item: Item) -> Tensor

Return the vector embedding of item under the deduction's attached encoder.

Requires the originating DeductionSystem to carry an item_encoder field (set by the DSL compiler when the deduction's body declares encoder C). Items are converted to quivers.structural.Term form on the fly.

PARAMETER DESCRIPTION
item

The item to embed.

TYPE: Item

RETURNS DESCRIPTION
Tensor

The encoder's embedding of the item.

RAISES DESCRIPTION
RuntimeError

If the run carries no encoder.

Source code in src/quivers/stochastic/agenda.py
def embedding(self, item: Item) -> torch.Tensor:
    """Return the vector embedding of ``item`` under the deduction's
    attached encoder.

    Requires the originating `DeductionSystem` to carry an
    ``item_encoder`` field (set by the DSL compiler when
    the deduction's body declares ``encoder C``). Items are
    converted to [`quivers.structural.Term`][quivers.structural.Term] form on the fly.

    Parameters
    ----------
    item : Item
        The item to embed.

    Returns
    -------
    torch.Tensor
        The encoder's embedding of the item.

    Raises
    ------
    RuntimeError
        If the run carries no encoder.
    """
    encoder = getattr(self._result, "encoder", None)
    if encoder is None:
        raise RuntimeError(
            "chart has no attached encoder; declare "
            "`signature ... encoder ...` in the deduction block"
        )
    return encoder(item)

derivations

derivations(item: Item) -> list[tuple[int, str, tuple[Item, ...]]]

The rule applications that derive item.

These are the item's incoming hyperedges in the derivation hypergraph Klein and Manning (2001): each derivation of item is an axiom of it, or one of these applications together with a derivation of each antecedent.

PARAMETER DESCRIPTION
item

The item whose derivations to return.

TYPE: Item

RETURNS DESCRIPTION
list of (int, str, tuple of Item)

Each application's rule position, rule name and antecedent items, in premise order; empty when no rule derives item. The axiom occurrences of item are in AgendaResult.axiom_occurrences.

Source code in src/quivers/stochastic/agenda.py
def derivations(self, item: Item) -> list[tuple[int, str, tuple[Item, ...]]]:
    """The rule applications that derive ``item``.

    These are the item's incoming hyperedges in the derivation
    hypergraph [Klein and Manning (2001)](<https://aclanthology.org/W01-1812/>):
    each derivation of ``item`` is an axiom of it, or one of these
    applications together with a derivation of each antecedent.

    Parameters
    ----------
    item : Item
        The item whose derivations to return.

    Returns
    -------
    list of (int, str, tuple of Item)
        Each application's rule position, rule name and antecedent
        items, in premise order; empty when no rule derives ``item``.
        The axiom occurrences of ``item`` are in
        ``AgendaResult.axiom_occurrences``.
    """
    return [
        (index, rule_name, antecedents)
        for index, rule_name, antecedents, conclusion in self._result.applications
        if conclusion == item
    ]

goal_weight

goal_weight() -> Tensor

Aggregate weight over all goal items.

If a single goal item was identified, returns its weight directly; otherwise aggregates via the semiring's plus reduction (the standard parse-as-marginal computation).

RETURNS DESCRIPTION
Tensor

The aggregated goal weight, or the semiring's zero in the dtype and device of the run's weights when no goal item was derived.

Source code in src/quivers/stochastic/agenda.py
def goal_weight(self) -> torch.Tensor:
    """Aggregate weight over all goal items.

    If a single goal item was identified, returns its weight
    directly; otherwise aggregates via the semiring's
    ``plus`` reduction (the standard parse-as-marginal
    computation).

    Returns
    -------
    torch.Tensor
        The aggregated goal weight, or the semiring's zero in the
        dtype and device of the run's weights when no goal item was
        derived.
    """
    if not self._result.goal_items:
        return self.semiring.zero_like((), self._result.like)
    if len(self._result.goal_items) == 1:
        return self._result.goal_items[0][1]
    weights = torch.stack([w for _, w in self._result.goal_items])
    return self.semiring.plus(weights, dim=0)

CorpusChart

CorpusChart(charts: tuple[ChartView, ...], semiring: ChartSemiring)

The charts of a corpus of independent sentences.

PARAMETER DESCRIPTION
charts

One chart per sentence, in corpus order.

TYPE: tuple[ChartView, ...]

semiring

The semiring the charts were computed in.

TYPE: ChartSemiring

Source code in src/quivers/stochastic/agenda.py
def __init__(self, charts: tuple[ChartView, ...], semiring: ChartSemiring) -> None:
    self.charts = charts
    self.semiring = semiring

goal_weight

goal_weight() -> Tensor

The corpus's goal weight: the semiring product over sentences.

RETURNS DESCRIPTION
Tensor

Under LogProb, the sum of the sentences' log inside weights, the corpus's log-likelihood.

Source code in src/quivers/stochastic/agenda.py
def goal_weight(self) -> torch.Tensor:
    """The corpus's goal weight: the semiring product over sentences.

    Returns
    -------
    torch.Tensor
        Under ``LogProb``, the sum of the sentences' log inside
        weights, the corpus's log-likelihood.
    """
    total = self.charts[0].goal_weight()
    for chart in self.charts[1:]:
        total = self.semiring.times(total, chart.goal_weight())
    return total

Agenda

Bases: ABC

A queue of items pending further inference.

The agenda discipline (FIFO / LIFO / priority) determines evaluation order. Correctness requires an appropriate schedule and stopping rule; idempotent aggregation alone does not establish it. Semiring parsing Goodman (1999) and bottom-up complexity analysis McAllester (2002) explain the relevant background.

push abstractmethod

push(item: Item, weight: Tensor) -> None

Add an item and its weight to the agenda.

PARAMETER DESCRIPTION
item

The derived item.

TYPE: Item

weight

The weight contributed by this derivation.

TYPE: Tensor

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def push(self, item: Item, weight: torch.Tensor) -> None:
    """Add an item and its weight to the agenda.

    Parameters
    ----------
    item : Item
        The derived item.
    weight : torch.Tensor
        The weight contributed by this derivation.
    """

pop abstractmethod

pop() -> tuple[Item, Tensor]

Remove and return the next item under this discipline.

RETURNS DESCRIPTION
tuple of (Item, torch.Tensor)

The next item and its pending weight.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def pop(self) -> tuple[Item, torch.Tensor]:
    """Remove and return the next item under this discipline.

    Returns
    -------
    tuple of (Item, torch.Tensor)
        The next item and its pending weight.
    """

empty abstractmethod

empty() -> bool

Whether no items are pending.

RETURNS DESCRIPTION
bool

True when the agenda holds no items.

Source code in src/quivers/stochastic/agenda.py
@abstractmethod
def empty(self) -> bool:
    """Whether no items are pending.

    Returns
    -------
    bool
        ``True`` when the agenda holds no items.
    """

bind_semiring

bind_semiring(semiring: ChartSemiring) -> None

Give the agenda access to the engine's semiring.

run_agenda calls this once, before pushing the axioms. Disciplines that can exploit the binding override it; for instance, FIFOAgenda merges pending contributions to the same item via semiring.plus. The default ignores the binding.

PARAMETER DESCRIPTION
semiring

The engine's semiring.

TYPE: ChartSemiring

Source code in src/quivers/stochastic/agenda.py
def bind_semiring(self, semiring: ChartSemiring) -> None:
    """Give the agenda access to the engine's semiring.

    `run_agenda` calls this once, before pushing the axioms.
    Disciplines that can exploit the binding override it; for
    instance, `FIFOAgenda` merges pending contributions
    to the same item via ``semiring.plus``. The default ignores
    the binding.

    Parameters
    ----------
    semiring : ChartSemiring
        The engine's semiring.
    """

FIFOAgenda

FIFOAgenda()

Bases: Agenda

First-in-first-out agenda (semi-naïve Datalog discipline).

The agenda processes items in the order they were derived. Correct for any monotone semiring; the canonical choice for Datalog and Earley parsing.

Once a semiring is bound (bind_semiring, which the engine does on entry), a contribution pushed for an item that is already pending merges into that item's single queue entry via semiring.plus. Semiring distributivity makes the merge exact: firing a rule once on the merged contribution pushes the same total mass downstream as firing it once per contribution. Without merging, a cyclic rule graph re-enqueues every contribution separately, and the number of pending entries grows geometrically with derivation depth even when the weighted fixed point converges.

Source code in src/quivers/stochastic/agenda.py
def __init__(self) -> None:
    self._queue: deque[tuple[Item, torch.Tensor]] = deque()
    self._order: deque[Item] = deque()
    self._pending: dict[Item, torch.Tensor] = {}
    self._semiring: ChartSemiring | None = None
    self._work = _ComponentWork()

work_counts

work_counts() -> Mapping[WorkField, int]

The queue's work since it was made.

RETURNS DESCRIPTION
Mapping of WorkField to int

Sums merging pending contributions, one per element, and dictionary accesses; a queue in order compares and multiplies nothing.

Source code in src/quivers/stochastic/agenda.py
def work_counts(self) -> Mapping[WorkField, int]:
    """The queue's work since it was made.

    Returns
    -------
    Mapping of WorkField to int
        Sums merging pending contributions, one per element, and
        dictionary accesses; a queue in order compares and multiplies
        nothing.
    """
    return self._work.counts()

bind_semiring

bind_semiring(semiring: ChartSemiring) -> None

Bind the semiring that merges pending contributions.

PARAMETER DESCRIPTION
semiring

The engine's semiring.

TYPE: ChartSemiring

Source code in src/quivers/stochastic/agenda.py
def bind_semiring(self, semiring: ChartSemiring) -> None:
    """Bind the semiring that merges pending contributions.

    Parameters
    ----------
    semiring : ChartSemiring
        The engine's semiring.
    """
    self._semiring = semiring

push

push(item: Item, weight: Tensor) -> None

Add an item and its weight to the agenda.

PARAMETER DESCRIPTION
item

The derived item.

TYPE: Item

weight

The weight contributed by this derivation.

TYPE: Tensor

Source code in src/quivers/stochastic/agenda.py
def push(self, item: Item, weight: torch.Tensor) -> None:
    """Add an item and its weight to the agenda.

    Parameters
    ----------
    item : Item
        The derived item.
    weight : torch.Tensor
        The weight contributed by this derivation.
    """
    if self._semiring is None:
        self._queue.append((item, weight))
        return
    self._work.hashes += 1
    existing = self._pending.get(item)
    if existing is None:
        self._work.hashes += 1
        self._pending[item] = weight
        self._order.append(item)
        return
    stacked = torch.stack([existing, weight])
    merged = self._semiring.plus(stacked, dim=0)
    self._work.sums += merged.numel()
    self._work.hashes += 1
    self._pending[item] = merged

pop

pop() -> tuple[Item, Tensor]

Remove and return the next item under this discipline.

RETURNS DESCRIPTION
tuple of (Item, torch.Tensor)

The next item and its pending weight.

Source code in src/quivers/stochastic/agenda.py
def pop(self) -> tuple[Item, torch.Tensor]:
    """Remove and return the next item under this discipline.

    Returns
    -------
    tuple of (Item, torch.Tensor)
        The next item and its pending weight.
    """
    # Entries pushed before a semiring was bound drain first;
    # they were pushed earliest, so this preserves FIFO order.
    if self._queue:
        return self._queue.popleft()
    item = self._order.popleft()
    self._work.hashes += 1
    return item, self._pending.pop(item)

empty

empty() -> bool

Whether no items are pending.

RETURNS DESCRIPTION
bool

True when the agenda holds no items.

Source code in src/quivers/stochastic/agenda.py
def empty(self) -> bool:
    """Whether no items are pending.

    Returns
    -------
    bool
        ``True`` when the agenda holds no items.
    """
    return not self._queue and not self._order

LIFOAgenda

LIFOAgenda()

Bases: Agenda

Last-in-first-out agenda (depth-first proof-search discipline).

The agenda processes items in reverse-derivation order. Suitable for goal-directed search like Agda elaboration and Twelf-style MLTT type-checking, where depth-first proof construction is the natural strategy.

Source code in src/quivers/stochastic/agenda.py
def __init__(self) -> None:
    self._stack: list[tuple[Item, torch.Tensor]] = []

work_counts

work_counts() -> Mapping[WorkField, int]

The queue's work: none of the counted kinds.

RETURNS DESCRIPTION
Mapping of WorkField to int

A stack sums, hashes, compares and multiplies nothing.

Source code in src/quivers/stochastic/agenda.py
def work_counts(self) -> Mapping[WorkField, int]:
    """The queue's work: none of the counted kinds.

    Returns
    -------
    Mapping of WorkField to int
        A stack sums, hashes, compares and multiplies nothing.
    """
    return dict.fromkeys(COMPONENT_FIELDS, 0)

push

push(item: Item, weight: Tensor) -> None

Add an item and its weight to the agenda.

PARAMETER DESCRIPTION
item

The derived item.

TYPE: Item

weight

The weight contributed by this derivation.

TYPE: Tensor

Source code in src/quivers/stochastic/agenda.py
def push(self, item: Item, weight: torch.Tensor) -> None:
    """Add an item and its weight to the agenda.

    Parameters
    ----------
    item : Item
        The derived item.
    weight : torch.Tensor
        The weight contributed by this derivation.
    """
    self._stack.append((item, weight))

pop

pop() -> tuple[Item, Tensor]

Remove and return the next item under this discipline.

RETURNS DESCRIPTION
tuple of (Item, torch.Tensor)

The next item and its pending weight.

Source code in src/quivers/stochastic/agenda.py
def pop(self) -> tuple[Item, torch.Tensor]:
    """Remove and return the next item under this discipline.

    Returns
    -------
    tuple of (Item, torch.Tensor)
        The next item and its pending weight.
    """
    return self._stack.pop()

empty

empty() -> bool

Whether no items are pending.

RETURNS DESCRIPTION
bool

True when the agenda holds no items.

Source code in src/quivers/stochastic/agenda.py
def empty(self) -> bool:
    """Whether no items are pending.

    Returns
    -------
    bool
        ``True`` when the agenda holds no items.
    """
    return not self._stack

PriorityQueueAgenda

PriorityQueueAgenda(priority_fn: Callable[[Item, Tensor], float])

Bases: Agenda

Priority-queue agenda parameterized by a priority function.

Items are processed in decreasing priority order. Used by Knuth's algorithm (priority = current best score), A* parsing (priority = g + h with admissible h), and any best-first chart algorithm.

PARAMETER DESCRIPTION
priority_fn

(item, weight) -> float. Higher priorities are processed first. The chart's monotone-priority property (Nederhof 2003) ensures correctness when the semiring is superior.

TYPE: Callable

Source code in src/quivers/stochastic/agenda.py
def __init__(self, priority_fn: Callable[[Item, torch.Tensor], float]) -> None:
    self._priority_fn = priority_fn
    self._heap: list[_HeapEntry] = []
    self._counter = 0  # tie-breaker for deterministic ordering
    self._work = _ComponentWork()

work_counts

work_counts() -> Mapping[WorkField, int]

The queue's work since it was made.

RETURNS DESCRIPTION
Mapping of WorkField to int

The comparisons its heap made, counted by its entries; it sums, hashes and multiplies nothing.

Source code in src/quivers/stochastic/agenda.py
def work_counts(self) -> Mapping[WorkField, int]:
    """The queue's work since it was made.

    Returns
    -------
    Mapping of WorkField to int
        The comparisons its heap made, counted by its entries; it
        sums, hashes and multiplies nothing.
    """
    return self._work.counts()

push

push(item: Item, weight: Tensor) -> None

Add an item and its weight to the agenda.

PARAMETER DESCRIPTION
item

The derived item.

TYPE: Item

weight

The weight contributed by this derivation.

TYPE: Tensor

Source code in src/quivers/stochastic/agenda.py
def push(self, item: Item, weight: torch.Tensor) -> None:
    """Add an item and its weight to the agenda.

    Parameters
    ----------
    item : Item
        The derived item.
    weight : torch.Tensor
        The weight contributed by this derivation.
    """
    # heapq is a min-heap; negate priority for max-heap behavior.
    priority = -float(self._priority_fn(item, weight))
    self._counter += 1
    heapq.heappush(
        self._heap, _HeapEntry(priority, self._counter, item, weight, self._work)
    )

pop

pop() -> tuple[Item, Tensor]

Remove and return the next item under this discipline.

RETURNS DESCRIPTION
tuple of (Item, torch.Tensor)

The next item and its pending weight.

Source code in src/quivers/stochastic/agenda.py
def pop(self) -> tuple[Item, torch.Tensor]:
    """Remove and return the next item under this discipline.

    Returns
    -------
    tuple of (Item, torch.Tensor)
        The next item and its pending weight.
    """
    entry = heapq.heappop(self._heap)
    return entry.item, entry.weight

empty

empty() -> bool

Whether no items are pending.

RETURNS DESCRIPTION
bool

True when the agenda holds no items.

Source code in src/quivers/stochastic/agenda.py
def empty(self) -> bool:
    """Whether no items are pending.

    Returns
    -------
    bool
        ``True`` when the agenda holds no items.
    """
    return not self._heap

AgendaResult didactic-model

AgendaResult(*, chart: Chart = field(opaque=True, extras=OPAQUE_BY_IDENTITY), semiring: ChartSemiring = field(opaque=True, extras=OPAQUE_BY_IDENTITY), goal_items: list[tuple[tuple[HeldValue, ...], Tensor]] = field(default_factory=list, opaque=True, extras=OPAQUE_BY_IDENTITY), iterations: int = 0, applications: list[tuple[int, str, tuple[tuple[HeldValue, ...], ...], tuple[HeldValue, ...]]] = field(default_factory=list, opaque=True, extras=OPAQUE_BY_IDENTITY), axiom_occurrences: list[tuple[HeldValue, ...]] = field(default_factory=list, opaque=True, extras=OPAQUE_BY_IDENTITY), like: Tensor = field(default_factory=lambda: empty(0), opaque=True, extras=OPAQUE_BY_IDENTITY), encoder: Encoder | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), attached_loss: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), work: WorkReport = field(default_factory=lambda: WorkReport(phase=EXECUTION), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The chart produced by an agenda-driven deduction.

ATTRIBUTE DESCRIPTION
chart

The completed chart: each derived item's weight.

TYPE: Chart

semiring

The semiring used for weight aggregation.

TYPE: ChartSemiring

goal_items

Items in the chart matching the goal predicate, with their final aggregated weights.

TYPE: list of (Item, torch.Tensor)

iterations

Number of agenda steps consumed (diagnostic).

TYPE: int

applications

Every rule application of the run: the rule's position in the system, its name, its antecedent items in premise order, and its conclusion. Two rules of one name are told apart by position.

TYPE: list of (int, str, tuple of Item, Item)

axiom_occurrences

The item of every axiom occurrence, in the order given, so equal axioms are two occurrences.

TYPE: list of Item

like

An empty tensor of the dtype and device of the run's axiom weights, which the zeros and units the result makes take; the default dtype when the run had no axiom.

TYPE: Tensor

work

The run's work: its pops and recorded applications; its pattern matches, sums, products and hash operations together with the chart's and the queue's, each measured when the run and both report it (ReportsWork); products only when no rule has a weight_fn, whose products are its own; and the elements saved for the backward pass when measured.

TYPE: WorkReport

DeductionSystem didactic-model

DeductionSystem(*, rules: tuple[InferenceRule, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), semiring: ChartSemiring = field(opaque=True, extras=OPAQUE_BY_IDENTITY), axiom_injector: Callable[[HeldValue], list[tuple[Item, Tensor]]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), goal: Callable[[Item], bool] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), agenda_factory: Callable[[], Agenda] = field(default=FIFOAgenda, opaque=True, extras=OPAQUE_BY_IDENTITY), chart_factory: Callable[..., Chart] = field(default=HashChart, opaque=True, extras=OPAQUE_BY_IDENTITY), max_iterations: int = 100000, tolerance: float = 0.0, mappable: bool = False, productions: ProductionWeights | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), production_refusal: str | None = None, goal_extent: Callable[[Item], tuple[int, int] | None] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), name: str = '', modules: dict[str, Module] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), item_signature: Signature | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), item_encoder: Encoder | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), losses: dict[str, LossRegistry] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), presentation: RulePresentation | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), reveal: ChartReveal | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

A weighted deductive system parameterized over its components.

The system is parameterized by:

  • An item algebra (implicit in the patterns the rules use).
  • A list of arity-n InferenceRule hyperedges.
  • A ChartSemiring for weight aggregation.
  • An axiom injector In -> [(Item, Weight)] producing the input's lexical / boundary items.
  • A goal predicate Item -> bool selecting the result items.
  • (Optional) a chart constructor and an agenda strategy.

The same data structure subsumes CKY (FIFO agenda, span items, Boolean / inside semiring), Viterbi (priority agenda with the current weight as priority, max-times semiring), A* parsing (priority agenda with an admissible heuristic, tropical semiring), MLTT type-checking (LIFO agenda, judgment items, Boolean semiring), and weighted Datalog (FIFO, atoms, any naturally-ordered semiring).

ATTRIBUTE DESCRIPTION
name

The declaration name used to look up an attached loss registry.

TYPE: str

modules

Owned parameter modules, keyed by their stable parameter-name prefixes.

TYPE: dict[str, Module]

item_signature

The signature of structured items, when declared.

TYPE: Signature | None

item_encoder

The encoder used by chart embedding queries.

TYPE: Encoder | None

losses

Shared loss registries keyed by deduction name. Compilation can attach a registry after another program has captured this system.

TYPE: dict[str, LossRegistry]

goal_extent

The positions of the input an item covers, declared for an item type whose items cover stretches of the input, None for an item that covers none. A goal of such a type has to cover the whole input. Without a declaration the goal is the predicate alone.

TYPE: Callable or None

mappable

Whether the chart can be filled at many parameter values in one pass: the order of the agenda, the rules that fire, and the axioms depend on the items alone, and the weights are computed by tensor operations. The DSL compiler declares it of the systems it builds.

TYPE: bool

presentation

The rule presentation the rules are derived from: each rule is the rule of the presentation at its position, spelled in the chart representation. None for a system built from rules directly.

TYPE: RulePresentation | None

reveal

What the run's items and applications stand for, when the system runs a deduction through an encoding with items and rules of its own; every result and every application a rule-attached loss reads goes through it. None when the run's items are the deduction's.

TYPE: ChartReveal | None

production_groups

production_groups() -> tuple[ProductionGroup, ...]

The system's productions, grouped by left-hand side.

RETURNS DESCRIPTION
tuple[ProductionGroup, ...]

One group per left-hand side, in order of its first production; rules first, then lexicon entries.

RAISES DESCRIPTION
ValueError

If the system has no fixed production groups: it was not compiled from a grammar, or a rule stands for one production per binding of a category variable.

Source code in src/quivers/stochastic/agenda.py
def production_groups(self) -> tuple[ProductionGroup, ...]:
    """The system's productions, grouped by left-hand side.

    Returns
    -------
    tuple[ProductionGroup, ...]
        One group per left-hand side, in order of its first
        production; rules first, then lexicon entries.

    Raises
    ------
    ValueError
        If the system has no fixed production groups: it was not
        compiled from a grammar, or a rule stands for one production
        per binding of a category variable.
    """
    if self.productions is None:
        raise ValueError(
            "the deduction has no fixed production groups: "
            + (self.production_refusal or "it was not compiled from a grammar")
        )
    return self.productions.groups

production_log_probs

production_log_probs(probabilities: Mapping[str, Tensor] | None = None) -> dict[str, dict[str, Tensor]]

Each production's log-probability, by left-hand side.

PARAMETER DESCRIPTION
probabilities

Production probabilities to read instead of the learned weights: one vector per left-hand side with several productions, keyed by its label, in production order.

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

RETURNS DESCRIPTION
dict[str, dict[str, Tensor]]

For each left-hand side, the log-probability of each of its productions (a rule by name, a lexicon entry by its word in double quotes); the probabilities of a group sum to one. The tensors carry gradients to the learned weights.

RAISES DESCRIPTION
ValueError

If the system does not normalize its weights per left-hand side (normalize=lhs), or the probabilities do not fit its groups.

Source code in src/quivers/stochastic/agenda.py
def production_log_probs(
    self, probabilities: Mapping[str, torch.Tensor] | None = None
) -> dict[str, dict[str, torch.Tensor]]:
    """Each production's log-probability, by left-hand side.

    Parameters
    ----------
    probabilities : Mapping[str, torch.Tensor] | None
        Production probabilities to read instead of the learned
        weights: one vector per left-hand side with several
        productions, keyed by its label, in production order.

    Returns
    -------
    dict[str, dict[str, torch.Tensor]]
        For each left-hand side, the log-probability of each of its
        productions (a rule by name, a lexicon entry by its word in
        double quotes); the probabilities of a group sum to one.
        The tensors carry gradients to the learned weights.

    Raises
    ------
    ValueError
        If the system does not normalize its weights per left-hand
        side (``normalize=lhs``), or the probabilities do not fit its
        groups.
    """
    return self._normalized().log_probs(probabilities)

run

run(input_value: Any, probabilities: Mapping[str, Tensor] | None = None) -> AgendaResult

Run the deduction system on an input value.

Injects the input's axioms, runs the agenda to fixed point, attaches the item encoder when one is set, and sums any rule-attached and chart-attached losses.

PARAMETER DESCRIPTION
input_value

The input the axiom injector reads.

TYPE: Any

probabilities

Production probabilities the run reads instead of the learned weights, for a grammar normalized per left-hand side: one vector per left-hand side with several productions, keyed by its label (production_groups).

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

RETURNS DESCRIPTION
AgendaResult

The completed chart, its goal items, and any attached loss.

RAISES DESCRIPTION
ValueError

If probabilities are given to a system that is not normalized per left-hand side, or do not fit its groups.

Source code in src/quivers/stochastic/agenda.py
def run(
    self,
    input_value: Any,
    probabilities: Mapping[str, torch.Tensor] | None = None,
) -> AgendaResult:
    """Run the deduction system on an input value.

    Injects the input's axioms, runs the agenda to fixed point,
    attaches the item encoder when one is set, and sums any
    rule-attached and chart-attached losses.

    Parameters
    ----------
    input_value : Any
        The input the axiom injector reads.
    probabilities : Mapping[str, torch.Tensor] | None
        Production probabilities the run reads instead of the
        learned weights, for a grammar normalized per left-hand
        side: one vector per left-hand side with several
        productions, keyed by its label (`production_groups`).

    Returns
    -------
    AgendaResult
        The completed chart, its goal items, and any attached
        loss.

    Raises
    ------
    ValueError
        If probabilities are given to a system that is not
        normalized per left-hand side, or do not fit its groups.
    """
    productions = self.productions
    # A normalized grammar computes its production table once per run,
    # so every axiom and firing reads one consistent table.
    if probabilities is not None:
        normalized = self._normalized()
        scope = normalized.active(normalized.table(probabilities))
    elif productions is not None and productions.normalize:
        scope = productions.active(productions.table())
    else:
        scope = nullcontext()
    with scope:
        return self._run(input_value)

corpus

corpus(sentences: Sequence[Any], probabilities: Mapping[str, Tensor] | None = None) -> CorpusChart

Run the deduction on every sentence of a corpus.

The sentences are independent draws, so the corpus's goal weight is the semiring product of the sentences' goal weights: under LogProb, the sum of their log inside weights.

PARAMETER DESCRIPTION
sentences

The inputs, one per sentence.

TYPE: Sequence[Any]

probabilities

Production probabilities every sentence reads instead of the learned weights, as for run.

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

RETURNS DESCRIPTION
CorpusChart

The sentences' charts and the corpus's goal weight.

RAISES DESCRIPTION
ValueError

If the corpus is empty, or the probabilities do not fit the system.

Source code in src/quivers/stochastic/agenda.py
def corpus(
    self,
    sentences: Sequence[Any],
    probabilities: Mapping[str, torch.Tensor] | None = None,
) -> CorpusChart:
    """Run the deduction on every sentence of a corpus.

    The sentences are independent draws, so the corpus's goal weight
    is the semiring product of the sentences' goal weights: under
    ``LogProb``, the sum of their log inside weights.

    Parameters
    ----------
    sentences : Sequence[Any]
        The inputs, one per sentence.
    probabilities : Mapping[str, torch.Tensor] | None
        Production probabilities every sentence reads instead of the
        learned weights, as for `run`.

    Returns
    -------
    CorpusChart
        The sentences' charts and the corpus's goal weight.

    Raises
    ------
    ValueError
        If the corpus is empty, or the probabilities do not fit the
        system.
    """
    if len(sentences) == 0:
        raise ValueError("a corpus has at least one sentence")
    views = tuple(self(sentence, probabilities) for sentence in sentences)
    return CorpusChart(views, self.semiring)

parameters

parameters(recurse: bool = True) -> Iterable[Parameter]

Yield every learnable parameter owned by this system.

Walks the optional _axiom_module (lexicon log-weights) and _rule_module (per-rule log-weights keyed by category bindings) submodules attached by the compiler. The recurse flag is the standard torch.nn.Module.parameters signature so user code can pass a DeductionSystem anywhere a nn.Module parameter iterator is expected.

PARAMETER DESCRIPTION
recurse

Whether to include parameters of nested submodules.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Iterable of torch.nn.Parameter

The learnable parameters.

Source code in src/quivers/stochastic/agenda.py
def parameters(self, recurse: bool = True) -> Iterable[torch.nn.Parameter]:
    """Yield every learnable parameter owned by this system.

    Walks the optional ``_axiom_module`` (lexicon log-weights)
    and ``_rule_module`` (per-rule log-weights keyed by category bindings)
    submodules attached by the compiler. The ``recurse`` flag
    is the standard `torch.nn.Module.parameters` signature
    so user code can pass a ``DeductionSystem`` anywhere a
    ``nn.Module`` parameter iterator is expected.

    Parameters
    ----------
    recurse : bool
        Whether to include parameters of nested submodules.

    Returns
    -------
    Iterable of torch.nn.Parameter
        The learnable parameters.
    """
    for attr in ("_axiom_module", "_rule_module"):
        mod = self.modules.get(attr)
        if mod is not None and hasattr(mod, "parameters"):
            yield from mod.parameters(recurse=recurse)

named_parameters

named_parameters(prefix: str = '', recurse: bool = True) -> Iterable[tuple[str, Parameter]]

Yield (name, parameter) pairs over all learnable parameters.

PARAMETER DESCRIPTION
prefix

A prefix prepended to every parameter name.

TYPE: str DEFAULT: ''

recurse

Whether to include parameters of nested submodules.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Iterable of (str, torch.nn.Parameter)

The named learnable parameters.

Source code in src/quivers/stochastic/agenda.py
def named_parameters(
    self,
    prefix: str = "",
    recurse: bool = True,
) -> Iterable[tuple[str, torch.nn.Parameter]]:
    """Yield ``(name, parameter)`` pairs over all learnable parameters.

    Parameters
    ----------
    prefix : str
        A prefix prepended to every parameter name.
    recurse : bool
        Whether to include parameters of nested submodules.

    Returns
    -------
    Iterable of (str, torch.nn.Parameter)
        The named learnable parameters.
    """
    for attr in ("_axiom_module", "_rule_module"):
        mod = self.modules.get(attr)
        if mod is not None and hasattr(mod, "named_parameters"):
            sub_prefix = f"{prefix}.{attr}" if prefix else attr
            for n, p in mod.named_parameters(
                prefix=sub_prefix,
                recurse=recurse,
            ):
                yield n, p

make_wildcard

make_wildcard(name: str) -> Wildcard

Build a fresh wildcard with the given variable name.

PARAMETER DESCRIPTION
name

The pattern variable the wildcard binds.

TYPE: str

RETURNS DESCRIPTION
Wildcard

The wildcard.

Source code in src/quivers/stochastic/agenda.py
def make_wildcard(name: str) -> Wildcard:
    """Build a fresh wildcard with the given variable name.

    Parameters
    ----------
    name : str
        The pattern variable the wildcard binds.

    Returns
    -------
    Wildcard
        The wildcard.
    """
    return Wildcard(name=name)

instantiate

instantiate(pattern: Pattern, bindings: Bindings) -> Item

Substitute wildcards in a pattern with their bound values.

The pattern may be a bare Wildcard (treated as "the entire item is the wildcard"), a structural tuple, or a leaf value (returned unchanged). Recursion runs over tuple children.

PARAMETER DESCRIPTION
pattern

The pattern to instantiate.

TYPE: Pattern

bindings

Values for the pattern's wildcards.

TYPE: Bindings

RETURNS DESCRIPTION
Item

A concrete item with no wildcards.

RAISES DESCRIPTION
KeyError

If a wildcard in the pattern has no binding.

Source code in src/quivers/stochastic/agenda.py
def instantiate(pattern: Pattern, bindings: Bindings) -> Item:
    """Substitute wildcards in a pattern with their bound values.

    The pattern may be a bare `Wildcard` (treated as "the
    entire item is the wildcard"), a structural tuple, or a leaf
    value (returned unchanged). Recursion runs over tuple
    children.

    Parameters
    ----------
    pattern : Pattern
        The pattern to instantiate.
    bindings : Bindings
        Values for the pattern's wildcards.

    Returns
    -------
    Item
        A concrete item with no wildcards.

    Raises
    ------
    KeyError
        If a wildcard in the pattern has no binding.
    """
    if isinstance(pattern, Wildcard):
        return bindings[pattern.name]
    if not isinstance(pattern, tuple):
        return pattern
    out: list[Any] = []
    for p in pattern:
        if isinstance(p, Wildcard):
            out.append(bindings[p.name])
        elif isinstance(p, tuple):
            out.append(instantiate(p, bindings))
        else:
            out.append(p)
    return tuple(out)

match

match(pattern: Pattern, item: Item, bindings: Bindings | None = None) -> Bindings | None

Match an item against a pattern.

Wildcards bind the values at their positions; a wildcard already bound in bindings (or earlier in the pattern) must see an equal value, whatever value it is bound to, None included. Tuples match slot by slot when their lengths agree, and other values match by equality.

PARAMETER DESCRIPTION
pattern

The pattern to match.

TYPE: Pattern

item

The item to match against.

TYPE: Item

bindings

Bindings to extend; None starts from no bindings.

TYPE: Bindings or None DEFAULT: None

RETURNS DESCRIPTION
Bindings or None

The extended bindings, or None when the item does not match.

Source code in src/quivers/stochastic/agenda.py
def match(
    pattern: Pattern, item: Item, bindings: Bindings | None = None
) -> Bindings | None:
    """Match an item against a pattern.

    Wildcards bind the values at their positions; a wildcard
    already bound in ``bindings`` (or earlier in the pattern) must
    see an equal value, whatever value it is bound to, ``None``
    included. Tuples match slot by slot when their
    lengths agree, and other values match by equality.

    Parameters
    ----------
    pattern : Pattern
        The pattern to match.
    item : Item
        The item to match against.
    bindings : Bindings or None
        Bindings to extend; ``None`` starts from no bindings.

    Returns
    -------
    Bindings or None
        The extended bindings, or ``None`` when the item does not
        match.
    """
    if bindings is None:
        bindings = {}
    if isinstance(pattern, Wildcard):
        if pattern.name not in bindings:
            return {**bindings, pattern.name: item}
        if bindings[pattern.name] == item:
            return bindings
        return None
    if not isinstance(pattern, tuple) or not isinstance(item, tuple):
        if pattern == item:
            return bindings
        return None
    if len(pattern) != len(item):
        return None
    out = dict(bindings)
    for p, v in zip(pattern, item):
        if isinstance(p, Wildcard):
            if p.name not in out:
                out[p.name] = v
            elif out[p.name] != v:
                return None
        elif isinstance(p, tuple) and isinstance(v, tuple):
            sub = match(p, v, out)
            if sub is None:
                return None
            out = sub
        elif p != v:
            return None
    return out

run_agenda

run_agenda(axioms: Iterable[tuple[Item, Tensor]], rules: Iterable[InferenceRule], semiring: ChartSemiring | None = None, agenda: Agenda | None = None, goal: Callable[[Item], bool] | None = None, max_iterations: int = 100000, chart: Chart | None = None, rule_callback: RuleCallback | None = None, *, measure_tape: bool = False) -> AgendaResult

Run the agenda-driven deduction engine to fixed point.

The value of an item is the semiring sum, over its derivations, of the semiring product of the weights in the derivation Goodman (1999): an axiom's weight, and for each rule application the product of its antecedents' values (combined by the rule's weight_fn when it has one). Equivalently, the chart solves the equations value(c) = axiom(c) ⊕ ⨁_{applications e → c} ⊗_j value(a_j); on a finite acyclic system the solution is unique and equals the sum over derivations, each derivation counted exactly once.

The engine is the weighted agenda algorithm of Eisner, Goldlust, and Smith (2005), figure 3:

  1. Push every axiom onto the agenda.
  2. While the agenda is non-empty: a. Pop an item a with its pending update Δ. b. Record old = chart[a] and aggregate chart[a] := old ⊕ Δ. c. If the chart's weight changed, then for every rule and every premise position i that a matches, and every way of matching the other premises against the chart, push onto the conclusion the product whose j-th factor is old when j < i and premise j is a itself, Δ when j = i, and chart[a_j] otherwise.
  3. Return the chart with all items that match goal.

The case split in 2c is what keeps an item that fills several premises of one rule from being counted once per premise: when a fills the premise positions S, the increments over i ∈ S sum, by distributivity, to exactly the terms of ⊗_{j ∈ S} (old ⊕ Δ) that contain at least one Δ. A rule NP, NP ⊢ S with one NP axiom of weight w thus gives S the weight w ⊗ w, not (w ⊗ w) ⊕ (w ⊗ w).

A least fixed-point reading of a cyclic system requires an ordered setting in which the iteration converges; the iteration bound may raise before closure is reached.

PARAMETER DESCRIPTION
axioms

Initial items with their input-derived weights.

TYPE: iterable of (Item, weight)

rules

The deduction system's hyperedges. A rule's weight_fn must distribute over ⊕ in each premise weight (for instance, a rule weight times the product of the premise weights), as the algorithm propagates increments rather than totals.

TYPE: iterable of InferenceRule

semiring

Weight aggregation. Defaults to log-prob.

TYPE: ChartSemiring DEFAULT: None

agenda

Evaluation strategy. Defaults to FIFO (semi-naive).

TYPE: Agenda DEFAULT: None

goal

Predicate selecting result items. Defaults to "every item".

TYPE: callable DEFAULT: None

max_iterations

Safety bound on agenda steps; raises if exceeded.

TYPE: int DEFAULT: 100000

chart

Initial chart (defaults to empty HashChart).

TYPE: Chart DEFAULT: None

rule_callback

Called as (rule_name, antecedents, conclusion, weight) once per rule application (a rule together with one tuple of antecedent items), after the chart reaches its fixed point. antecedents carries each antecedent's final chart weight and weight is the application's contribution to the conclusion computed from those weights.

TYPE: callable DEFAULT: None

measure_tape

Whether to count the elements the run saves for the backward pass, by a hook on the autograd graph that costs time.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
AgendaResult

The final chart, the goal items, the step count, and the work report of the run.

RAISES DESCRIPTION
RuntimeError

If the agenda runs for more than max_iterations steps.

Source code in src/quivers/stochastic/agenda.py
def run_agenda(
    axioms: Iterable[tuple[Item, torch.Tensor]],
    rules: Iterable[InferenceRule],
    semiring: ChartSemiring | None = None,
    agenda: Agenda | None = None,
    goal: Callable[[Item], bool] | None = None,
    max_iterations: int = 100_000,
    chart: Chart | None = None,
    rule_callback: RuleCallback | None = None,
    *,
    measure_tape: bool = False,
) -> AgendaResult:
    """Run the agenda-driven deduction engine to fixed point.

    The value of an item is the semiring sum, over its derivations, of
    the semiring product of the weights in the derivation
    [Goodman (1999)](<https://aclanthology.org/J99-4004/>): an axiom's
    weight, and for each rule application the product of its
    antecedents' values (combined by the rule's ``weight_fn`` when it
    has one). Equivalently, the chart solves the equations
    ``value(c) = axiom(c) ⊕ ⨁_{applications e → c} ⊗_j value(a_j)``;
    on a finite acyclic system the solution is unique and equals the
    sum over derivations, each derivation counted exactly once.

    The engine is the weighted agenda algorithm of
    [Eisner, Goldlust, and Smith (2005)](<https://doi.org/10.3115/1220575.1220611>),
    figure 3:

    1. Push every axiom onto the agenda.
    2. While the agenda is non-empty:
       a. Pop an item ``a`` with its pending update ``Δ``.
       b. Record ``old = chart[a]`` and aggregate ``chart[a] := old ⊕ Δ``.
       c. If the chart's weight changed, then for every rule and every
          premise position ``i`` that ``a`` matches, and every way of
          matching the other premises against the chart, push onto
          the conclusion the product whose ``j``-th factor is ``old``
          when ``j < i`` and premise ``j`` is ``a`` itself, ``Δ`` when
          ``j = i``, and ``chart[a_j]`` otherwise.
    3. Return the chart with all items that match ``goal``.

    The case split in 2c is what keeps an item that fills several
    premises of one rule from being counted once per premise: when
    ``a`` fills the premise positions ``S``, the increments over
    ``i ∈ S`` sum, by distributivity, to exactly the terms of
    ``⊗_{j ∈ S} (old ⊕ Δ)`` that contain at least one ``Δ``. A rule
    ``NP, NP ⊢ S`` with one ``NP`` axiom of weight ``w`` thus gives
    ``S`` the weight ``w ⊗ w``, not ``(w ⊗ w) ⊕ (w ⊗ w)``.

    A least fixed-point reading of a cyclic system requires an ordered
    setting in which the iteration converges; the iteration bound may
    raise before closure is reached.

    Parameters
    ----------
    axioms : iterable of (Item, weight)
        Initial items with their input-derived weights.
    rules : iterable of InferenceRule
        The deduction system's hyperedges. A rule's ``weight_fn`` must
        distribute over ``⊕`` in each premise weight (for instance, a
        rule weight times the product of the premise weights), as the
        algorithm propagates increments rather than totals.
    semiring : ChartSemiring, optional
        Weight aggregation. Defaults to log-prob.
    agenda : Agenda, optional
        Evaluation strategy. Defaults to FIFO (semi-naive).
    goal : callable, optional
        Predicate selecting result items. Defaults to "every item".
    max_iterations : int, optional
        Safety bound on agenda steps; raises if exceeded.
    chart : Chart, optional
        Initial chart (defaults to empty `HashChart`).
    rule_callback : callable, optional
        Called as ``(rule_name, antecedents, conclusion, weight)`` once
        per rule application (a rule together with one tuple of
        antecedent items), after the chart reaches its fixed point.
        ``antecedents`` carries each antecedent's final chart weight
        and ``weight`` is the application's contribution to the
        conclusion computed from those weights.

    measure_tape : bool, optional
        Whether to count the elements the run saves for the backward
        pass, by a hook on the autograd graph that costs time.

    Returns
    -------
    AgendaResult
        The final chart, the goal items, the step count, and the work
        report of the run.

    Raises
    ------
    RuntimeError
        If the agenda runs for more than ``max_iterations`` steps.
    """
    semiring = semiring or LOG_PROB
    agenda = agenda or FIFOAgenda()
    agenda.bind_semiring(semiring)
    if chart is None:
        chart = HashChart()
    rules = tuple(rules)
    applications: dict[tuple[int, tuple[Item, ...]], _Application] = {}

    chart_before = chart.work_counts() if isinstance(chart, ReportsWork) else None
    queue_before = agenda.work_counts() if isinstance(agenda, ReportsWork) else None
    occurrences: list[Item] = []
    weights_seen: list[torch.Tensor] = []
    for item, w in axioms:
        occurrences.append(item)
        weights_seen.append(w)
        agenda.push(item, w)
    like = (
        torch.empty(0, dtype=weights_seen[0].dtype, device=weights_seen[0].device)
        if weights_seen
        else torch.empty(0)
    )

    work = _AgendaWork()
    joins = _RuleJoins(rules, work)
    for present, _ in list(chart.items()):
        joins.add(present, joins.matches(present))
    saved: list[int] = []
    with _tape(saved) if measure_tape else nullcontext():
        _drain(
            agenda,
            chart,
            rules,
            semiring,
            applications,
            work,
            max_iterations,
            joins,
        )
    iterations = work.pops
    if rule_callback is not None:
        for application in applications.values():
            weights = tuple(_chart_weight(chart, a) for a in application.antecedents)
            rule_callback(
                application.rule.name,
                list(zip(application.antecedents, weights)),
                application.conclusion,
                _conclusion_weight(
                    application.rule,
                    application.bindings,
                    weights,
                    semiring,
                    like,
                    work,
                ),
            )

    goal_items: list[tuple[Item, torch.Tensor]] = []
    if goal is not None:
        for item, w in chart.items():
            if goal(item):
                goal_items.append((item, w))
    else:
        goal_items = list(chart.items())

    return AgendaResult(
        chart=chart,
        semiring=semiring,
        goal_items=goal_items,
        iterations=iterations,
        applications=[
            (index, a.rule.name, a.antecedents, a.conclusion)
            for (index, _), a in applications.items()
        ],
        axiom_occurrences=occurrences,
        like=like,
        work=_agenda_report(
            work,
            applications=sum(
                1 + len(application.antecedents)
                for application in applications.values()
            ),
            occurrences=len(occurrences),
            products_measured=all(rule.weight_fn is None for rule in rules),
            saved=sum(saved) if measure_tape else None,
            components=(_since(chart, chart_before), _since(agenda, queue_before)),
        ),
    )

cky_agenda

cky_agenda() -> Agenda

The CKY (bottom-up sweep) agenda: semi-naïve FIFO.

For context-free + Boolean / inside semirings, FIFO order suffices to reach the chart's fixed point in :math:O(n^3 \cdot |R|) time (McAllester 2002).

RETURNS DESCRIPTION
Agenda

A fresh FIFOAgenda.

Source code in src/quivers/stochastic/agenda.py
def cky_agenda() -> Agenda:
    """The CKY (bottom-up sweep) agenda: semi-naïve FIFO.

    For context-free + Boolean / inside semirings, FIFO order
    suffices to reach the chart's fixed point in
    :math:`O(n^3 \\cdot |R|)` time (McAllester 2002).

    Returns
    -------
    Agenda
        A fresh `FIFOAgenda`.
    """
    return FIFOAgenda()

earley_agenda

earley_agenda() -> Agenda

The Earley (predict / scan / complete) agenda: FIFO.

Earley's algorithm is identical to FIFO agenda-driven deduction over the predict / scan / complete items (Pereira & Warren 1983).

RETURNS DESCRIPTION
Agenda

A fresh FIFOAgenda.

Source code in src/quivers/stochastic/agenda.py
def earley_agenda() -> Agenda:
    """The Earley (predict / scan / complete) agenda: FIFO.

    Earley's algorithm is identical to FIFO agenda-driven
    deduction over the predict / scan / complete items
    (Pereira & Warren 1983).

    Returns
    -------
    Agenda
        A fresh `FIFOAgenda`.
    """
    return FIFOAgenda()

viterbi_agenda

viterbi_agenda(priority_fn: Callable[[Item, Tensor], float]) -> Agenda

Viterbi-style best-first agenda.

Priorities are the current best weight in the :math:(\max, \times) semiring; the agenda is a priority queue. Equivalent to Knuth's algorithm when the semiring is superior (Nederhof 2003).

PARAMETER DESCRIPTION
priority_fn

The priority of an item given its weight; higher pops first.

TYPE: Callable[[Item, Tensor], float]

RETURNS DESCRIPTION
Agenda

A PriorityQueueAgenda ordered by priority_fn.

Source code in src/quivers/stochastic/agenda.py
def viterbi_agenda(priority_fn: Callable[[Item, torch.Tensor], float]) -> Agenda:
    """Viterbi-style best-first agenda.

    Priorities are the current best weight in the
    :math:`(\\max, \\times)` semiring; the agenda is a priority
    queue. Equivalent to Knuth's algorithm when the semiring is
    superior (Nederhof 2003).

    Parameters
    ----------
    priority_fn : Callable[[Item, torch.Tensor], float]
        The priority of an item given its weight; higher pops first.

    Returns
    -------
    Agenda
        A `PriorityQueueAgenda` ordered by ``priority_fn``.
    """
    return PriorityQueueAgenda(priority_fn)

astar_agenda

astar_agenda(g_plus_h: Callable[[Item, Tensor], float]) -> Agenda

Priority agenda for an A* parsing strategy Klein and Manning (2003).

The queue pops the highest numeric priority first. If g and h are costs to minimize, pass a priority such as -(g + h). A valid A* algorithm also needs an appropriate heuristic, update policy, and termination condition; constructing this queue alone does not prove optimality or enumerate every item in increasing true cost.

PARAMETER DESCRIPTION
g_plus_h

The priority g + h of an item given its weight; higher pops first.

TYPE: Callable[[Item, Tensor], float]

RETURNS DESCRIPTION
Agenda

A PriorityQueueAgenda ordered by g_plus_h.

Source code in src/quivers/stochastic/agenda.py
def astar_agenda(
    g_plus_h: Callable[[Item, torch.Tensor], float],
) -> Agenda:
    """Priority agenda for an A* parsing strategy [Klein and Manning (2003)](<https://aclanthology.org/N03-1016/>).

    The queue pops the highest numeric priority first. If ``g`` and ``h``
    are costs to minimize, pass a priority such as ``-(g + h)``. A valid
    A* algorithm also needs an appropriate heuristic, update policy, and
    termination condition; constructing this queue alone does not prove
    optimality or enumerate every item in increasing true cost.

    Parameters
    ----------
    g_plus_h : Callable[[Item, torch.Tensor], float]
        The priority ``g + h`` of an item given its weight; higher pops first.

    Returns
    -------
    Agenda
        A `PriorityQueueAgenda` ordered by ``g_plus_h``.
    """
    return PriorityQueueAgenda(g_plus_h)

knuth_agenda

knuth_agenda() -> Agenda

Knuth's best-first hyperpath search.

Priority is the current chart weight (the item's best-so-far score). For a superior semiring, this is Dijkstra's algorithm on AND-OR hypergraphs (Knuth 1977; Nederhof 2003).

RETURNS DESCRIPTION
Agenda

A PriorityQueueAgenda ordered by the item's weight.

Source code in src/quivers/stochastic/agenda.py
def knuth_agenda() -> Agenda:
    """Knuth's best-first hyperpath search.

    Priority is the current chart weight (the item's best-so-far
    score). For a superior semiring, this is Dijkstra's algorithm
    on AND-OR hypergraphs (Knuth 1977; Nederhof 2003).

    Returns
    -------
    Agenda
        A `PriorityQueueAgenda` ordered by the item's weight.
    """

    def _priority(_item: Item, weight: torch.Tensor) -> float:
        return float(weight) if weight.numel() == 1 else float(weight.sum())

    return PriorityQueueAgenda(_priority)

depth_first_agenda

depth_first_agenda() -> Agenda

LIFO agenda: depth-first proof search (Agda / Twelf style).

RETURNS DESCRIPTION
Agenda

A fresh LIFOAgenda.

Source code in src/quivers/stochastic/agenda.py
def depth_first_agenda() -> Agenda:
    """LIFO agenda: depth-first proof search (Agda / Twelf style).

    Returns
    -------
    Agenda
        A fresh `LIFOAgenda`.
    """
    return LIFOAgenda()

semi_naive_agenda

semi_naive_agenda() -> Agenda

Semi-naïve Datalog evaluation (McAllester 2002): FIFO.

RETURNS DESCRIPTION
Agenda

A fresh FIFOAgenda.

Source code in src/quivers/stochastic/agenda.py
def semi_naive_agenda() -> Agenda:
    """Semi-naïve Datalog evaluation (McAllester 2002): FIFO.

    Returns
    -------
    Agenda
        A fresh `FIFOAgenda`.
    """
    return FIFOAgenda()

Cited sources

Stuart M. Shieber, Yves Schabes, and Fernando C. N. Pereira. Principles and Implementation of Deductive Parsing. The Journal of Logic Programming, 24(1–2):3–36, 1995. URL: https://www.sciencedirect.com/science/article/pii/074310669500035I, doi:10.1016/0743-1066(95)00035-I.

Joshua Goodman. Semiring Parsing. Computational Linguistics, 25(4):573–606, 1999. URL: https://aclanthology.org/J99-4004/.

Jason Eisner, Eric Goldlust, and Noah A. Smith. Compiling Comp Ling: Practical Weighted Dynamic Programming and the Dyna Language. In Proceedings of Human Language Technology Conference and Conference on Empirical Methods in Natural Language Processing, 281–290. Association for Computational Linguistics, 2005. URL: https://aclanthology.org/H05-1036/.

Dan Klein and Christopher D. Manning. A* Parsing: Fast Exact Viterbi Parse Selection. In Proceedings of the 2003 Human Language Technology Conference of the North American Chapter of the Association for Computational Linguistics, 119–126. 2003. URL: https://aclanthology.org/N03-1016/.

Jason Eisner and John Blatz. Program Transformations for Optimization of Parsing Algorithms and Other Weighted Logic Programs. In Shuly Wintner, editor, Proceedings of FG-2006. CSLI Publications, 2007. URL: https://web.stanford.edu/group/cslipublications/cslipublications/FG/2006/FG.pdf.

Fernando C. N. Pereira and David H. D. Warren. Parsing as Deduction. In 21st Annual Meeting of the Association for Computational Linguistics, 137–144. Association for Computational Linguistics, 1983. URL: https://aclanthology.org/P83-1021/, doi:10.3115/981311.981338.

Dan Klein and Christopher D. Manning. Parsing and Hypergraphs. In Proceedings of the Seventh International Workshop on Parsing Technologies, 123–134. 2001. URL: https://aclanthology.org/W01-1812/.

Donald E. Knuth. A Generalization of Dijkstra's Algorithm. Information Processing Letters, 6(1):1–5, 1977. URL: https://www.sciencedirect.com/science/article/abs/pii/0020019077900023, doi:10.1016/0020-0190(77)90002-3.

Mark-Jan Nederhof. Squibs and Discussions: Weighted Deductive Parsing and Knuth's Algorithm. Computational Linguistics, 29(1):135–143, 2003. URL: https://aclanthology.org/J03-1006/, doi:10.1162/089120103321337467.

David McAllester. On the Complexity Analysis of Static Analyses. Journal of the ACM, 49(4):512–537, 2002. URL: https://doi.org/10.1145/581771.581774, doi:10.1145/581771.581774.