Skip to content

Generated computation graphs

Several QVR declarations elaborate to definitions of the Quivers Indexed Effect Core (QIEC) that the declaration does not spell out. Elaboration may add families, instances, handlers, and helper computations, and every generated definition is typed, visible to the tooling, and carries the source range of the declaration it came from, so a diagnostic in generated code points to the source line.

What each declaration generates

Source declaration Principal QIEC graph Runtime requirement
program one computation over the built-in random and score instances, with helpers for marginalization and scans the core handlers, and any model attachments
deduction a family of items, a recursive derivation, Search, Settle, Weight[K], Param, the search, collection, and settlement handlers, and a run entry the core search, semiring, and parameter providers
interpret a checked case fold over a lexical deduction's indexed proof family the named effects of the rule and axiom operations
define p = parser(...) a finite family of items and a deduction instantiated from rule schemata and bundles, searched from the goal the search runtime of a deduction
syntax a checked family per object sort, its term operations, and, with oriented equations, its normalizer (Object languages) none: the families and operations are ordinary checked code
judgment a checker, inferencer, and chart over the syntax's terms, run on the host (Object languages) the agenda engine of the deduction runtime
encoder a typed Compute[Term, Code] request and a named computation an attached PyTorch encoder
decoder a typed Compute[Code, Term] request and computations for the negative log-likelihood an attached PyTorch decoder
loss a named computation that calls its encoder and decoder the attachments the loss reaches

The compiler names generated members by their parent and member path, as in G.Item, G.run, G.read_goal.Outcomes, and p.x_corpus. Source names a member the same way and can qualify it through imports, as in L.G.Item (qualified names). An explicit splice can introduce a top-level declaration instead.

Program.entry_points() lists the public entry points of a compiled module. The generated helpers are visible in the checked module, but their names are not part of the interface, and a caller selects a documented entry.

Deduction declarations

A weighted deduction system is a set of inference rules over items, each derivation carrying a weight combined in a semiring (Shieber et al., 1995; Goodman, 1999; Nederhof, 2003). A deduction elaborates to a search computation whose weights are interpreted in the declared semiring. For a span grammar, elaboration creates:

  1. a family of items with constructors for atoms, applied symbols, and positions;
  2. a recursive derivation that chooses an axiom or an applicable rule and recurs on smaller spans (on smaller yields, for items with several spans), with a closure computation for unary rules and, when depth is declared, a computation that bounds the depth of each conclusion's category;
  3. computations for structural equality and display of items;
  4. a Search instance for the alternatives;
  5. a Weight[K] instance for the rule and lexical weights;
  6. a Param instance for learned weights;
  7. three handlers, each declaring what it computes in the semiring: <D>.search answers the semiring sum over the alternatives of a choice, <D>.collect the semiring product of the weights a derivation adds, and <D>.settle the value at which an iteration stops, when the stop certifies it (foreign handler semantics); and
  8. a run computation that installs these handlers.

Pattern variables shared between premises are checked by structural equality after the recursive premises return, and a failed match performs an empty choice. A learned lexical or rule weight is read from Param under the stable name that the agenda-based chart parser of the compiled runtime in quivers.stochastic uses (Eisner et al., 2005), so the two share one parameter store.

Under normalize=lhs, the rules that share a left-hand side are normalized as a group (production probabilities). Each left-hand side with several productions, at least one of them learnable, gains a computation <D>.lhs<i>. It reads the free weights of those productions from Param and returns their log-sum-exp, computed relative to the largest. Each rule and lexicon entry then adds its own free weight minus that normalizer, which is its entry of the group's log_softmax.

When a program binds the grammar's production probabilities, the deduction is elaborated a second time. <D>.weighted_axiom, <D>.weighted_derive, and the other computations that read weights take a table of the productions' log probabilities as their last argument and read each weight from it, and <D>.weighted_run is the entry the program calls. A program that parses a corpus gains a helper <program>.<let>_corpus that calls the entry on each sentence and multiplies the answers in the semiring.

