Skip to content

Weighted Combinatory Categorial Grammar

Overview

Combinatory Categorial Grammar (CCG) is expressed as an agenda-based weighted deduction whose items are chart spans span(I, J, X) (token range [I, J) carrying category X). Steedman's combinators, forward and backward application, harmonic composition, and crossed composition (Steedman, 2000), are not written in the grammar: the standard library's module std.grammar.ccg declares them as deduction signatures, and the grammar extends the ones it uses. The example is a package of three modules: one declares the fragment's categories, one its lexicon, and the root module composes them with the library's combinators into a learnable deduction. The lexicon is chosen so that each of the six combinators is needed by at least one sentence, and removing each rule in turn tests its contribution. The semiring is the log semiring, so inside scores flow as differentiable tensors back to the learnable lexicon weights.

The categories use Steedman notation: Fwd(X, Y) denotes X/Y and Bwd(X, Y) denotes X\Y, with the result first in both (Steedman, 2000).

QVR source

The package's manifest names it and exposes its root module:

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

ccg.english adds the fragment's atoms to the library's categorial core:

# The categories of a small English fragment over std.grammar.ccg.
#
# std.grammar.ccg's `Categorial` declares the sentence category S, the
# slashes Fwd(X, Y) = X/Y and Bwd(X, Y) = X\Y (result first, the slash
# saying where the argument is sought), and the chart item
# span(I, J, X). This signature adds the noun phrase and noun atoms.

import std.grammar.ccg as C

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

#! The clauses quoting the fragment's atoms as `C.Atom` categories.
export meta define english_categories : Seq[MorphClause] !{} =
    let clauses <- C.atoms("English", SeqCons("NP", SeqCons("N", SeqNil)))
    return clauses

ccg.lexicon is a lexicon module typed against that signature:

# The lexicon of the fragment: one learnable entry per word and
# category.
#
# Each entry's meaning is a constant naming its word. "Mary" has two
# entries, the plain noun phrase and the type-raised subject S/(S\NP)
# that forward composition needs.

import std.grammar.ccg as C
import ccg.english (English)

#! The fragment's words.
export lexicon Words for English
    atoms the, cat, dog, mary, saw, sleeps, purrs, whom, that, probably, today, yesterday
    "the" : Fwd(NP, N) = the #[learnable]
    "cat" : N = cat #[learnable]
    "dog" : N = dog #[learnable]
    "Mary" : NP = mary #[learnable]
    "Mary" : Fwd(S, Bwd(S, NP)) = mary #[learnable]
    "saw" : Fwd(Bwd(S, NP), NP) = saw #[learnable]
    "sleeps" : Bwd(S, NP) = sleeps #[learnable]
    "purrs" : Bwd(S, NP) = purrs #[learnable]
    "whom" : Fwd(Bwd(N, N), Fwd(S, NP)) = whom #[learnable]
    "that" : Fwd(Bwd(N, N), Bwd(S, NP)) = that #[learnable]
    "probably" : Fwd(S, S) = probably #[learnable]
    "today" : Bwd(S, S) = today #[learnable]
    "yesterday" : Bwd(Bwd(S, NP), Bwd(S, NP)) = yesterday #[learnable]

#! The clauses quoting the words' meanings as `C.Atom` constants.
export meta define word_constants : Seq[MorphClause] !{} =
    let clauses <- C.atoms("Words", SeqCons("the", SeqCons("cat", SeqCons("dog", SeqCons("mary", SeqCons("saw", SeqCons("sleeps", SeqCons("purrs", SeqCons("whom", SeqCons("that", SeqCons("probably", SeqCons("today", SeqCons("yesterday", SeqNil)))))))))))))
    return clauses

The root module ccg composes the grammar and scores sentences with it:

