Skip to content

16. Composing a grammar

A grammar written as one deduction states its categories, its rules, and its words in one place, so a second grammar that shares the rules restates them, and a fix to a rule must be made in every copy. This chapter assembles a small combinatory categorial grammar (CCG) (Steedman, 2000) from parts instead, each in its own module:

  1. a core, a deduction signature that declares the categories and the application rules;
  2. two lexicon modules, each holding words typed against the core;
  3. three deductions that extend the core and take the lexicons, two of which add the library's composition schemata and one a polymorphic entry for and;
  4. generic code that reads the chart items of any deduction extending the core;
  5. a choice of semiring for each deduction, and one chart computed once and evaluated in several semirings.

The rules come from std.grammar.ccg, the standard library's CCG, so no rule is written by hand. Composable deductions states every form the chapter uses.

1. The package

The fragment is a package of four modules, laid out as the quickstart lays out a package:

qvr.toml
fragment/
    core.qvr
    nominal.qvr
    verbal.qvr
    grammar.qvr
[package]
name = "fragment"
version = "0.1.0"
modules = ["fragment.core", "fragment.nominal", "fragment.verbal", "fragment.grammar"]

A module's path follows its file, so fragment/core.qvr is the module fragment.core. Each qvr block below is one file of the package, which is also in docs/tutorials/qvr/source/grammar.

2. The core

fragment/core.qvr
import std.grammar.ccg as C

#! The core of the fragment: noun phrases and common nouns, beside the
#! sentence category and the slashes of every categorial grammar, with
#! forward and backward application.
export deduction signature English
    extends C.Application
    atoms NP, N

A deduction signature declares atoms and rules, but no lexicon and no header, so it is a core other deductions extend, not a grammar that parses. C.Categorial, which C.Application extends, declares the sentence category S, the slashes, and the chart item: categories are written result first, so Fwd(X, Y) is \(X/Y\), which takes a Y on its right, and Bwd(X, Y) is \(X\backslash Y\), which takes a Y on its left, and an item span(i, j, X) says that the words from position i up to j derive X. C.Application adds the two rules of application,

\[\frac{X/Y \quad Y}{X}\ (>) \qquad \frac{Y \quad X\backslash Y}{X}\ (<)\]

and English adds the atoms of this fragment, NP and N.

3. Two lexicon modules

fragment/nominal.qvr
import fragment.core (English)

#! Two names, a determiner, and a common noun.
export lexicon Nominal for English
    atoms kim, sandy, the, dog
    "Kim" : NP = kim
    "Sandy" : NP = sandy
    "the" : Fwd(NP, N) = the
    "dog" : N = dog
fragment/verbal.qvr
import fragment.core (English)

#! An intransitive verb and a transitive verb.
export lexicon Verbal for English
    atoms sleeps, sees
    "sleeps" : Bwd(S, NP) = sleeps
    "sees" : Fwd(Bwd(S, NP), NP) = sees

A lexicon L for S module holds entries whose categories are built from the atoms of S: each entry is a word, its category, and its meaning, an atom the module's atoms line declares. The determiner the is \(NP/N\), and the transitive verb sees is \((S\backslash NP)/NP\), so it takes its object on the right and then its subject on the left. A lexicon names its signature, so an entry whose category uses an atom English lacks is refused, and a grammar may take a lexicon only if it extends the lexicon's signature. Each lexicon module is thus written apart from the grammars that use it, and one grammar may take several.

4. Grammars that extend the core

fragment/grammar.qvr
import std.grammar.ccg as C
import std.semiring
import fragment.core (English)
import fragment.nominal (Nominal)
import fragment.verbal (Verbal)

object Word : FinSet 16

object Count : Real 1

#! The core and both lexicons, parsing by application alone.
deduction Small[S = std.semiring.Counting] : Word -> Word [start=S, depth=6]
    extends English
    lexicon Nominal, Verbal

#! The core with harmonic composition of degree one and a polymorphic
#! coordinator.
deduction Grammar[S = std.semiring.Counting] : Word -> Word [start=S, depth=6]
    extends English, C.HarmonicComposition[n <= 1]
    lexicon Nominal, Verbal
    atoms and_c
    categories Conj = S, NP, Bwd(S, NP)
    lexicon
        "and" : ∀ X in Conj. Fwd(Bwd(X, X), X) = and_c

#! The parts of `Small` with composition, run in the Viterbi semiring.
deduction Best[S = std.semiring.Viterbi] : Word -> Word [start=S, depth=6]
    extends English, C.HarmonicComposition[n <= 1]
    lexicon Nominal, Verbal