The result type follows the semiring: a LogWeight for LogProb and Viterbi, a Bool for Boolean, and an Int for Counting. run_deduction returns the goal's inside weight, the semiring sum over all derivations of the goal of the product of their rule weights (inside algorithm) (Goodman, 1999). Depending on the deduction's shape, it accepts tokens, explicit axioms, axiom weights, and parameter values. A deduction whose derivations may repeat an item iterates, and its stop is certified when no further derivation was found, or when the arithmetic is exact and two iterates agree. A stop at the declared tolerance, or in rounded arithmetic while derivations still grow, raises ContractNotMet, and run_deduction(..., on_failure=FailurePolicy.RETURN_UNESTABLISHED) returns it as an Unestablished value instead. A program that calls the deduction refuses such a stop.

The proof interpretation declaration generates an ordinary checked computation. Its type takes a proof at the deduction's indices and returns the declared carrier. Its effect row follows from the operations assigned to the proof constructors.

A reindexed interpretation also generates its own proof rows. If the interpretation is named meaning, the family is meaning.Proofs and its constructors are meaning.proof_end and meaning.proof_entry. Each entry carries the source proof indices, the mapped category index, the proof, its weight, and the remaining rows.

The weighted deduction guide and the parsing tutorial build deductions step by step.

Parsers from rule schemata

parser(rules=[...], terminal=Token, start=S, depth=n) builds a parser from rule schemata, rule templates with pattern variables (Shieber et al., 1995). It instantiates the schemata over the finite set of syntactic categories built from the atoms of the declared FreeResiduated object with its connectives (by default the slashes / and \), nested up to depth n, as in the Lambek calculus (Lambek, 1958; Moortgat, 1997). It then lowers the resulting rules to the same graph of search and weights as a deduction.

A schema's category variables are static binders, written in brackets: schema apply[X, Y : Cat] : (X / Y) * Y -> X. A top-level rule uses the corresponding untyped pattern list, as in rule apply[X, Y] : X / Y, Y |- X. Matching substitutes categories for these variables before applying a rule instance. These declarations thus share the static-bracket convention of programs and computations, without introducing runtime value parameters.

The compiled runtime's ChartParser and the QIEC entry share their lexical and rule weights and compute the same inside weight, bounded by depth. The ChartParser fits by batched PyTorch optimization, and the well-typed computation gives effect handling, entry point execution, stable serialization, and target diagnostics.

A target without the search runtime reports qiec:capability:search:<entry>. A parser that another program in the module calls is kept, and the reachable call graph determines whether a target can emit the model.

Structural signatures and autoencoders

A checked module can give the type of a neural computation without containing the network. It holds an attachment descriptor, a typed reference to an implementation, and a runtime provider gives the PyTorch object when the module runs. Saving the checked module thus saves neither the learned parameters nor a runnable Python module, and both are given at invocation.

A syntax declares typed terms: data leaves, recursive constructors whose arguments may bind variables, and variables written as de Bruijn indices. Each object sort S of a syntax Σ lowers to an ordinary checked family Σ.S with the variable constructor Σ.S.var, together with the generated term operations (Σ.S.shift, Σ.S.subst.V, Σ.S.instantiate.V, Σ.S.occurs, Σ.S.eq, Σ.S.ord, Σ.S.hash, Σ.S.show) and, when its equations have oriented rules in the supported fragment, Σ.S.rewrite, Σ.S.normalize, and Σ.S.equal_modulo (Object languages). These are checked computations like any define, so every target that runs the core runs them.

An encoder or a decoder becomes a Compute instance and a named computation. For the term autoencoder:

reconstruct(term)
  -> Enc.apply(term)
  -> Dec.nll.apply((term, code))
  -> LogWeight

Program.run("reconstruct", term) attaches the compiled torch.nn.Module objects, validates the Python values against the checked input and output types, and keeps the autograd graph. The encoder and decoder are registered under stable module names derived from the source, so parameters(), named_parameters(), and state_dict() include them.

A process that deserializes the module attaches compatible providers before it invokes an entry that needs them. A transpile target without such a provider refuses the entry with qiec:capability:neural-attachment:<entry>.

The tree autoencoder tutorial and the Term Autoencoder example build one end to end.

