Skip to content

Weighted deduction

A deduction declaration denotes a weighted deduction system: a set of items, inference rules over them, a semiring of weights, the axioms an input gives, and the goal items (Shieber et al., 1995; Goodman, 1999; Nederhof, 2003). Its denotation is a function from inputs to weights: the chart assigns each item the \(\oplus\)-sum, over its derivations, of the \(\otimes\)-product of the weights each derivation uses, and the value is the sum of the chart over the goal items. The Weighted deduction systems guide shows the declarations in use. The same form expresses parsers, proof search, Datalog programs, and graph algorithms, which differ in their items, rules, and semiring. A deduction composed from signatures, lexicon modules, and rule schemata denotes the ordinary deduction its parts compose into (Composable deductions), so everything on this page applies to it unchanged.

A chart is the table of items proved so far and their weights, and an agenda is the queue of items still to be processed (Eisner et al., 2005). A chart lets a derivation reuse an item another derivation has already proved. In a graph, edges \(a \to b\) and \(b \to c\) of costs \(2\) and \(3\) derive a path \(a \to c\) of cost \(5\), and a direct edge of cost \(4\) derives it again: under the tropical semiring the chart keeps \(4\), and under the counting semiring it counts two derivations.

1. Items

The atoms clause of a deduction declares the constructor symbols. An item is a term over them: a symbol applied to items, c(a_1, ..., a_n), with nullary symbols as constants. The set \(I\) of items is the term algebra over the declared symbols, and two items are equal when they are the same term. The keyword atoms names these symbols, which logic programming would call function symbols.

A rule's patterns may contain variables, which range over items, and rules fire under the substitutions that unification finds for them. An identifier in a rule is a variable exactly when it is neither a declared symbol nor a numeral, whatever its spelling, and single uppercase letters are the convention. A declared symbol always denotes itself, in the agenda's chart and in the search computation of the Quivers Indexed Effect Core (QIEC) alike, so a variable must not be spelled like a symbol. A symbol is a valid ground pattern in a category slot. In a chart position slot (§2.1) it is a compile error naming the rule and the identifier, since a position slot holds a position variable or an integer.

2. Rules

A rule declaration

rule r : π_1, ..., π_m |- π

states the inference rule

\[ \frac{\pi_1\sigma \quad \cdots \quad \pi_m\sigma}{\pi\sigma} \quad (r) \]

for every substitution \(\sigma\) of items for its variables: when every premise instance \(\pi_\ell\sigma\) is in the chart, the conclusion \(\pi\sigma\) is derived. A rule with several premises is a hyperedge of a hypergraph, an edge from several premises to one conclusion (Klein and Manning, 2001). It needs all its premises at once, so it is not a set of separate rules with one premise. Each instance has a weight \(\beta_r(\sigma) \in K\) in the deduction's semiring \(K\), which is \(\mathbf 1_K\) unless the rule is learnable or weighted.

A ground rule rule r : |- π has no premises and a conclusion with no free rule variables. Its single instance contributes \(\beta_r\) directly to the chart at \(\pi\). In a checked lexical outcome query, the two positions of a ground span must be ordered natural literals. Equal positions denote an empty span.

The compiler reads a deduction once into a rule presentation, a RulePresentation: one judgment form for each kind of item, with its position slots typed as natural numbers, and one rule for each sequent. The agenda's rules and the QIEC elaboration are both derived from it, so the two read every pattern alike. A premise or conclusion that is a bare variable ranges over every judgment form, and the rule is the family of its instances, one for each form, sharing one weight.

