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
¶
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
¶
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
¶
A hook called once per rule application with its name, antecedents (each with its chart weight), conclusion, and contribution.
Wildcard
didactic-model
¶
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:
|
premises
|
Patterns the rule's antecedents must match.
TYPE:
|
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:
|
weight_fn
|
Function
TYPE:
|
side_condition
|
Predicate
TYPE:
|
canonical
|
Function
TYPE:
|
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.
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
¶
Enumerate the (item, weight) pairs that match a pattern under bindings.
| PARAMETER | DESCRIPTION |
|---|---|
pattern
|
The pattern to match stored items against.
TYPE:
|
bindings
|
Values of some of the pattern's wildcards; an item matches when it matches the pattern with those wildcards fixed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable of (Item, torch.Tensor)
|
The matching items with their weights. |
Source code in src/quivers/stochastic/agenda.py
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:
|
weight
|
The weight to insert, or to aggregate with the stored
weight under
TYPE:
|
semiring
|
The semiring whose
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
Source code in src/quivers/stochastic/agenda.py
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:
|
item
|
The item, whose stored weight the update changed.
TYPE:
|
weight
|
The increment.
TYPE:
|
semiring
|
The semiring.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The increment itself. |
Source code in src/quivers/stochastic/agenda.py
get
abstractmethod
¶
items
abstractmethod
¶
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
HashChart
¶
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;
TYPE:
|
Source code in src/quivers/stochastic/agenda.py
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
lookup
¶
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:
|
bindings
|
Values of some of its wildcards.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable of (Item, torch.Tensor)
|
The matching items with their weights. |
Source code in src/quivers/stochastic/agenda.py
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:
|
weight
|
The weight to insert or aggregate.
TYPE:
|
semiring
|
The semiring whose
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
Source code in src/quivers/stochastic/agenda.py
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:
|
item
|
The item.
TYPE:
|
weight
|
The increment.
TYPE:
|
semiring
|
The semiring, whose zero is the increment of no change.
TYPE:
|
| 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
get
¶
items
¶
Enumerate all stored (item, weight) pairs.
| RETURNS | DESCRIPTION |
|---|---|
Iterable of (Item, torch.Tensor)
|
Every stored item with its weight. |
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:
|
weight
|
Its weight in the run.
TYPE:
|
semiring
|
The run's semiring.
TYPE:
|
| 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
axiom
abstractmethod
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Item, ...]
|
The items of the deduction's axiom occurrences it stands for. |
Source code in src/quivers/stochastic/agenda.py
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:
|
antecedents
|
Its antecedents with their weights, in premise order. |
conclusion
|
Its conclusion.
TYPE:
|
semiring
|
The run's semiring.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, tuple[tuple[Item, Tensor], ...], Item] | None
|
The deduction's rule, its antecedents with their weights, and
its conclusion; |
Source code in src/quivers/stochastic/agenda.py
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:
|
rules
|
The system's rules; a revealed application is numbered by the first position of its rule.
TYPE:
|
goal
|
The run's goal predicate.
TYPE:
|
| 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
ChartView
¶
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 differentiabletorch.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:
|
Source code in src/quivers/stochastic/agenda.py
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.
goal_items
property
¶
List of (item, weight) pairs matching the goal predicate.
weight
¶
Return the aggregated weight at a concrete item.
| PARAMETER | DESCRIPTION |
|---|---|
item
|
A ground item.
TYPE:
|
| 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
try_weight
¶
Return the weight at item, or a fallback if it is absent.
| PARAMETER | DESCRIPTION |
|---|---|
item
|
A ground item.
TYPE:
|
default
|
The value to return for an absent item;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The item's weight, |
Source code in src/quivers/stochastic/agenda.py
enumerate
¶
Enumerate (item, weight) pairs matching pattern.
Wildcards in pattern (instances of Wildcard)
match any slot value.
| PARAMETER | DESCRIPTION |
|---|---|
pattern
|
The pattern to match.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of (Item, torch.Tensor)
|
The matching items with their differentiable weights. |
Source code in src/quivers/stochastic/agenda.py
embedding
¶
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:
|
| 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
derivations
¶
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:
|
| 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 |
Source code in src/quivers/stochastic/agenda.py
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
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:
|
semiring
|
The semiring the charts were computed in.
TYPE:
|
Source code in src/quivers/stochastic/agenda.py
goal_weight
¶
goal_weight() -> Tensor
The corpus's goal weight: the semiring product over sentences.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Under |
Source code in src/quivers/stochastic/agenda.py
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
¶
pop
abstractmethod
¶
Remove and return the next item under this discipline.
| RETURNS | DESCRIPTION |
|---|---|
tuple of (Item, torch.Tensor)
|
The next item and its pending weight. |
empty
abstractmethod
¶
Whether no items are pending.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
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:
|
Source code in src/quivers/stochastic/agenda.py
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
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
bind_semiring
¶
bind_semiring(semiring: ChartSemiring) -> None
Bind the semiring that merges pending contributions.
| PARAMETER | DESCRIPTION |
|---|---|
semiring
|
The engine's semiring.
TYPE:
|
Source code in src/quivers/stochastic/agenda.py
push
¶
Add an item and its weight to the agenda.
| PARAMETER | DESCRIPTION |
|---|---|
item
|
The derived item.
TYPE:
|
weight
|
The weight contributed by this derivation.
TYPE:
|
Source code in src/quivers/stochastic/agenda.py
pop
¶
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
empty
¶
Whether no items are pending.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
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
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
push
¶
pop
¶
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
empty
¶
Whether no items are pending.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
PriorityQueueAgenda
¶
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
|
TYPE:
|
Source code in src/quivers/stochastic/agenda.py
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
push
¶
Add an item and its weight to the agenda.
| PARAMETER | DESCRIPTION |
|---|---|
item
|
The derived item.
TYPE:
|
weight
|
The weight contributed by this derivation.
TYPE:
|
Source code in src/quivers/stochastic/agenda.py
pop
¶
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
empty
¶
Whether no items are pending.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
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:
|
semiring |
The semiring used for weight aggregation.
TYPE:
|
goal_items |
Items in the chart matching the goal predicate, with their final aggregated weights.
TYPE:
|
iterations |
Number of agenda steps consumed (diagnostic).
TYPE:
|
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:
|
axiom_occurrences |
The item of every axiom occurrence, in the order given, so equal axioms are two occurrences.
TYPE:
|
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:
|
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 (
TYPE:
|
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
InferenceRulehyperedges. - A
ChartSemiringfor weight aggregation. - An axiom injector
In -> [(Item, Weight)]producing the input's lexical / boundary items. - A goal predicate
Item -> boolselecting 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:
|
modules |
Owned parameter modules, keyed by their stable parameter-name prefixes.
TYPE:
|
item_signature |
The signature of structured items, when declared.
TYPE:
|
item_encoder |
The encoder used by chart embedding queries.
TYPE:
|
losses |
Shared loss registries keyed by deduction name. Compilation can attach a registry after another program has captured this system.
TYPE:
|
goal_extent |
The positions of the input an item covers, declared for an item
type whose items cover stretches of the input,
TYPE:
|
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:
|
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.
TYPE:
|
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.
TYPE:
|
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
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:
|
| 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 ( |
Source code in src/quivers/stochastic/agenda.py
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:
|
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 (
TYPE:
|
| 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
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:
|
probabilities
|
Production probabilities every sentence reads instead of the
learned weights, as for
TYPE:
|
| 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
parameters
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable of torch.nn.Parameter
|
The learnable parameters. |
Source code in src/quivers/stochastic/agenda.py
named_parameters
¶
Yield (name, parameter) pairs over all learnable parameters.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
A prefix prepended to every parameter name.
TYPE:
|
recurse
|
Whether to include parameters of nested submodules.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable of (str, torch.nn.Parameter)
|
The named learnable parameters. |
Source code in src/quivers/stochastic/agenda.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Wildcard
|
The wildcard. |
Source code in src/quivers/stochastic/agenda.py
instantiate
¶
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:
|
bindings
|
Values for the pattern's wildcards.
TYPE:
|
| 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
match
¶
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:
|
item
|
The item to match against.
TYPE:
|
bindings
|
Bindings to extend;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Bindings or None
|
The extended bindings, or |
Source code in src/quivers/stochastic/agenda.py
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:
- Push every axiom onto the agenda.
- While the agenda is non-empty:
a. Pop an item
awith its pending updateΔ. b. Recordold = chart[a]and aggregatechart[a] := old ⊕ Δ. c. If the chart's weight changed, then for every rule and every premise positionithatamatches, and every way of matching the other premises against the chart, push onto the conclusion the product whosej-th factor isoldwhenj < iand premisejisaitself,Δwhenj = i, andchart[a_j]otherwise. - 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:
|
rules
|
The deduction system's hyperedges. A rule's
TYPE:
|
semiring
|
Weight aggregation. Defaults to log-prob.
TYPE:
|
agenda
|
Evaluation strategy. Defaults to FIFO (semi-naive).
TYPE:
|
goal
|
Predicate selecting result items. Defaults to "every item".
TYPE:
|
max_iterations
|
Safety bound on agenda steps; raises if exceeded.
TYPE:
|
chart
|
Initial chart (defaults to empty
TYPE:
|
rule_callback
|
Called as
TYPE:
|
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:
|
| 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 |
Source code in src/quivers/stochastic/agenda.py
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 | |
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 |
Source code in src/quivers/stochastic/agenda.py
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 |
Source code in src/quivers/stochastic/agenda.py
viterbi_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. |
| RETURNS | DESCRIPTION |
|---|---|
Agenda
|
A |
Source code in src/quivers/stochastic/agenda.py
astar_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 |
| RETURNS | DESCRIPTION |
|---|---|
Agenda
|
A |
Source code in src/quivers/stochastic/agenda.py
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 |
Source code in src/quivers/stochastic/agenda.py
depth_first_agenda
¶
depth_first_agenda() -> Agenda
LIFO agenda: depth-first proof search (Agda / Twelf style).
| RETURNS | DESCRIPTION |
|---|---|
Agenda
|
A fresh |
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.