Programs that call generated entries

Generated entries compose through ordinary calls. A program can call a deduction:

import std.semiring

object Term : FinSet 16
object Weight : Real 1

deduction AB[S = std.semiring.LogProb] : Term -> Term [start=S, depth=6]
    atoms S, NP, N, Fwd, Bwd, span, the, dog, runs
    rule fwd_app : span(I, K, Fwd(X, Y)), span(K, J, Y) |- span(I, J, X) #[learnable]
    rule bwd_app : span(I, K, Y), span(K, J, Bwd(X, Y)) |- span(I, J, X) #[learnable]
    lexicon
        "the" : Fwd(NP, N) = the #[learnable]
        "dog" : N = dog #[learnable]
        "runs" : Bwd(S, NP) = runs #[learnable]

program fit : Term -> Weight
    let chart = parse(AB, sentence)
    score evidence = chart.goal_weight()
    return evidence

export fit

Elaboration replaces the goal_weight() access with a call to the deduction's run computation and a request to score. The features a target must support for fit thus include search, weight accumulation, parameter lookup when weights are learned, and the probabilistic effects of the program's other steps.

Inspect the generated graph

From the least to the most detailed:

qvr run model.qvr --list
qvr repl model.qvr
# then: :info entry
#       :effects entry
#       :dump entry --json
#       :graph program --mermaid

In Python, program.entry_points() gives the public entries and program.qiec gives the checked module. The entries are invoked, and the helpers in program.qiec show how they were compiled.

Target requirements

A generated computation can require a feature that no single source line shows: parser(...) requires search, and a loss over a decoder requires neural attachments. The diagnostic names the reachable computation and keeps its source range. qvr check --target TARGET, or a target set in the language server, reports these requirements while the source is edited, and qvr transpile then reports any restriction particular to the target's renderer.

Typed score bindings

A typed score binding names a zero-argument computation whose operation selects the request that the runtime provider must implement. The operand identifies a declared relation or string graph. With empty parentheses, the runtime provider determines which relation or graph the computation uses.

The model below declares a relation edit and a graph chain whose observed word is (1), and binds three scores over them:

object Letters : FinSet 2

relation edit [algebra=markov, states=2]
    input Letters
    output Letters
    initial 0 [weight=one]
    arc 0 -> 1 [labels=(0, 0), weight=same]
    arc 0 -> 1 [labels=(0, 1), weight=different]
    arc 0 -> 1 [labels=(1, 1), weight=same]
    final 1 [weight=one]

string_graph chain
    variable source : Letters
    variable observed : Letters [observed=(1)]
    factor edit(source, observed)

define invoke() : Real !{} =
    pair()

#! Pair weight for the fixed channel.
define pair : Real = pair_weight(edit)
define evidence : Real = tree_partition(chain)
define likelihood : LogWeight = conditional_log_prob()

The three entries return the pair weight, the graph's partition and the log conditional probability. The same runtime parameter bindings serve all three queries.

qvr migrate --from legacy-score-heads model.qvr rewrites source in the legacy-score-heads grammar, which declares each score with its own head, into these bindings, and --from weighted-total-long reads the grammar whose handler clauses spell resumption in full. Each rewrite keeps the score operation, the result type, and any named relation or graph.

from math import isclose, log
from pathlib import Path

import torch

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    CoreRuntimeProvider,
    FixedRelationRequest,
    FixedRelationRuntimeProvider,
    ParameterId,
    RuntimeConfiguration,
    TreeStringGraphRequest,
    TreeStringGraphRuntimeProvider,
    host_value,
    run_named,
)