#! Whether an item of any deduction extending the core is a sentence.
define is_sentence(module D : Deduction extends English, item : D.Item) : Bool !{} =
    case item
        D.span(i, j, D.S) =>
            return true
        _ =>
            return false

#! `is_sentence` on the items of both grammars.
define both_grammars_read() : Bool !{} =
    let big <- is_sentence(Grammar, Grammar.span(0, 2, Grammar.S))
    let small <- is_sentence(Small, Small.span(0, 2, Small.S))
    let noun <- is_sentence(Grammar, Grammar.span(0, 1, Grammar.NP))
    return big && small && not noun

#! The number of derivations of a sentence by application alone.
program by_application : Word -> Count
    let chart = parse(Small, sentence)
    score count = chart.goal_weight()
    return count

#! The number of derivations of a sentence in `Grammar`.
program derivations : Word -> Count
    let chart = parse(Grammar, sentence)
    score count = chart.goal_weight()
    return count

#! The log weight of the best derivation of a sentence in `Best`.
program best : Word -> Count
    let chart = parse(Best, sentence)
    score value = chart.goal_weight()
    return value

test "application derives a transitive sentence once" [numbers=float64] =
    expect by_application(sentence=["Kim", "sees", "the", "dog"]) == 1 within 1e-9
    expect by_application(sentence=["sees", "Kim"]) == 0 within 1e-9

test "composition adds a second derivation" [numbers=float64] =
    expect derivations(sentence=["Kim", "sees", "the", "dog"]) == 2 within 1e-9

test "and coordinates each category of its set" [numbers=float64] =
    expect derivations(sentence=["Kim", "sleeps", "and", "Sandy", "sleeps"]) == 2 within 1e-9
    expect derivations(sentence=["Kim", "and", "Sandy", "sleeps"]) == 2 within 1e-9
    expect derivations(sentence=["Kim", "sleeps", "and", "sees", "Sandy"]) == 2 within 1e-9
    expect derivations(sentence=["Kim", "sees", "the", "dog", "and", "Sandy"]) == 1 within 1e-9

test "the best derivation has log weight zero" [numbers=float64] =
    expect best(sentence=["Kim", "sees", "the", "dog"]) == 0 within 1e-9

test "generic code reads the items of both grammars" =
    expect both_grammars_read()

Each deduction states its parts on its body lines: extends names the signatures whose atoms and rules it takes, and lexicon Nominal, Verbal the lexicon modules whose entries it takes. Small is the core with the two lexicons, and parses by application alone. Grammar also extends C.HarmonicComposition, whose rules are schemata: a schema is a family of rules indexed by static parameters, here the degree \(n\) of generalized composition, and [n <= 1] keeps the instances of degree at most one, the composition rules

\[\frac{X/Y \quad Y/Z}{X/Z}\ (B_>) \qquad \frac{Y\backslash Z \quad X\backslash Y}{X\backslash Z}\ (B_<)\]

Composition adds derivations a grammar with application alone lacks: sees the composes into \((S\backslash NP)/N\) before it takes dog, so Kim sees the dog has two derivations, one by application alone and one through \(B_>\).

Grammar also has an entry of its own. categories Conj = S, NP, Bwd(S, NP) declares a set of categories, and the entry "and" : ∀ X in Conj. Fwd(Bwd(X, X), X) is one entry for each member: and is \((X\backslash X)/X\) for \(X\) a sentence, a noun phrase, or a verb phrase, so it coordinates two constituents of one category into one of the same category. One declaration stands for three entries, and every instance reads the one meaning and_c (polymorphic entries).

A deduction made of parts is interpreted away before anything runs: the reference machine, the compiled runtime, and the transpile targets run the one deduction whose atoms, rules, and entries are those of its parts, in order. Parts are identified by where they are declared, so English, reached by both deductions and by both lexicons, contributes its atoms and rules once, and two parts that declare one atom are refused, naming both.

5. Code over every extension

is_sentence takes a deduction as an argument: module D : Deduction extends English ranges over every deduction that extends the core, and D.Item is that deduction's chart item. The body is checked once, against the core's constructors (D.span, D.S, and the others) and one more that no code can name, which stands for every constructor an extension adds. A case that lists only the core's constructors is thus refused, so the final _ arm is required: it stands for the atoms of the lexicons, for Grammar.and_c, which Small lacks, and for any constructor a later extension adds. Each call is specialized at the deduction it passes, so both_grammars_read runs is_sentence on the items of both grammars (generic code over extensions).

6. Semirings

