Skip to content

Custom Sequent Rules

Overview

This AB grammar (Ajdukiewicz-Bar-Hillel) adds harmonic composition to forward and backward application, and one rule of its own. The combinators are not written in the grammar: it extends the deduction signatures of the standard library's std.grammar.ccg, which state them once for every categorial grammar. The rule the grammar declares itself is subject type raising, written as a lexical rule that derives the raised category of every noun phrase in the lexicon. The example is a package of two modules: one holds the fragment's categories and words, the other composes them with the library's rules and the grammar's own. The grammar uses Steedman notation (Steedman, 2000): Fwd(X, Y) is X/Y and Bwd(X, Y) is X\Y, with the result first in both. Removing a rule tests which sentences depend on it.

QVR source

The package's manifest:

[package]
name = "custom_rules"
version = "0.1.0"
modules = ["custom_rules"]

custom_rules.words declares the fragment's signature, its lexicon, and the clauses that quote its atoms:

# The categories and words of a small English fragment over
# std.grammar.ccg.
#
# `Fragment` adds the noun phrase and noun atoms to the library's
# categorial core (S, the slashes Fwd and Bwd, and the chart item
# span). `Words` types each word against it. Every proper noun is a
# plain NP here; the grammar derives the type-raised subject it needs
# with a lexical rule of its own.

import std.grammar.ccg as C

#! The atoms of the fragment besides S.
export deduction signature Fragment
    extends C.Categorial
    atoms NP, N

#! The fragment's words, one learnable entry each.
export lexicon Words for Fragment
    atoms the, dog, cat, mary, saw, runs, barks, whom, that, today
    "the" : Fwd(NP, N) = the #[learnable]
    "dog" : N = dog #[learnable]
    "cat" : N = cat #[learnable]
    "Mary" : NP = mary #[learnable]
    "saw" : Fwd(Bwd(S, NP), NP) = saw #[learnable]
    "runs" : Bwd(S, NP) = runs #[learnable]
    "barks" : Bwd(S, NP) = barks #[learnable]
    "whom" : Fwd(Bwd(N, N), Fwd(S, NP)) = whom #[learnable]
    "that" : Fwd(Bwd(N, N), Bwd(S, NP)) = that #[learnable]
    "today" : Bwd(S, S) = today #[learnable]

#! The clauses quoting the fragment's atoms and its words' meanings as
#! `C.Atom` values.
export meta define fragment_clauses : Seq[MorphClause] !{} =
    let categories <- C.atoms("Fragment", SeqCons("NP", SeqCons("N", SeqNil)))
    let words <- C.atoms("Words", SeqCons("the", SeqCons("dog", SeqCons("cat", SeqCons("mary", SeqCons("saw", SeqCons("runs", SeqCons("barks", SeqCons("whom", SeqCons("that", SeqCons("today", SeqNil)))))))))))
    let clauses <- seq_append[MorphClause](categories, words)
    return clauses

The root module custom_rules composes the grammar:

# Custom Rules
#
# An AB grammar (Ajdukiewicz-Bar-Hillel) with harmonic composition,
# taken from std.grammar.ccg, and one rule the grammar declares itself.
# `C.HarmonicComposition[n <= 1]` is application and harmonic
# composition of degree one:
#
#   forward_application      X/Y, Y    |- X      (>)
#   backward_application     Y, X\Y    |- X      (<)
#   forward_harmonic_1_Fwd   X/Y, Y/Z  |- X/Z    (B>)
#   backward_harmonic_1_Bwd  Y\Z, X\Y  |- X\Z    (B<)
#
# Fwd(X, Y) is X/Y and Bwd(X, Y) is X\Y: the result comes first and
# the slash direction says where the argument is sought.
#
# The grammar's own rule is subject type raising, NP |- S/(S\NP),
# declared as a lexical rule: it derives an entry from every NP entry
# of the lexicon when the lexicon is compiled, so "Mary" has the raised
# category without a second entry, and no item a rule derives is
# raised. Its learned weight is added to the weight of every entry it
# derives.
#
# The lexicon is chosen so that each rule is needed by some sentence.
# Application alone derives "the dog runs". The object relative "the
# dog whom Mary saw runs" needs forward composition and type raising:
# the raised subject Mary : S/(S\NP) composes with saw : (S\NP)/NP
# into S/NP, the argument whom : (N\N)/(S/NP) seeks. The subject
# relative "the dog that runs today barks" needs backward composition:
# runs : S\NP composes with the sentence modifier today : S\S into
# S\NP, the argument that : (N\N)/(S\NP) seeks.