path = Path("docs/examples/qiec/typed-score-bindings.qvr")
compiler = Compiler(parse(path.read_text()), module_name="typed_scores")
module = compiler.qiec_module
assert module is not None
parameters = {
    ParameterId.derive("typed_scores", "relation_weights", name): (
        torch.tensor(value, dtype=torch.float64)
        if name == "one"
        else torch.nn.Parameter(torch.tensor(value, dtype=torch.float64))
    )
    for name, value in {"one": 1.0, "same": 0.5, "different": 0.25}.items()
}
pair = FixedRelationRequest(
    relation=compiler.relation_specs["edit"],
    operation="pair_weight",
    words=((0,), (1,)),
    max_states=60,
    max_work=180,
)
tree = TreeStringGraphRequest(
    graph=compiler.string_graph_specs["chain"],
    variable="source",
    max_states=60,
    max_work=180,
)
runtime = RuntimeConfiguration(selections=(), providers=(
    CoreRuntimeProvider(),
    FixedRelationRuntimeProvider.for_score("pair", pair, parameters),
    TreeStringGraphRuntimeProvider.for_score("evidence", tree, parameters),
    FixedRelationRuntimeProvider.for_score(
        "likelihood", pair.with_(operation="conditional_log_prob"), parameters
    ),
))
for name, expected in (("pair", 0.25), ("evidence", 0.75), ("likelihood", log(1 / 3))):
    assert isclose(host_value(run_named(module, name, runtime=runtime).value), expected)

Fixed-word relation scores

A typed binding for a fixed-word relation score exposes a zero-argument computation. Pair weights have type Real for Markov or LogWeight for LogProb. A conditional log probability has type LogWeight. Path entropy and expected additive costs return Real.

define paired_words : Real = pair_weight()
define output_likelihood : LogWeight = conditional_log_prob()

Each declaration elaborates to a checked computation that installs a foreign Compute handler. In the reference machine, FixedRelationRuntimeProvider.for_score serves that handler with a serialized FixedRelationRequest and the original scalar parameters indexed by identity. The provider checks the operation and result type against the declaration. The request supplies the topology, observed words, and construction limits. The wire and runtime contract describes the operations and their wire records.

Stan, BUGS, and JAGS report the foreign handler as an obstacle. The ordinary QIEC provider boundary remains explicit for other hosts.

Authored relation topologies

A relation declaration supplies the finite control states, typed tapes, and weighted occurrences of a sparse relation. Each tape names a finite alphabet declared by an object statement. Input tapes precede output tapes, and the label list follows that order. The label eps consumes no symbol. Arcs with the same record are distinct occurrences. Repeating a weight name shares one live scalar parameter across the module.

object Letters : FinSet 2

relation deletion [algebra=markov, states=2]
    input Letters
    output Letters
    initial 0 [weight=one]
    arc 0 -> 1 [labels=(0, eps), weight=delete]
    arc 0 -> 1 [labels=(0, 0), weight=keep]
    final 1 [weight=one]

define uncertainty : Real = path_entropy(deletion)
define expected_loss : Real = expected_path_cost(deletion)

Compiler.relation_specs["deletion"] returns its ordinary RationalRelationSpec for constructing a serialized request. The request supplies the words and limits. An expected-cost request also supplies its signed costs in occurrence order. The checked handler's identity includes the authored specification, so attaching a request with different arcs, tapes, or weight identities fails even if the scalar result type agrees.

String graph scores

A typed binding for a string graph score exposes a zero-argument computation for a checked tree query. Both bindings below receive their graph, observations, and resource limits from a serialized TreeStringGraphRequest.

define full_mass : Real = tree_partition()
define word_probability : LogWeight = tree_log_prob()

A partition may also use LogWeight when its graph uses LogProb. tree_log_prob always uses LogWeight. Attach each request using TreeStringGraphRuntimeProvider.for_score and the original graph's parameter store. The reference machine checks both the operation and its result type before it runs the request. String graph serialization

Authored relation composition

Two primitive declarations can be composed on a shared tape. An operand may appear later in the module.

object Letters : FinSet 2

relation channel = compose(typo, normalize)
define pair : Real = pair_weight(channel)

relation typo [algebra=markov, states=2]
    input Letters
    output Letters
    initial 0 [weight=one]
    arc 0 -> 1 [labels=(0, 1), weight=error]
    final 1 [weight=one]

relation normalize [algebra=markov, states=2]
    input Letters
    output Letters
    initial 0 [weight=one]
    arc 0 -> 1 [labels=(1, 0), weight=normalize_weight]
    final 1 [weight=one]