The header Grammar[S = std.semiring.Counting] runs Grammar in the counting semiring, the natural numbers with \(+\) and \(\times\), so the weight of the goal item is the number of derivations of the sentence. Small runs in it as well. Best[S = std.semiring.Viterbi] runs the parts of Grammar without the coordinator in the Viterbi semiring, max and \(+\) on log weights, so its goal weight is the log weight of the best derivation; every rule and entry has log weight zero here, so the best derivation has weight zero as well. A deduction without a header runs in the log semiring (Goodman, 1999).

The tests of fragment/grammar.qvr state the counts exactly. The first three coordinations have two derivations each, though each has one reading. In Kim sleeps and Sandy sleeps, and may coordinate the two sentences, or and Sandy sleeps, an \(S\backslash S\), may compose by \(B_<\) with sleeps into an \(S\backslash NP\) that then takes Kim; both derivations give one meaning. This is the spurious ambiguity of a grammar with composition (Eisner, 1996), and counting derivations is how a test catches it. Kim sees the dog and Sandy has one derivation, since the derivation through \(B_>\) builds the verb phrase sees the dog before and Sandy could join the dog. Run the tests from the package's directory:

qvr test fragment/grammar.qvr
ok    fragment/grammar.qvr:64 test 'application derives a transitive sentence once'
ok    fragment/grammar.qvr:68 test 'composition adds a second derivation'
ok    fragment/grammar.qvr:71 test 'and coordinates each category of its set'
ok    fragment/grammar.qvr:77 test 'the best derivation has log weight zero'
ok    fragment/grammar.qvr:80 test 'generic code reads the items of both grammars'
5 passed (0 cached), 0 failed, 0 errors, 0 modules failed to load

7. One chart, every semiring

The items of a chart and the derivations of each do not depend on the semiring; only their weights do. The free chart is the chart computed once in the free commutative semiring: the derivation hypergraph of the sentence, each item with the rule instances and words that derive it, a provenance semiring in the sense of Green, Karvounarakis, and Tannen (Green et al., 2007). Evaluating it along the homomorphism into a semiring gives the chart that a run in that semiring computes. Compute the free chart of Best once, and evaluate its goal in four semirings:

from quivers.dsl import load
from quivers.dsl.semirings import free_chart, goal_value, homomorphism, polynomial

fragment = load(
    "docs/tutorials/qvr/source/grammar/fragment/grammar.qvr",
    roots=("docs/tutorials/qvr/source/grammar",),
)
chart = free_chart(fragment.deductions["Best"], "Kim sees the dog".split())
for name in ("Counting", "Boolean", "LogProb", "Viterbi"):
    instance = fragment.semirings[f"std.semiring:{name}"]
    print(name, float(goal_value(chart, homomorphism(instance))))
(goal,) = chart.goals
print(len(polynomial(chart, goal)), "monomials")
Counting 2.0
Boolean 1.0
LogProb 0.6931471805599453
Viterbi 0.0
2 monomials

free_chart computes the hypergraph, homomorphism sends each rule instance and word to its weight in an instance, and goal_value evaluates the goal along it. The counting semiring gives the two derivations that the test of Grammar counts, the Boolean semiring says that a derivation exists, the log semiring gives \(\log 2\), the log of the summed weight of two derivations of log weight zero, and the Viterbi semiring gives the weight of the best one, which is the goal weight a run of Best computes. polynomial gives the goal's element of the free semiring itself, one monomial for each distinct multiset of rule instances and words that derives it: here two, the derivation by application alone and the one through \(B_>\).

The free chart is taken of Best because its weights are log weights, which each of these semirings can read. The free chart of Grammar, run in the counting semiring, evaluates to the counting and Boolean semirings, but its homomorphism into the log semiring is refused with a SemiringError, since a count is not a log weight.

Next

Composable deductions states every form of composition and the refusals, Lexical entries the category sets, polymorphic entries, and semantic types, and std.grammar.ccg the crossed composition schemata and the reification of chart items as Category values.

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

Jason Eisner. Efficient Normal-Form Parsing for Combinatory Categorial Grammar. In 34th Annual Meeting of the Association for Computational Linguistics, 79–86. Santa Cruz, California, USA, 1996. Association for Computational Linguistics. URL: https://aclanthology.org/P96-1011/, doi:10.3115/981863.981874.

Todd J. Green, Grigoris Karvounarakis, and Val Tannen. Provenance Semirings. In Proceedings of the Twenty-Sixth ACM SIGMOD-SIGACT-SIGART Symposium on Principles of Database Systems, 31–40. 2007. URL: https://doi.org/10.1145/1265530.1265535, doi:10.1145/1265530.1265535.