import std.grammar.ccg as C
import custom_rules.words (Fragment, Words, fragment_clauses)

object Term : FinSet 16

object LogWeight : Real 1

meta define fragment_quote : Morph !{} =
    let clauses <- fragment_clauses()
    return Morph(clauses)

#! Application and degree-one harmonic composition from the library,
#! the fragment's words, and the grammar's own type-raising rule.
deduction AB : Term -> Term [start=S, depth=6] deriving (Quote[C.Category via fragment_quote])
    extends Fragment, C.Reified, C.HarmonicComposition[n <= 1]
    lexicon Words
    lexical rule raise : span(I, J, NP) |- span(I, J, Fwd(S, Bwd(S, NP))) #[learnable]

#! The grammar's contribution to a probabilistic program: parsing an
#! observed sentence and scoring the chart's goal weight adds the inside
#! log-weight log Z(s), summed over every derivation of S, to the
#! program's log-joint.
program score_sentence : Term -> LogWeight
    let chart = parse(AB, sentence)
    score log_Z = chart.goal_weight()
    return log_Z

export score_sentence

Understanding the model

A rule is a template for combining known facts. Suppose one chart entry is span(0, 1, Fwd(NP, N)) and the next is span(1, 2, N). The repeated position and category variables in forward application must agree, giving span(0, 2, NP). This agreement is unification: different occurrences of one variable receive one value within that rule firing.

Application suffices for the dog runs. Composition earns its place when a constituent is missing an argument at its edge. In the object relative the dog whom Mary saw runs, the clause Mary saw lacks its object, and whom : (N\N)/(S/NP) asks for exactly such a clause. Forward composition builds it: the type-raised subject Mary : S/(S\NP) composes with saw : (S\NP)/NP into S/NP. In the subject relative the dog that runs today barks, that : (N\N)/(S\NP) asks for a verb phrase, and backward composition of runs : S\NP with the sentence modifier today : S\S provides the verb phrase runs today : S\NP.

An agenda records newly derived entries and tries rules that can use them. Weights say how to combine evidence along a derivation and across alternatives. Changing the rule changes what can be derived. Changing the semiring changes what is accumulated about those derivations. Keep those two choices separate when interpreting the returned goal weight.

The goal weight \(Z(s)\) is a sum of exponentiated derivation weights, not a probability. Over the finitely many strings of a fixed length \(n\) it normalizes into the length-conditional distribution \(P(s \mid n) = Z(s) / \sum_{|s'| = n} Z(s')\), which is the model the fit below recovers.

Walkthrough

custom_rules.words imports std.grammar.ccg as C. The signature Fragment extends C.Categorial, which declares the sentence category S, the slash constructors Fwd and Bwd, and the chart-item constructor span, and adds NP and N. lexicon Words for Fragment types each word against those atoms; its own atoms line declares the logical-form constants its entries mean, and every entry carries #[learnable].

The deduction AB states which rules it uses rather than how they work. extends Fragment, C.HarmonicComposition[n <= 1] takes the library's application rules and the instances of its harmonic composition schemata of degree at most one, four rules named after their schema and parameters: forward_application, backward_application, forward_harmonic_1_Fwd (X/Y, Y/Z ⊢ X/Z), and backward_harmonic_1_Bwd (Y\Z, X\Y ⊢ X\Z). Each is a sequent over chart items whose pattern variables are single uppercase letters; a variable that occurs twice in a rule must take one value, so the Y of forward application's two premises is one category.

The grammar's own rule is the lexical rule raise. A lexical rule derives a lexical item from a lexical item over the same span. In its default mode the lexicon is closed under it when the deduction is compiled: the entry "Mary" : NP yields the entry "Mary" : S/(S\NP), and no item a combinator derives is ever raised. The learnable rule has one weight, which is added to the weight of every entry it derives, so the raised Mary reads the weight of Mary and the weight of raising. Raising only lexical noun phrases keeps the grammar's derivations exactly those of a lexicon listing both categories of Mary by hand, which is what the charts below reproduce.