2.1 Learnable rule weights (#[learnable])

A rule marked #[learnable],

rule r : π_1, ..., π_m |- π #[learnable]

has a learnable weight that depends on some of its variables. The variables of a rule are of two kinds. A position variable fills a chart position: one of the first two slots of span in a deduction with a lexicon (whose axioms are the items span(i, i + 1, c)), a slot that an integer literal fills, or a slot that a variable shared with a position slot fills in the same rule, closed under this last condition. Every other variable is a category variable, ranging over categories, logical forms, or other items. Write \(P(r)\) for the position variables of \(r\) and \(C(r)\) for its category variables. A firing with substitution \(\sigma\) gives its conclusion the weight

\[ \bigotimes_{\ell=1}^{m} \alpha\bigl(\pi_\ell\sigma\bigr) \otimes \theta_{r, \sigma|_{C(r)}}, \]

where \(\alpha\) is the chart, and \(\theta_{r, \kappa} \in K\) is one learnable scalar for each restriction \(\kappa\) of the substitution to the category variables. Positions never enter \(\kappa\), so a rule has the same weight at every position of every input, and the number of parameters does not grow with the length of the input. The weights are parameters of a PyTorch module owned by the deduction, and the weight of a category binding is created the first time a firing produces it.

  • A rule with no category variable, such as np : span(I, K, Det), span(K, J, N) |- span(I, J, NP), has one weight \(\theta_r\), the weight of a production of a weighted context-free grammar. It is created when the deduction is compiled.
  • A rule with category variables, such as fwd : span(I, K, Fwd(X, Y)), span(K, J, Y) |- span(I, J, X), has a separate weight for each ground value of \((X, Y)\).

A lexicon entry marked #[learnable] has one weight per entry, and one per candidate category for a wildcard or restricted category, shared by every position of its word. The checked QIEC elaboration reads the same weights from its parameter store under the names <D>.rule.<r>:<κ> and <D>.lex.<i>, with \(\kappa\) the category bindings in the order of their variable names joined by | (empty for a rule with no category variables), so the agenda and the QIEC search share a weight between the same firings.

2.2 Parent rules (parent=)

A rule may name a parent rule:

rule r' : π'_1, ..., π'_m |- π' #[learnable, parent=r]

Its weight is then the product, in \(K\), of its own learnable weight and the parent's weight under the same category bindings:

\[ \bigotimes_\ell \alpha\bigl(\pi'_\ell\sigma\bigr) \otimes \theta_{r', \kappa} \otimes \theta_{r, \kappa}, \qquad \kappa = \sigma|_{C(r')}. \]

Parent links form chains that end at a rule with no parent, and cycles are rejected. In the log semiring the weights add, so the child's weight is a correction to its parent's, a form of additive hierarchical sharing of parameters.

2.3 Bounded rule weights (bounded)

A learnable rule with bounded in its pragma has the weight

\[ \theta_{r, \kappa} = -\mathrm{softplus}(\mathit{raw}_{r, \kappa}) - \log n_b, \]

where \(\mathit{raw}_{r, \kappa}\) is the unconstrained parameter and \(n_b\) is the number of bounded rules in the deduction. Each firing of a bounded rule thus multiplies by less than \(1 / n_b\). When the bounded rules form cycles of unary rules, each giving at most one conclusion per item, the total weight one item passes on through all bounded rules is below \(1\). Under a semiring that is not idempotent, such as LogProb or Counting, the weight of an item on a cycle is the sum of a series over every number of trips around the cycle, the Kleene star \(a^* = \bigoplus_{n \ge 0} a^n\) of the cycle weight (Mohri, 2002), and this bound makes the series converge for every value of the parameters (§5). A bound of \(1\) on each rule separately would not suffice: interlocking cycles, such as an introduction and an elimination rule over nested constructors, can diverge when each single cycle has weight below one.

2.4 Production probabilities (normalize=lhs)

With the deduction option normalize=lhs, the rules and the lexicon entries are the productions \(p\) of a grammar, each with a left-hand side \(\mathrm{lhs}(p)\): the category of a span conclusion or of a lexical axiom, and otherwise the conclusion with its position slots erased. Each production has a log weight \(\phi_p\), its learnable parameter or \(0\) when it is not learnable, and is used with the weight

\[ \theta_p = \phi_p - \log \sum_{q \,:\, \mathrm{lhs}(q) = \mathrm{lhs}(p)} e^{\phi_q}, \]

so that \(\sum_{q : \mathrm{lhs}(q) = A} e^{\theta_q} = 1\) for every left-hand side \(A\), and the deduction is a probabilistic context-free grammar (PCFG) (Booth and Thompson, 1973). The groups must be fixed by the declaration: no rule has a category variable, parent, or bounded, the lexicon categories are ground, items carry no logical forms, the axioms come from a lexicon, and the semiring is LogProb or Viterbi. Any other deduction with this option is a compile error. The checked elaboration computes the same \(\theta_p\) from the parameter reads of each group.

3. Semirings

The semiring option chooses \(K\):

semiring \(\oplus\) \(\otimes\) Chart value at the goal
LogProb (default) log-sum-exp \(+\) log of the total weight of all derivations
Viterbi \(\max\) \(+\) log weight of the best derivation
Boolean or and whether a derivation exists
Counting \(+\) \(\times\) number of derivations

LogProb is the log semiring, Viterbi the max-plus semiring, and Counting the counting semiring (Semirings, t-norms, and change of base). They are the instances of the class ChartSemiring that a deduction accepts, members of the same hierarchy as the Algebra instances that compose morphisms (Semirings, t-norms, and change of base §5), so a chart sums by the semiring's own \(\oplus\). The same rules give the answers in the last column under the different semirings, as in semiring parsing (Goodman, 1999). A value of semiring outside these four is a compile error that lists the four.

4. Binders, logical forms, and axioms

4.1 Binders

A deduction may list constructors whose first argument is a bound variable:

deduction D : A -> B
    atoms NP, S, Bwd, App, Var, bark
    binders Lam
    ...

For \(c \in \mathsf{binders}(D)\), the items \(c(x, t)\) and \(c(y, t[x := y])\) are alpha-equivalent: they differ only in the name of the bound variable. The compiler renames every bound variable of a lexicon logical form to the canonical name of its de Bruijn level, the number of binders outside it,

\[ c(x, t) \longmapsto c(\mathsf{v}_k, t[x := \mathsf{v}_k]) \qquad \text{at level } k, \]

where \(\mathsf{v}_k\) is a name no source identifier can spell. Two logical forms that differ only in the names of their bound variables thus build the same item, and equality of items in the chart is alpha-equivalence of the source terms. Nested binders get distinct levels, so an inner variable is never confused with an outer one. The bound names of the lexicon are added to the symbols of the deduction while its logical forms are compiled, so they need not be listed in atoms. A use of a bound name outside its binder is rejected, unless the same name is also a declared constant, and a binder whose first argument is not a variable is rejected.

The runtime represents the two kinds of leaf differently:

Source term Runtime term
constant dog_p or dog_p() ("atom", "dog_p")
bound variable x ("var", "#v0") after renaming, at level 0
application App(f, x) ("App", f_term, x_term)

A rule pattern that mentions dog_p has the same runtime shape as dog_p in a lexicon, inline or read from a file. The tags atom and var are reserved and cannot be declared in atoms. Because bound variables are named by level, different forms reuse the same names, and subst(t, v, w) thus renames binders apart wherever a name would otherwise be captured (§9.3).

A rule's patterns may use binders too, in a premise or in a conclusion. The name a binder binds in a rule is no pattern variable: it is bound by the binder and scoped over the binder's other arguments, so a conclusion may introduce an abstraction no premise matches, as composition does:

rule fc : span(I, K, Fwd(X, Y), F), span(K, J, Fwd(Y, Z), G)
       |- span(I, J, Fwd(X, Z), Lam(z, App(F, App(G, Var(z)))))

Each application builds its own abstraction. The matched terms \(F\) and \(G\) are closed, and placing them under the new binder moves their own binders one level in, so the conclusion is renamed to level-canonical form when it is built: composing twice gives the same item as the alpha-equivalent form written by hand, and no variable of \(F\) or \(G\) is captured. The reference machine keeps bound variables as de Bruijn indices, the number of binders between an occurrence and its own, which a closed term keeps under any binder, so it builds the conclusion as written; both engines identify exactly the alpha-equivalent items. A term matched under \(k\) binders refers to them by number, so the rule must use it under \(k\) binders, or outside every binder, where its references to them are free: the contraction App(Lam(V, B), A) |- B drops the abstraction and leaves the occurrences of its variable in \(B\) free, alike in both engines. One matched outside every binder holds a closed term and may be used anywhere. A bound name that the rule also uses as a pattern variable outside its binder is refused, as is a binder whose first argument is not a name.

4.2 The shape of span items

A lexicon produces axioms with the lexical category in the fourth slot, and with the logical form (LF) in a fifth slot when some rule binds an LF or the deduction declares binders:

\[ (\mathsf{span}, i, j, \mathit{cat}) \quad\text{or}\quad (\mathsf{span}, i, j, \mathit{cat}, \mathit{lf}). \]

The compiler decides per deduction whether items carry LFs, by looking for a pattern span(I, J, C, F) with four arguments in its rules. In a deduction with LFs, a pattern span(I, J, C) is extended with a fresh LF variable, so both forms match the same items.

4.3 Axioms

The axioms map an input to the weighted items that start the chart. They are given in one of three ways:

  • a lexicon block of entries such as "word" : Cat = lf #[learnable] or "word" : Cat #[entry=word_entry] for category-only span items, looked up by word;
  • lexicon from "path.tsv", the same table read from a file, whose logical forms get the same tagging of constants, renaming of binders, and scope checks as inline entries;
  • the option axioms = m, naming a declared morphism from the input to weighted items.

5. Goal, depth, and convergence

The deduction options start, depth, tolerance, and max_iterations (in the option block of the declaration, as [start=S, depth=2]) fix the goal and bound the evaluation.

start = s declares the start symbol. The goal items are the conclusions \(c(s, \dots)\) of the configured form, such as span(0, n, s) over the whole input of length \(n\).

depth = k bounds the depth of the category in a rule's conclusion, counting each constructor application as one level. A span item has the depth of its category, and positions, constants, bound variables, and integer literals have depth zero. The compiler adds to every rule the side condition that rejects a firing whose conclusion is deeper than \(k\). This bounds the categories that cycles of unary introduction and elimination rules (modal, continuation, residuation) can build. It does not bound the number of rules a derivation uses: a sentence whose derivations use many rules is still parsed in full. The checked QIEC search applies the same measure to the same conclusions.

tolerance = ε controls the evaluation of cyclic rule systems. Under a semiring that is not idempotent, every new derivation of an item adds to its weight, so on a cycle the weight is the limit of a series (§2.3). The agenda stops re-deriving an item once an update changes its weight by at most \(\varepsilon\). The tolerance bounds that update, and the remaining error depends on the weights of the recursive rules. With \(\varepsilon = 0\), the default, any change in a stored weight counts as an update. The checked QIEC search bounds how often a chain of unary rules may revisit an item and raises that bound until two successive goal weights agree or the number of derivations stops growing. The weights are compared within the declared tolerance in rounded arithmetic. A deduction evaluated by its chart compares successive rounds over every item. In rounded arithmetic, weight agreement stops that chart only once more rounds have passed than the chart has items, which shows a cycle. The stop is handled by the deduction's settlement handler, <D>.settle. It certifies the value when the number of derivations stopped growing, so the value sums every derivation, or when the semiring's arithmetic is exact and the two weights agree, since a fixed point reached from below is the least one. A stop by the tolerance in rounded arithmetic, such as under LogProb, certifies nothing: the run raises ContractNotMet, or, with run_deduction(on_failure=FailurePolicy.RETURN_UNESTABLISHED), returns the stopped value as Unestablished together with the report that says why.

max_iterations = N bounds the number of items taken from the agenda, \(10^5\) by default, and the agenda raises an error when it is exceeded.

6. Chart denotation

Write \(D = (I, R, K, \mathrm{ax}, \mathrm{goal})\) for the deduction's items, rules, semiring, axioms, and goal, and fix an input \(x\). The chart is the function \(\alpha : I \to K\) with

\[ \alpha(i) = \bigoplus_{\delta \in \mathrm{Der}(i)} \mathrm{wt}(\delta), \]

where \(\mathrm{Der}(i)\) is the set of derivations of \(i\) from the axioms \(\mathrm{ax}(x)\), and the weight \(\mathrm{wt}(\delta)\) of a derivation is the \(\otimes\)-product of the weights of the axioms and rule instances it uses. Equivalently, \(\alpha\) satisfies

\[ \alpha(i) = a(i) \oplus \bigoplus_{(r, \sigma) \,:\, \pi\sigma = i} \beta_r(\sigma) \otimes \bigotimes_{\ell=1}^{m} \alpha(\pi_\ell\sigma), \]

where \(a(i)\) is the weight of \(i\) among the axioms (\(\mathbf 0_K\) if it is not an axiom), and is \(\mathbf 0_K\) on items with no derivation. When \(\mathrm{Der}(i)\) is infinite, as on a cycle, the sum is the limit of §5, and the equation holds when that limit exists. The denotation of the deduction is

\[ \llbracket D \rrbracket(x) = \bigoplus_{i \in \mathrm{goal}} \alpha(i). \]

Under LogProb it is the log of the total weight of the derivations of the input, which for a PCFG is the log inside probability (Baker, 1979). Under Viterbi it is the log weight of the best derivation, and under Boolean whether the input is in the language.

7. Independence of the evaluation strategy

The agenda processes rule instances in some order. For an acyclic system, every evaluation that processes each item after all items it depends on, and combines every derivation once, computes the chart of §6, whatever the order (Goodman, 1999). For a cyclic system under an idempotent semiring such as Boolean or Viterbi, the chart is the least fixed point of the equation of §6, which exists by the Knaster–Tarski theorem when the weights form a complete lattice and the rules are monotone. For a cyclic system under a semiring that is not idempotent, the chart is the limit of §5, which depends on convergence.

When the system is linear, so that each rule instance has at most one premise on a cycle through its conclusion, the chart has a closed form. recursion.solve splits the derived hypergraph into strongly connected components and solves each as \(M^* b\) or \(b N^*\) through the semiring's closure (Semirings, t-norms, and change of base §6) (Lehmann, 1977), which needs no commutative product. It refuses, with CyclicRefused, a component with an edge that has two premises in it, a component that mixes the two sides under a product that does not commute, and a closure that diverges or that rounding cannot decide.

Plans for the monotone polynomial contract use decomposed Newton when the product commutes. In algebras embedded in the nonnegative reals, the solver certifies the least fixed point with an enclosure. In idempotent algebras with a closure, it computes the least fixed point exactly. It refuses a system whose least fixed point is certified infinite.

Pruning an item removes its derivations from the sum, and stopping early leaves some unprocessed, so neither preserves the chart.

The compiler chooses the agenda from the semiring and the rules: a depth-first agenda for Boolean when some rule has one premise, semi-naive evaluation for Boolean otherwise, and a bottom-up CKY agenda for every other semiring. The runtime class DeductionSystem accepts other agendas, including a priority agenda for best-first and A* search (Knuth, 1977; Klein and Manning, 2003).

8. Gradients

The chart stores its weights as PyTorch tensors, dense for span charts and in a dictionary keyed by item otherwise. Gradients flow from the learnable weights of §2 through every \(\oplus\) and \(\otimes\) the agenda performs. For a cyclic system, the gradient is that of the computed approximation, obtained by differentiating through every iteration up to convergence. The gradient of the log inside weight with respect to the weight of a rule instance is its expected count, which gives the outside weights of the inside–outside algorithm by backpropagation (Eisner, 2016).

9. Charts in program bodies

A program body evaluates a compiled deduction \(D\) with the parse builtin:

let chart = parse(D, sentence)

The value is a chart, whose methods return tensors that carry gradients through the deduction's learnable weights (§2.1):

Method Value
chart.weight(item) \(\alpha(i)\) at the ground item \(i\), an error if \(i\) is not proved
chart.try_weight(item, default) \(\alpha(i)\), or default if \(i\) is not proved, or \(\mathbf 0_K\) if default is omitted
chart.enumerate(pattern) the pairs \((i, \alpha(i))\) for the proved items \(i\) that match the pattern
chart.goal_weight() \(\bigoplus_{i \in \mathrm{goal}} \alpha(i)\)
chart.embedding(item) the vector of an item under the attached encoder, if there is one
chart.attached_loss the sum of the losses declared in attached loss blocks
chart.semiring the semiring \(K\)

A score step adds the goal weight to the program's log joint density:

let chart = parse(D, sentence)
score log_Z = chart.goal_weight()

Under LogProb the score is the log inside weight of the sentence under the deduction's current weights, and stochastic variational inference (SVI) and the No-U-Turn Sampler (NUTS) over the program's parameters reach the deduction's weights through it.

A corpus of independent sentences of one length is one input of one run, a table with one sentence for each element of a plate \(P\):

let chart = parse(D, corpus, P)
score log_L = chart.goal_weight()

and chart.goal_weight() is then \(\bigotimes_{n \in P} \bigoplus_{i \in \mathrm{goal}_n} \alpha_n(i)\), which under LogProb is the log likelihood of the corpus, \(\sum_n \log Z(s_n)\), with \(Z(s)\) the inside weight of the sentence \(s\).

For a grammar normalized by left-hand side (§2.4), the call may bind the production probabilities of each left-hand side \(A\) with more than one production to a program value \(p_A\), a vector over the productions of \(A\) in the order production_groups lists:

let chart = parse(D, corpus, P, ("A", p_A), ("B", p_B))

The chart then uses \(\theta_q = \log p_{A,q} - \log \sum_{q'} p_{A,q'}\) for each production \(q\) of \(A\), which is \(\log p_{A,q}\) when \(p_A\) lies on the simplex, in place of the learned weights, and a production alone in its group has \(\theta_q = 0\). With \(p_A \sim \mathrm{Dirichlet}(\alpha_A)\) drawn in the program, the program's log joint density is \(\sum_A \log \mathrm{Dir}(p_A ; \alpha_A) + \sum_n \log Z(s_n ; p)\), that of a Bayesian PCFG (Johnson et al., 2007). The compiler checks the binding when it lowers the program: each bound label is a left-hand side of several productions, each such left-hand side is bound once, each value is a vector of its group's size, and a value drawn at a sample site comes from a family whose support is the simplex.

9.1 Composing deductions

compose(D_1, D_2) builds a deduction whose axioms are the goal items of \(D_1\) together with the axioms of \(D_2\):

\[ \mathrm{ax}_{\mathsf{compose}(D_1, D_2)}(x) = \mathrm{goalitems}\bigl(D_1(x)\bigr) \cup \mathrm{ax}_{D_2}(x). \]

Its rules, semiring, agenda, and goal are those of \(D_2\), and its parameters are those of both, so the result may be passed to parse and fitted as one system. No associativity or identity law is claimed for compose.

9.2 Sampling sentences

sample_corpus draws sentences of one given length. It enumerates every string of that length over the deduction's vocabulary, computes the goal weight of each, and samples from the softmax of these log weights. Under LogProb this samples exactly from the distribution of sentences conditional on their length, and the cost grows exponentially with the length.

9.3 Builtins

Builtin Type Value
parse(D, x) (DeductionSystem, Input) -> Chart the chart of \(D\) on \(x\)
parse_outcomes(D, x, key) checked rows of keys and log masses the goal log masses grouped by key (§9.4)
parse_normalized_outcomes(D, x, key) checked rows of keys and log masses the grouped goal log masses normalized over their support (§9.4)
compose(D_1, D_2) (DeductionSystem, DeductionSystem) -> DeductionSystem §9.1
subst(t, v, w) (Term, Term, Term) -> Term \(t\) with each subterm equal to \(v\) replaced by \(w\)

Inside a deduction, subst is capture-avoiding substitution with respect to the declared binders (§4.1): when v is a variable, a binder of the same variable shadows it, a binder whose variable is free in w is renamed apart before w is placed under it, and the result is renamed back to level names, so alpha-equivalent results are identical. Another v is replaced at every subterm equal to it. Outside a deduction no constructor binds, and subst replaces subterms by structure.

9.4 Checked weighted outcomes

For a checked lexical LogProb deduction on a sentence \(x\), let \(G_x\) be its finite set of proved goal items and let \(\alpha(g)\) be the inside log mass of \(g \in G_x\). A key \(h\) maps a goal item to its form, category, or full item, or invokes a checked deterministic computation that returns a supported discrete value. Each returned row \((u, \ell(u))\) has log mass

\[ \ell(u) = \operatorname{logsumexp}_{g \in G_x\, :\, h(g)=u} \alpha(g). \]

The sum retains each proof occurrence through its contribution to \(\alpha(g)\), including when several goals have equal keys. The query omits rows with log mass \(-\infty\). The normalized query subtracts \(\operatorname{logsumexp}_u \ell(u)\) from every row and requires a finite normalizer. On fixed positive support these operations retain derivatives with respect to the deduction weights.

The checked lexical fragment uses contiguous premises and orders dependencies by the pair of span width and category rank. A premise can preserve the width when the other premises are empty. The category rank must increase on every such transition, including transitions of rules with several premises. The finite grounding and this strict order justify computing \(\alpha\) from the packed chart before grouping the goal items.

9.5 Checked proof interpretations

For each goal \(g \in G_x\), let \(P(g)\) be its set of ordered proof trees, with a separate occurrence for each rule or axiom occurrence in the grounded chart. The same strict order makes every \(P(g)\) finite. The structural count of a chart item is the sum over its incoming occurrences of the product of the premise counts. An axiom contributes one, by the empty-product convention. A proof query checks the sum of the goal counts against its budget before constructing any proof values. This check includes occurrences with zero weight.

A checked interpretation assigns to each rule or axiom occurrence an operation on the interpreted premises in their stated order and the constructor's ordinary fields. For an occurrence with operation \(F_r\), fields \(\mathbf{v}\) and subproofs \(p_1,\ldots,p_k\), the pure interpretation is defined by

\[ I\bigl(r(\mathbf{v};p_1,\ldots,p_k)\bigr) = F_r\bigl(I(p_1),\ldots,I(p_k),\mathbf{v}\bigr). \]

A proof-dependent outcome query with pure discrete key \(h\) returns log mass \(\operatorname{logsumexp}_{g \in G_x,\,p \in P(g):\,h(p)=u} \log w(p)\) for each supported key \(u\), where \(w(p)\) is the product of the occurrence weights in \(p\). Grouping partitions the positive-weight proof occurrences. Summing over the keys thus recovers the total mass of the same goals in §9.4. A normalized query divides by that mass when it is positive.

A reindexed interpretation first maps the category index of each proof node using its declared index map. The original category remains in the proof type. The mapped category determines the index available to the carrier, so each \(F_r\) is checked against the mapped premise and conclusion indices. For lexical leaves the entry name selects the axiom operation, including when several entries contribute the same chart item. Reindexing preserves the source proof tree and its weight. The developer note states the fold and the relation between source and mapped indices.

10. Grammar of the program and composition forms

The forms below are written in EBNF after the tree-sitter grammar grammars/qvr/grammar.js, which is authoritative. Their semantics is on Programs as kernels, Expressions, and Composition rules.

# The option block is one production read by every declaration and step
# that takes options. A value is a name, a number, a string, a list, or
# one call.
option_block        := '[' option_entry (',' option_entry)* ']'
option_entry        := IDENT [ '=' option_value ]
option_value        := IDENT
                     | INT | FLOAT | STRING
                     | '[' option_value (',' option_value)* ']'
                     | IDENT '(' option_value (',' option_value)* ')'

# The outer pragma decorates the next declaration, the inner pragma the module.
pragma_outer        := '#['  pragma_entry (',' pragma_entry)* ']'
pragma_inner        := '#!['  pragma_entry (',' pragma_entry)* ']'
pragma_entry        := IDENT [ '=' option_value ]

rule_decl           := 'rule' IDENT '[' IDENT (',' IDENT)* ']'
                       ':' type_expr (',' type_expr)* '|-' type_expr
schema_decl         := 'schema' IDENT '[' schema_parameter (',' schema_parameter)* ']'
                       ':' type_expr '->' type_expr
schema_parameter    := IDENT (',' IDENT)* ':' type_expr
# Rule and schema binders range over static category patterns.

deduction_decl      := 'deduction' IDENT ':' type_expr '->' type_expr
                       [ option_block ] NEWLINE
                       INDENT deduction_body_entry+ DEDENT

deduction_body_entry
                    := deduction_atoms
                     | deduction_binders
                     | deduction_rule
                     | deduction_lexicon
                     | deduction_lexicon_from_file

deduction_atoms     := 'atoms' IDENT (',' IDENT)*
deduction_binders   := 'binders' IDENT (',' IDENT)*

deduction_rule      := 'rule' IDENT ':' [ premise_list ] ('|-' | '⊢')
                       conclusion [ '#[' pragma_entry (',' pragma_entry)* ']' ]
# Rule pragma entries: learnable, bounded, parent = IDENT, weight = expr.
lexicon_entry       := STRING ':' lexicon_category
                       ( '=' expression [pragma_outer] | pragma_outer )
# Omitting the logical form requires entry=IDENT and a category-only deduction.

# Deduction options: semiring, start, depth, tolerance, max_iterations,
# axioms, signature, encoder, normalize.

program_static_param := qiec_static_binder
                      | IDENT ':' (object_kind | morphism_kind)
program_value_params := IDENT (',' IDENT)*
                      | program_value_param (',' program_value_param)*
program_value_param  := IDENT ':' qiec_type
object_kind         := 'FinSet' | 'Space' | 'Object'
morphism_kind       := 'Mor' '[' type_expr ',' type_expr ']'

effect_set          := effect (',' effect)*
effect              := 'Sample' | 'Score' | 'Marginal' | 'Pure'

# External values are parameters of the program, not body steps.
# Finite object cardinalities may be '_' for inference when data are bound.

sample_step         := 'let' var_pattern [ ':' type_expr ] '<-' model_operation
                       IDENT [ program_arguments ] [ option_block ]
model_operation     := 'sample' | 'program' | 'apply'
# Model operations respectively draw from a law, instantiate a template,
# and apply a static recipe or morphism parameter.
# Draw options: over, iid_over.

observe_step        := 'observe' IDENT [ ':' type_expr ]
                       '<-' IDENT [ program_arguments ]
                       [ option_block ]
# Observation options: via = idx (an index map into the group of an
# enclosing grouped marginalize), weights, over, iid_over.

program_arguments   := [ '[' program_static_arg (',' program_static_arg)* ']' ]
                       '(' [ draw_arg_list ] ')'
program_static_arg  := IDENT | ['-'] (INT | FLOAT)

score_step          := 'score' IDENT '=' let_arith

call_step           := 'let' IDENT '<-' qiec_call
# Binds the result of a computation declared with `define`; the callee's
# effect row joins the program's. The compiled runtime inlines supported
# calls; other checked calls run on the reference machine. Tensor extents
# may be inferred from the actual arguments' types.

marginalize_step    := 'marginalize' IDENT [ ':' type_expr ] '<-' IDENT
                       [ program_arguments ]
                       [ option_block ]
                       NEWLINE INDENT program_step+ DEDENT
# Options: over = G, over = product(G_1, ...), or over = [G_1, ...] for the
# group set, and reduction = logsumexp | sum | mean (default logsumexp).

let_index           := IDENT '[' let_arith (',' let_arith)* ']'

program_decl        := 'program' IDENT
                       [ '[' program_static_param (',' program_static_param)* ']' ]
                       [ '(' [ program_value_params ] ')' ]
                       ':' type_expr '->' type_expr
                       [ option_block ]
                       NEWLINE INDENT program_step* return_step DEDENT
# Options: effects = [E_1, ..., E_n], and over = M for a program over the
# posterior draws of the model M.

composition_decl    := 'composition' IDENT
                       [ option_block ]
                       [ NEWLINE INDENT composition_rule_entry+ DEDENT ]
# Option: level = algebra | semigroupoid | magmoid | rule.

composition_rule_entry
                    := IDENT '(' IDENT (',' IDENT)* ')' '=' let_arith
                     | IDENT '=' let_arith

contraction_decl    := 'contraction' IDENT
                       '(' contraction_input (',' contraction_input)* ')'
                       ':' type_expr '->' type_expr
                       [ option_block ]
# Options: rule = IDENT (required), wiring = STRING.

contraction_input   := IDENT ':' type_expr '->' type_expr

trans_compose       := expr '>>>' expr
change_base_postfix := expr '.' 'change_base' '(' expr ')'
morphism_call       := IDENT [ '[' program_static_arg (',' program_static_arg)* ']' ]
                       '(' IDENT (',' IDENT)* ')'
                     | IDENT '[' program_static_arg (',' program_static_arg)* ']' '(' ')'

A program's static telescope uses the QIEC binders for types, effects, and indices, with additional object and morphism kinds. Its runtime telescope provides values at the resulting types. A bare runtime parameter names a component of the domain; a typed parameter declares an external input. A typed runtime parameter alone does not make a program a static template. The compiler expands a static template at a specialized call site (Programs as kernels §3.2). The option effects is checked as in Programs as kernels §2.8, and over = M declares a program over the posterior draws of M, whose latent variables become parameters of the program. The composition declaration is described on Composition rules §3. A program call uses IDENT[static_arguments](value_arguments), omitting brackets when it has no explicit static arguments. A call IDENT(arg_1, ..., arg_n) is resolved against the contractions, the parametric programs, and the morphisms of the module, in that order (Expressions §2.13). In a morphism expression, runtime actuals are names. An explicit static list also permits an empty runtime list, as in define fixed = prior[3](). A bare nullary form such as Flow() retains its distribution-family interpretation.

11. QIEC fragment

The Quivers Indexed Effect Core (QIEC) adds its own declarations and computations to the module grammar (Typing and checking). A telescope is an ordered list of binders in which later types may mention earlier variables (de Bruijn, 1991). Square brackets bind static types, indices, or effect interfaces, and parentheses bind family indices or computation and program values. Family indices remain static, refinable type information. The EBNF below is abridged, and grammars/qvr/grammar.js is authoritative:

index_decl        := 'index' IDENT '=' index_constructor ('|' index_constructor)*
index_map_decl    := 'index' 'map' IDENT ':' index_sort '->' index_sort NEWLINE
                     INDENT index_map_clause+ DEDENT
index_map_clause  := IDENT ['(' IDENT (',' IDENT)* ')'] '=>' index_term NEWLINE
static_telescope  := '[' qiec_static_binder (',' qiec_static_binder)* ']'
qiec_static_binder := IDENT ':' ('Type' | 'Effect' | index_sort)
index_telescope   := '(' qiec_index_binder (',' qiec_index_binder)* ')'
qiec_index_binder := IDENT ':' index_sort
family_decl       := 'family' IDENT [static_telescope] [index_telescope]
                     ':' KIND constructor_decl+
constructor_decl  := 'constructor' IDENT [static_telescope] ':'
                     [type ('*' type)* '->'] type

reindexed_interpretation_decl
                  := 'interpret' IDENT '[' 'reindex' '=' IDENT [',' 'mapped' '=' IDENT] ']' ':'
                     IDENT '->' type NEWLINE INDENT interpretation_clause+ DEDENT
interpretation_clause := ('rule' | 'axiom') IDENT '=' IDENT NEWLINE

effect_decl       := 'effect' IDENT [static_telescope] operation_decl+
operation_decl    := IDENT [static_telescope] ':' [type ('*' type)* '->'] type
instance_decl     := 'instance' IDENT ':' effect_ref
handler_decl      := 'handler' IDENT [static_telescope] 'for' effect_ref ':'
                     type '->' type ['with' '(' value_params ')']
                     [handler_options] handler_clause+
handler_clause    := return_clause | operation_clause
return_clause     := 'return' local '=>' computation
operation_clause  := IDENT [static_telescope] ['(' local (',' local)* ')']
                     'resumes' grade ['=>' computation]
grade             := '0' | 'aff' | '1' | 'omega'

computation_decl  := 'define' IDENT [static_telescope] ['(' [value_params] ')']
                     ':' type effect_row '=' computation
effect_row        := '!{' [IDENT (',' IDENT)*]
                     ['|' IDENT ['lacks' IDENT (',' IDENT)*]] '}'
computation       := 'return' value
                   | 'let' local '=' value computation
                   | 'let' local '<-' inline computation
                   | inline computation
                   | 'handle' IDENT 'with' handler_application 'in' computation
                   | 'with' 'instance' IDENT ':' effect_ref 'in' computation
                   | 'case' value 'motive' [index_telescope] '=>' type branch+
                   | 'if' expression 'then' computation 'else' computation
inline            := perform | call | resume
value             := 'construct' IDENT [static_arguments] '(' [value (',' value)*] ')'
                     'as' type
                   | expression
expression        := expression binop expression | ('-' | 'not') atom | atom
atom              := IDENT | NUMBER | STRING | 'true' | 'false' | 'unit'
                   | '(' expression ')'
                   | '(' expression ',' expression (',' expression)* ')'
                   | IDENT '[' INT ']'
                   | IDENT '(' [expression (',' expression)*] ')'
binop             := '||' | '&&' | '==' | '!=' | '<' | '<=' | '>' | '>=' | '+'
                   | '-' | '*' | '/' | '%'
perform           := 'perform' IDENT '.' IDENT [static_arguments]
                     '(' [value (',' value)*] ')'
call              := IDENT [static_arguments] '(' [value (',' value)*] ')'
resume            := 'resume' '(' [value] ')'
                     ['with' '(' value (',' value)* ')']
handler_application := IDENT [static_arguments] ['(' value (',' value)* ')']
static_arguments  := '[' static_argument (',' static_argument)* ']'
static_argument   := type | INT

A static argument is type syntax, read as a type or an effect according to the binder it fills, or an integer literal, which fills a Nat index: pad[3](xs) applies a computation declared define pad[n : Nat](xs : Real[Fin n]) ... at extent three. The grade of an operation clause is its resumption grade, the number of times the clause may resume its continuation: never (0), at most once (aff), exactly once (1), or any number of times (omega) (Atkey, 2018).

Calls, requests, and constructors

Three forms have the shape NAME(...), and their position or a qualifier separates them: a call is NAME(...) in computation position, an effect request is perform inst.op(...), qualified by its effect instance, and a constructor value is NAME(...) in value position, where the name is a constructor. Explicit static arguments, NAME[...](...), and an annotation, (VALUE : TYPE), are value forms of their own. A handler clause resumes its continuation with resume, a keyword and not a bound name.

Patterns

A case branch head and a destructuring let hold a pattern. Its forms are _, a name with an optional type, a constructor applied to sub-patterns with optional static names C[k](p, q), a literal, a tuple, a record {l = p, m, ..}, an or-pattern p | q (the loosest form), an as-pattern p as x, and, as a constructor argument only, a binder pattern x y. p. _, |, and as have these meanings only where a pattern is parsed, so _ remains a name elsewhere. A branch may follow its pattern with a guard if VALUE. pattern NAME(x, ...) = PATTERN declares a synonym at the top level; pattern is a keyword only there.

Bindings

let x = VALUE binds a pure expression and let x <- COMPUTATION binds the result of a computation. They are separate productions with separate typing rules.

Pure expressions

QIEC values and the let and score steps of programs share one expression grammar. From loosest to tightest, the operators are ||, &&, comparison, + -, * / %, and the unary - and not, and operators of equal precedence associate to the left. A comparison with a negative literal needs parentheses, x < (-1), because <- is the binding arrow.

In a QIEC value each operator resolves by the type of its operands to one primitive of the closed registry, and both operands must have the same type: + is integer or real addition or string concatenation, % is integer only, == and != compare integers, reals, Booleans, or strings, and &&, ||, and not take Booleans. Integer division and remainder truncate toward zero on every target. The builtins real, int, exp, log, sqrt, pow, abs, min, and max resolve the same way. A tuple (a, b) builds a finite product, and t[i] with an integer literal selects a component. A list literal [a, b, c] is a Tensor whose leading dimension is its number of entries and whose entries share one type, so [[1.0, 2.0], [3.0, 4.0]] is a Real[Fin 2, Fin 2], and a numeric list with any fractional entry is real. A family application such as Normal(loc=mu, scale=1.0) or Dirichlet(concentration=[1.0, 2.0]) selects a complete parameterization by name and evaluates the arguments in source order to build a Sampleable. site("x") is a Site at the type its position expects, and log_prob(d, x) is the LogWeight of d at x. log_mass(d) is a pure structural query returning its total LogWeight; its argument has type Sampleable[A] for any checked outcome type A.

The migration from v0.71.0 reads the predecessor's checked value fields and family schemas. If the predecessor matched its \(i\)th operand to the semantic field \(p_i\), the migration inserts the corresponding source name immediately before that operand. The checker then reads the same ordered sequence of semantic fields and expressions. This preserves the checked family identity, each operand's evaluation, and the first error in that sequence.

The outer call in a traverse callback resolves in the computation namespace. Its arguments still resolve in the value namespace. If a stored callback uses one call as both a computation and a family value, the migration reports the call's location for a source-level split into two callbacks.

if COND then ... else ... branches on a Boolean in a computation, so the untaken branch is never entered, and a recursive computation can stop.

Site estimator policies

effect_law for NAME is followed by an indented list of one or more estimator POLICY at "SITE" = METHOD rows. NAME is the lexical owner of the sample requests named by the rows. A row resolves its label against a direct Random request in that computation and retains the request's static site identity. The ordered policies guide a derivative planner after checking.

Layout

A construct that takes a nested computation opens an indented block after a trailing => or in: handler clauses, case branches, handle ... in, and with instance ... in. An inline computation (a call, a request, or a resumption) takes one line and is followed by the rest of the computation at the same indentation.

Authored and foreign handlers

An operation clause with a => body is authored. A clause without one is a signature, and its handler must say [implementation=foreign], so that a missing body never means "look up a callback at run time". A foreign handler's clause behavior is given at run time by a provider, an arrangement close to a foreign function interface. In the elaborated core, a foreign handler may declare what its clauses compute as data on its declaration, HandlerDef.foreign: the enumeration of a finite draw, or a semiring sum, a semiring product, or a settlement, each of the last three naming its semiring as a KernelSemiring. The runtime builds such a handler from that declaration and the laws the semiring establishes, never from the handler's name, and refuses a semiring that does not establish the laws the handler relies on. The handlers of a deduction \(D\) are declared this way: D.search sums the derivations, D.collect multiplies the weights of one derivation, and D.settle settles an iteration (§5). The full grammar, worked examples, and limits are in the QIEC developer note.

Authored sparse relations

A relation introduces a finite control graph over ordered string tapes, each typed by a nominal finite alphabet. The input tapes come first. An arc carries one symbol or eps on each tape. The initial and final tables assign a weight to each marked state. The relation sums the weights of all accepting paths realizing a word tuple. Multiple identically labeled arcs contribute as separate occurrences even when their weight names resolve to one parameter.

A declaration of the form relation target = compose(left, right) names a binary composition of two authored relations. The operand order specifies the tape to synchronize. The two shared tape types and the scalar algebras must agree. The composed relation exposes a pair_weight score.

The right-hand side of an authored relation can also name a sparse transformation. Inversion, trimming, and closure take one operand. Projection takes its increasing tuple of retained tape positions and conditioning takes one tape position and a fixed word. Union, concatenation, and weighted intersection take two operands. A join also specifies the two shared tape positions and can retain the shared tape with keep_shared=true. Operands may refer to other relation declarations. Forward references are allowed when their dependency graph is acyclic.

A string_graph declares nominal variables and ordered occurrences of sparse factors. A variable can supply a fixed word, including the empty word. Each factor names a primitive or derived relation and lists one distinct variable per tape. A typed score binding can name this graph as the operand of a tree query.

A typed score binding may name the authored relation it uses. Its identity then binds the ordered topology, scalar algebra, and weight identities. The host supplies the observation and a checked binding of those parameters. Path entropy and additive expected loss are taken under the normalized distribution over accepting paths when that distribution has positive finite mass.

String graph scores

A typed binding for a tree query declares a closed scalar computation. Its attached graph has a weight \(F_f(\mathbf{w}_f)\) for each factor \(f\) and a partial assignment \(e\) of observed words. The exact tree request computes

\[ Z(e) = \sum_{\mathbf{w}\supseteq e}\prod_f F_f(\mathbf{w}_f). \]

The operation tree_partition returns this sum in the graph's algebra. The operation tree_log_prob at variable \(v\) and word \(w\) returns \(\log Z(e, v=w) - \log Z(e)\) when the normalizer is positive and finite. Sparse evaluation admits a forest when each local operation and any productive closure meet the request's limits. The generated foreign handler carries the objective in its identity, and the provider checks that identity alongside the declared scalar type. String graph requests

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/.

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.

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. Parsing and Hypergraphs. In Proceedings of the Seventh International Workshop on Parsing Technologies, 123–134. 2001. URL: https://aclanthology.org/W01-1812/.

Mehryar Mohri. Semiring Frameworks and Algorithms for Shortest-Distance Problems. Journal of Automata, Languages and Combinatorics, 7(3):321–350, 2002. doi:10.25596/jalc-2002-321.

Taylor L. Booth and Richard A. Thompson. Applying Probability Measures to Abstract Languages. IEEE Transactions on Computers, C-22(5):442–450, 1973. URL: https://doi.org/10.1109/T-C.1973.223746, doi:10.1109/T-C.1973.223746.

J. K. Baker. Trainable Grammars for Speech Recognition. The Journal of the Acoustical Society of America, 65(S1):S132, 1979. doi:10.1121/1.2017061.

Daniel J. Lehmann. Algebraic Structures for Transitive Closure. Theoretical Computer Science, 4(1):59–76, 1977. URL: https://doi.org/10.1016/0304-3975(77)90056-1, doi:10.1016/0304-3975(77)90056-1.

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.

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. Inside-Outside and Forward-Backward Algorithms Are Just Backprop. In Proceedings of the Workshop on Structured Prediction for NLP, 1–17. Association for Computational Linguistics, 2016. doi:10.18653/v1/W16-5901.

Mark Johnson, Thomas Griffiths, and Sharon Goldwater. Bayesian Inference for PCFGs via Markov Chain Monte Carlo. In Human Language Technologies 2007: The Conference of the North American Chapter of the Association for Computational Linguistics; Proceedings of the Main Conference, 139–146. Rochester, New York, 2007. Association for Computational Linguistics. URL: https://aclanthology.org/N07-1018/.

N. G. de Bruijn. Telescopic Mappings in Typed Lambda Calculus. Information and Computation, 91(2):189–204, 1991. doi:10.1016/0890-5401(91)90066-B.

Robert Atkey. Syntax and Semantics of Quantitative Type Theory. In Proceedings of the 33rd Annual ACM/IEEE Symposium on Logic in Computer Science (LICS), 56–65. 2018. doi:10.1145/3209108.3209189.