# Weighted Combinatory Categorial Grammar
#
# A learnable weighted CCG over the combinators of std.grammar.ccg.
# The grammar names the combinators it uses instead of writing them:
# `C.Composition[n <= 1]` is application together with harmonic and
# crossed 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<)
#   forward_crossed_1_Bwd    X/Y, Y\Z  |- X\Z    (Bx>)
#   backward_crossed_1_Fwd   Y/Z, X\Y  |- X/Z    (Bx<)
#
# and the module ccg.lexicon supplies the words. Each combinator is
# needed by one sentence of the lexicon:
#
#   the cat sleeps                  application only
#   the dog whom Mary saw sleeps    B>: Mary : S/(S\NP) with
#                                   saw : (S\NP)/NP gives S/NP
#   the cat that sleeps today purrs B<: sleeps : S\NP with
#                                   today : S\S gives S\NP
#   Mary probably sleeps            Bx>: probably : S/S with
#                                   sleeps : S\NP gives S\NP
#   Mary saw yesterday the cat      Bx<: saw : (S\NP)/NP with
#                                   yesterday : (S\NP)\(S\NP)
#                                   gives (S\NP)/NP
#
# A CCG is lexicalized: the combinators are the library's and carry
# no weight of their own, and the learned weights are the lexicon's.
# The grammar runs in the log semiring, so a sentence's goal weight is
# its differentiable inside log-weight. Every chart item reifies as the
# `C.Category` it spans, through the quotation clauses the two modules
# export.

import std.grammar.ccg as C
import ccg.english (English, english_categories)
import ccg.lexicon (Words, word_constants)

object Term : FinSet 16

object LogWeight : Real 1

meta define fragment_quote : Morph !{} =
    let categories <- english_categories()
    let words <- word_constants()
    let clauses <- seq_append[MorphClause](categories, words)
    return Morph(clauses)

#! The grammar: the fragment's categories, application and degree-one
#! composition, and the fragment's words.
deduction CCG : Term -> Term [start=S, depth=6] deriving (Quote[C.Category via fragment_quote])
    extends English, C.Reified, C.Composition[n <= 1]
    lexicon Words

#! 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(CCG, sentence)
    score log_Z = chart.goal_weight()
    return log_Z

export score_sentence

Understanding the model

A category describes what an expression can combine with. Read NP/N as an expression that takes a noun on its right and returns a noun phrase: the with that category can combine with dog : N to form the dog : NP. A verb seeking a noun phrase on its left can then complete the sentence. The chart stores these partial results by their token intervals.

Composition combines two functors before either has its argument. In the dog whom Mary saw sleeps, the type-raised subject Mary : S/(S\NP) composes with saw : (S\NP)/NP into Mary saw : S/NP, a sentence missing its object, which is what the relative pronoun whom : (N\N)/(S/NP) asks for. Backward composition does the same leftward: in the cat that sleeps today purrs, sleeps : S\NP and today : S\S compose into S\NP, the argument of that : (N\N)/(S\NP). Crossed composition combines functors whose slashes point in opposite directions. In Mary probably sleeps, the sentence adverb probably : S/S composes with sleeps : S\NP into S\NP. In the heavy-NP-shift order Mary saw yesterday the cat, saw : (S\NP)/NP composes with yesterday : (S\NP)\(S\NP) into (S\NP)/NP, which then takes the shifted object.

Unrestricted crossed composition also permits orders English does not: with the same lexicon, the sleeps cat parses, because backward crossed composition of the : NP/N with sleeps : S\NP yields S/N. Steedman restricts the crossed rules to particular categories for this reason. The library's CrossedComposition keeps them unrestricted, and the enumeration below lists such strings among the grammatical ones.

Lexical weights score derivations. Alternatives leading to the same goal are combined by the chosen semiring. In the log semiring, weights add along a single derivation and logsumexp combines alternatives. The goal weight \(Z(s)\) is thus 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

ccg.english imports std.grammar.ccg as C. Its signature English extends C.Categorial, which declares the sentence category S, the slash constructors Fwd and Bwd, and the chart-item constructor span, and adds the atoms NP and N. The meta computation english_categories returns the clauses that quote those two atoms as values of the library's family C.Category, built with the library's C.atoms.

ccg.lexicon declares lexicon Words for English. Every category an entry names is checked against the atoms of English and the signatures it extends, so a misspelled atom is refused at the entry. The lexicon's own atoms line declares the logical-form constants its entries mean (the, cat, ...), and every entry carries #[learnable]: its log weight is a parameter the fit trains. Mary has two entries, the plain NP and the type-raised S/(S\NP) that forward composition needs, and the chart sums over both.

The root module's deduction CCG names its parts instead of restating them. extends English, C.Composition[n <= 1] takes the fragment's atoms and the library's application rules, together with every instance of its harmonic and crossed composition schemata whose degree n is at most one; lexicon Words takes the lexicon module's entries. The six rules that result are named after their schema and parameters:

Rule Sequent Combinator
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<
forward_crossed_1_Bwd X/Y, Y\Z ⊢ X\Z B×>
backward_crossed_1_Fwd Y/Z, X\Y ⊢ X/Z B×<