The combinators carry no weight of their own: a categorial grammar is lexicalized, and its learned weights are those of its entries and its lexical rule. AB extends C.Reified and supplies the clauses that quote its added atoms (deriving (Quote[C.Category via fragment_quote])), so every chart item reifies as the category it spans.

The score_sentence program connects the grammar to a probabilistic program: parse(AB, sentence) runs the deduction on an observed sentence, and score log_Z = chart.goal_weight() adds \(\log Z(s)\) to the program's log-joint. That is an unnormalized factor. The fit below divides by the length-\(n\) total explicitly.

DSL features

  • extends S, T[n <= 1]: a deduction takes the rules of library signatures, restricted to the schema instances it wants.
  • lexicon L and lexicon L for S: a grammar's words are a module typed against its signature.
  • lexical rule NAME : premise |- conclusion: a rule of the grammar's own that derives entries from entries.
  • extends C.Reified with deriving (Quote[C.Category via q]): chart items reify as library values.
  • parse(D, sentence) in a program: a program body can run a deduction and score its goal weight.

Pattern matching and unification

A rule fires by first-order pattern matching:

  • Variables (X, Y, Z): metavariables that match any concrete subterm. Repeated occurrences within a rule must unify.
  • Constructor patterns (Fwd(X, Y)): match constructor-application items whose head is the same atom and whose children unify.

The agenda fires each rule at every chart cell (unary) or every combination of cells (binary and higher) whose items unify with the rule's premises. The conclusion item is then inserted into the chart under the rule's weight.

Chart rules beside the library's

A grammar may also state its own rules as chart rules, which apply to derived items as well as to lexical ones. Every variable in a conclusion must be bound by a premise, because the chart holds only ground items. General type raising, span(I, J, X) |- span(I, J, Fwd(Y, Bwd(Y, X))), leaves the result category Y free, and the compiler rejects it with rule 'type_raise' concludes with 'Y', which no premise binds. Fixing the raised-over category makes the rule well formed:

import std.grammar.ccg as C

object Term : FinSet 16

deduction signature Nominal
    extends C.Categorial
    atoms NP, N

deduction Raised : Term -> Term [start=S, depth=6]
    extends Nominal, C.Application
    atoms the, dog, runs
    rule subject_raise : span(I, J, NP) |- span(I, J, Fwd(S, Bwd(S, NP)))
    lexicon
        "the" : Fwd(NP, N) = the
        "dog" : N = dog
        "runs" : Bwd(S, NP) = runs

As a chart rule, subject_raise raises the derived noun phrase the dog, so the dog runs has two derivations, one by backward application and one by forward application of the raised subject, and its goal weight is \(\log 2\) with every weight at zero. The lexical rule of AB would not apply here, since no entry of this lexicon is an NP. Literal atoms in a pattern restrict a rule in the same way: span(I, K, Fwd(X, Y)), span(K, J, Fwd(Y, NP)) |- span(I, J, Fwd(X, NP)) is forward composition limited to functors whose argument is NP.

Try it

Every #[learnable] lexicon entry and the learnable lexical rule expose a real nn.Parameter on the compiled DeductionSystem. The system is callable: ded(sentence) returns a ChartView whose goal_weight() is the differentiable log-weight \(\log Z(s; \mathbf{w}) = \log \sum_d \exp \langle \mathbf{w}, \phi(d) \rangle\) summed over every derivation \(d\) that the start symbol licenses for the input.

Each rule is needed

Removing a rule from the compiled system and reparsing shows which sentences depend on it. Each sentence below parses with the full rule set and fails without the rule it is meant to exercise.

import torch
from quivers.dsl import load

prog = load("docs/examples/source/custom_rules/custom_rules.qvr")
ded = prog.deductions["AB"]


def parses(system, sentence):
    return bool(torch.isfinite(system(sentence.split()).goal_weight()))


def without(system, rule_name):
    rules = tuple(rule for rule in system.rules if rule.name != rule_name)
    assert len(rules) == len(system.rules) - 1
    return system.with_(rules=rules)