Each operand must have one input tape and one output tape. The first operand's output and the second operand's input must have the same nominal alphabet. The operands must share the Markov or LogProb algebra. The composed relation sums over the shared word, including all distinct compatible pairs of accepting paths. It keeps the original parameters, including weight names shared by both operands.

Compiler.composed_relation_specs["channel"] returns the ordered specification for a FixedComposedRelationRequest. The runtime request supplies the two outer words, the original scalar parameter bindings, and the product and query limits. Markov pair scores return Real. LogProb pair scores return LogWeight. Pair weights are also available when an operand is another checked relation operation.

Authored string factor graphs

A string graph declares variables, their observations, and ordered factor scopes. A factor names a primitive or derived relation. The variable order within each scope follows that relation's tape order.

object Letters : FinSet 2

string_graph chain
    variable source : Letters
    variable middle : Letters
    variable response : Letters [observed=(1)]
    factor edit(source, middle)
    factor edit(middle, response)

define evidence : Real = tree_partition(chain)

relation edit [algebra=markov, states=2]
    input Letters
    output Letters
    initial 0 [weight=one]
    arc 0 -> 1 [labels=(0, 1), weight=change]
    arc 0 -> 1 [labels=(1, 1), weight=keep]
    final 1 [weight=one]

A variable without an observation ranges over the words on its tape. The expression [observed=()] fixes the empty word. When different factors name the same relation, they share its weights and still contribute at separate graph positions.

Compiler.string_graph_specs["chain"] gives the checked StringFactorGraphSpec. The TreeStringGraphRequest supplies a query variable, an optional separately scored word, and sparse work limits. An authored score fixes the named graph's variables, observations, factor order, and relation topology. The runtime binds concrete parameter values and verifies the forest precondition before running the tree query.

Authored sparse relation transformations

A named transformation keeps the original typed relation specifications and parameter identities. This example projects the input tape and fixes the input word in a separate relation.

object Letters : FinSet 2

relation visible_inputs = project(channel, (0))
relation fixed_input = condition(channel, 0, (1))
relation response = compose(filtered, channel)
relation filtered = trim(channel)
define visible : Real = pair_weight(visible_inputs)
define fixed : Real = pair_weight(fixed_input)
define weight : Real = pair_weight(response)

relation channel [algebra=markov, states=2]
    input Letters
    output Letters
    initial 0 [weight=one]
    arc 0 -> 1 [labels=(1, 0), weight=replace]
    arc 0 -> 1 [labels=(1, 1), weight=keep]
    final 1 [weight=one]

Tape positions are zero-based. project(source, (0, 2)) retains the named tapes in increasing order. condition(source, 0, ()) fixes the empty word on tape zero. Other unary forms are invert(source), trim(source), and closure(source). The binary forms union(left, right), concatenate(left, right), and intersect(left, right) use their typed operand orders. join(left, right, 1, 0, keep_shared=true) synchronizes those two tape positions and retains their word once. Omitting keep_shared sums over the synchronized word.

A relation operand can name a primitive declaration or the result of another sparse operation, including one declared later. In the example, response composes the trimmed relation filtered with channel.

The compiler rejects cycles between declarations and checks the nominal tape layout of each step. It exposes longer recipes in Compiler.transformed_relation_specs. A FixedTransformedRelationRequest supplies the observed result words and work limits. A checked pair_weight score binds the exact named, ordered recipe. Cycles in a relation's state graph still require the declared closure capability. Native code targets identify the foreign handler that supplies the sparse score.

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

Joachim Lambek. The Mathematics of Sentence Structure. The American Mathematical Monthly, 65(3):154–170, 1958. URL: https://www.tandfonline.com/doi/abs/10.1080/00029890.1958.11989160, doi:10.1080/00029890.1958.11989160.

Michael Moortgat. Categorial Type Logics. In Johan van Benthem and Alice ter Meulen, editors, Handbook of Logic and Language, pages 93–177. Elsevier, 1997. URL: https://www.sciencedirect.com/book/9780444817143/handbook-of-logic-and-language, doi:10.1016/B978-044481714-3/50005-9.