The library's rules carry no weight of their own. A CCG is lexicalized: what distinguishes one grammar from another is its lexicon, so the learned weights are the lexicon's, and a combinator's contribution to a derivation is the semiring's unit.

Extending C.Reified makes the deduction reify its chart items as C.Category values: the signature quotes S, the two slashes, and an item as the category it spans, and the deduction supplies the clauses for the atoms it adds, its lexicon's included, by deriving (Quote[C.Category via fragment_quote]), where fragment_quote joins the clauses the two modules export. The compiler then generates CCG.Item.quote, the inclusion of the library's items into CCG.Item, and the property that quoting an included item gives the library's quotation of it, which qvr test checks. The deduction runs in the log semiring because its header names no instance.

The score_sentence program connects the grammar to a probabilistic program: parse(CCG, 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

  • A package: the directory's qvr.toml names the package and the module it exposes, and every module path starts with the package's name (ccg.english is ccg/english.qvr).
  • deduction signature and lexicon L for S: a grammar's categories and its words are separate modules, each checked on its own.
  • extends S, T[n <= 1]: a deduction takes the rules of library signatures, restricted to the schema instances it wants.
  • extends C.Reified with deriving (Quote[C.Category via q]): chart items reify as library values, with a generated naturality property.
  • parse(D, sentence) in a program: a program body can run a deduction and score its goal weight.

Try it

Every #[learnable] lexicon entry exposes 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 combinator is needed

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

import torch
from quivers.dsl import load

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


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 cat sleeps",
    "backward_application": "the cat sleeps",
    "forward_harmonic_1_Fwd": "the dog whom Mary saw sleeps",
    "backward_harmonic_1_Bwd": "the cat that sleeps today purrs",
    "forward_crossed_1_Bwd": "Mary probably sleeps",
    "backward_crossed_1_Fwd": "Mary saw yesterday the cat",
}
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}")

# Unrestricted backward crossed composition scrambles the noun phrase.
assert parses(ded, "the sleeps cat")
assert not parses(without(ded, "backward_crossed_1_Fwd"), "the sleeps cat")

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", "cat", "dog", "Mary", "saw", "sleeps", "purrs",
    "whom", "that", "probably", "today", "yesterday",
]
truth = load("docs/examples/source/ccg/ccg.qvr").deductions["CCG"]
model = load("docs/examples/source/ccg/ccg.qvr").deductions["CCG"]

strings = [
    list(words)
    for words in itertools.product(VOCAB, repeat=3)
    if parses(truth, " ".join(words))
]
print(len(strings), "grammatical three-word strings")
assert ["the", "sleeps", "cat"] in 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

Twenty-one three-word strings parse. Besides plain application, they include Mary saw Mary and probably Mary sleeps, with derivations through forward composition of the raised subject. Mary sleeps today, through backward composition. Mary probably sleeps, through forward crossed composition. And the scrambled the sleeps cat and Mary today sleeps, through backward crossed composition. With 2,000 draws over 21 outcomes, the sampling error of the maximum-likelihood fit is near \(20 / (2 \cdot 2000) = 0.005\) nats, so a divergence below 0.05 indicates that the fit has recovered the distribution. The weights themselves are not identifiable, since several bindings can trade mass along one derivation, so the check is on the distribution over strings.

Categorical perspective

Application and harmonic composition are theorems of the Lambek calculus (Lambek, 1958), whose models are biclosed monoidal categories: X/Y and X\Y are internal function types accepting a Y on opposite sides. Application evaluates such a function at its argument, formally the counit of a tensor-hom adjunction. Harmonic composition composes these internal functions. Crossed composition is not a Lambek theorem. It becomes derivable once the tensor is symmetric, as in the commutative calculus LP, which is also why it licenses the sleeps cat: a symmetric tensor forgets word order. The six rules thus extend the Lambek fragment rather than present the internal language of a biclosed monoidal category. The library draws the same line: std.grammar.lambek's signature Associative extends HarmonicComposition alone, so a grammar written over it is a sound fragment of the Lambek calculus.

Semiring selection

The choice of semiring affects the parser's behavior: LogProb, the default, accumulates inside log-weights (numerically stable, differentiable). Viterbi returns the highest-weight derivation. Counting counts distinct derivations. Boolean checks membership without weights. The same deduction serves all four objectives through its header parameter, deduction CCG[S = std.semiring.Counting], which names an instance of std.semiring.

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.

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.