needs = {
    "forward_application": "the dog runs",
    "backward_application": "the dog runs",
    "forward_harmonic_1_Fwd": "the dog whom Mary saw runs",
    "backward_harmonic_1_Bwd": "the dog that runs today barks",
}
assert set(needs) == {rule.name for rule in ded.rules}
for rule_name, sentence in needs.items():
    assert parses(ded, sentence), sentence
    assert not parses(without(ded, rule_name), sentence), (rule_name, sentence)
    print(f"{rule_name:24s} is needed for {sentence!r}")

Recovering a length-conditional distribution

A copy of the grammar with every weight drawn from a unit Normal serves as the ground truth. sample_corpus draws 2,000 three-word sentences from its length-conditional distribution, enumerating every string over the vocabulary and sampling in proportion to \(Z(s)\). A freshly loaded copy, with every weight at zero, is then fit by maximizing the same length-conditional log-likelihood. The denominator needs only the strings that parse at all, and whether a string parses does not depend on the weights, so the grammatical strings are enumerated once.

import itertools

from quivers.stochastic.deduction import sample_corpus

torch.manual_seed(0)
VOCAB = ["the", "dog", "cat", "Mary", "saw", "runs", "barks", "whom", "that", "today"]
truth = load("docs/examples/source/custom_rules/custom_rules.qvr").deductions["AB"]
model = load("docs/examples/source/custom_rules/custom_rules.qvr").deductions["AB"]

strings = [
    list(words)
    for words in itertools.product(VOCAB, repeat=3)
    if parses(truth, " ".join(words))
]
print(len(strings), "grammatical three-word strings")


def log_conditional(system):
    """log P(s | n = 3) for every grammatical three-word string."""
    scores = torch.stack([system(s).goal_weight() for s in strings])
    return scores - torch.logsumexp(scores, dim=0)


def kl(log_p, log_q):
    return float((log_p.exp() * (log_p - log_q)).sum())


# Parsing every string once allocates every weight either system uses.
for s in strings:
    truth(s).goal_weight()
    model(s).goal_weight()
with torch.no_grad():
    for p in truth.parameters():
        p.normal_(0.0, 1.0)
    true_log_p = log_conditional(truth)

corpus = sample_corpus(truth, length=3, n_samples=2000, seed=0)
index = {tuple(s): i for i, s in enumerate(strings)}
counts = torch.bincount(
    torch.tensor([index[tuple(s)] for s in corpus]), minlength=len(strings)
).float()

with torch.no_grad():
    kl_initial = kl(true_log_p, log_conditional(model))
opt = torch.optim.Adam(list(model.parameters()), lr=5e-2)
for _ in range(200):
    opt.zero_grad()
    loss = -(counts * log_conditional(model)).sum() / counts.sum()
    loss.backward()
    opt.step()
with torch.no_grad():
    kl_fitted = kl(true_log_p, log_conditional(model))

print(f"KL(true || initial) = {kl_initial:.4f}")
print(f"KL(true || fitted)  = {kl_fitted:.4f}")
assert kl_fitted < 0.05 and kl_fitted < 0.25 * kl_initial

Seven three-word strings parse, and two of them use composition: Mary saw Mary has one derivation through forward composition of the raised subject with saw, and Mary runs today two through backward composition of runs with today. With 2,000 draws over seven outcomes, the sampling error of the maximum-likelihood fit is near \(6 / (2 \cdot 2000) = 0.0015\) nats, so a divergence below 0.05 indicates that the fit has recovered the distribution. The weights themselves are not identifiable: the entries along one derivation can trade mass, so the check is on the distribution over strings.

Categorical perspective

A directed hyperedge can connect several premise items to one conclusion item. A rule describes such edges by patterns. Matching the premises finds a substitution for their variables, and repeated occurrences of a variable must receive the same value.

The chart combines premise weights by semiring multiplication and alternative derivations by semiring addition (Goodman, 1999). Agreement between evaluation orders requires correct handling of repeated contributions and, for recursive systems, termination or convergence. The runtime selects a strategy from rule arities and semiring properties. An arbitrary firing order need not preserve the result.

Cited sources

Mark Steedman. The Syntactic Process. MIT Press, 2000. URL: https://direct.mit.edu/books/book/4283/The-Syntactic-Process, doi:10.7551/mitpress/6591.001.0001.

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