Algorithm Search⌘K

Techniqueadvanced

Parent annotation

Also called vertical Markovization.

Split each nonterminal of the treebank trees by the label of its parent, so a PCFG sees more context. Klein and Manning measured F1 rising from 72.62 to 76.81.

Parent annotation is a tree transform for treebank grammars. Before the rules of a probabilistic context-free grammar are read off a treebank, each phrasal label is renamed to carry the label of its parent: an NP under S becomes NP^S, and an NP under VP becomes NP^VP. The grammar read off the new trees can give the two kinds of noun phrase different expansions, which a plain PCFG cannot do, because it chooses the expansion of a node from its label alone. After parsing, the parent part of every label is removed again. Mark Johnson studied the transform in 1998. In the measurements of Klein and Manning (2003) on the Penn Treebank, it raised the F1 of a plain treebank PCFG from 72.62 to 76.81, while the number of rules grew from 9657 to 14666. It is a heuristic: it adds context in a fixed way, and latent-variable PCFGs learn such splits from the data instead.

In plain words

A plain treebank grammar decides how to build a phrase by looking only at the name of the phrase, for example "noun phrase". But a noun phrase at the start of a sentence, the subject, is often just a pronoun such as "she", while a noun phrase after a verb, the object, is more often a full phrase such as "the cat". The plain grammar cannot see this difference, because both are just noun phrases.

Parent annotation gives the grammar this missing piece of context. Each phrase name gets the name of the phrase above it, so "noun phrase under a sentence" and "noun phrase under a verb phrase" become two different names with their own statistics. The parser works as before with the larger grammar, and at the end the extra part of each name is cut off.

When it applies

The transform applies to any grammar that is read off a treebank by relative frequency and parsed with a chart parser such as probabilistic CKY. It helps when the expansion of a node depends on where the node is, which is common in natural language. Klein and Manning report that in the Penn Treebank a subject NP is 8.7 times more likely than an object NP to expand as just a pronoun.

A small example shows the effect. Take a treebank of four trees:

  • (S (NP (PRP she)) (VP (VBD saw) (NP (DT the) (NN cat))))
  • (S (NP (PRP he)) (VP (VBD fed) (NP (DT the) (NN dog))))
  • (S (NP (DT the) (NN dog)) (VP (VBD saw) (NP (PRP her))))
  • (S (NP (PRP they)) (VP (VBD left)))

Of the seven NP nodes, four expand as PRP, so the plain grammar has q(NP→PRP)=4/7q(NP \to PRP) = 4/7 and q(NP→DT NN)=3/7q(NP \to DT\ NN) = 3/7. After annotation, the four subject nodes are NP^S, and the rule NP^S → PRP has probability 3/4. The three object nodes are NP^VP, and the rule NP^VP → PRP has probability 1/3. The plain grammar gives the trees of she saw the cat and the cat saw her the same probability 3/3923/392, because the two trees use the same multiset of rules. The annotated grammar gives them 1/641/64 and 1/3841/384, a factor of 6 in favour of the pronoun subject. The numbers are exact fractions computed by the tests.

The transform does not apply in the same way to parsers that do not read rules off trees, such as span-based neural parsers, whose encoder already sees the whole sentence.

The template

The transform is a walk over the tree with an explicit stack. Each stack entry is a node of the input tree, the original label of its parent, and the list that receives its copy. The default leaves the part-of-speech tags unchanged.

  1. ANNOTATE(t) ▷ t: a treebank tree; ^ does not occur in its labels
  2. 1stack ← [(root of t, ROOT, out)]
  3. 2while stack is not empty do
  4. 3pop (u, p, dest)
  5. 4if u is a preterminal then append a copy of u to dest; continue
  6. 5append a new node with the label label(u)^p and an empty child list kids to dest
  7. 6for each child c of u, from right to left do push (c, label(u), kids)
  8. 7return the only node of out
  9. STRIP(t)
  10. 8return a copy of t in which every label x is cut at its first ^

The whole method is then:

  1. Annotate every training tree with ANNOTATE.
  2. Read off the PCFG by relative frequency, q(A→α)=count(A→α)/count(A)q(A \to \alpha) = \mathrm{count}(A \to \alpha) / \mathrm{count}(A), with AA an annotated label.
  3. Parse a new sentence with the annotated grammar, from the start symbol S^ROOT.
  4. Apply STRIP to the result and evaluate it with the PARSEVAL measures against the plain gold tree.

The root has no parent, so it gets the marker ROOT. The root may have any number of children; the transform does not depend on it. STRIP undoes ANNOTATE exactly, and every tree that the annotated grammar builds strips to a tree that the plain grammar can also build. Both facts are theorems, proved in the correctness proof. Whether the annotated grammar picks better trees is a measurement. ANNOTATE and STRIP each take time linear in the size of the tree.

Classic examples

  • Johnson's treebank PCFG. Johnson (1998) compared several tree representations for a PCFG read off the Penn Treebank and found that the parent transform improved on the plain treebank grammar, which Charniak (1996) had studied. His point was that the independence assumptions of a PCFG are a property of the tree representation, so changing the trees changes the model.
  • Unlexicalized parsing. Klein and Manning (2003) annotated each node with its v−1v - 1 nearest ancestors and kept only the last hh siblings in each rule. Their Figure 2 gives an F1 of 72.62 for the plain grammar (v=1v = 1), 76.81 with the parent (v=2v = 2), and 79.07 with the parent and grandparent and two siblings (v=3v = 3, h=2h = 2). They then added hand-made splits of single categories on top of this grammar.
  • Lexicalized models. The head-driven models of Collins condition the head child and the dependents of a node on the label of the node itself, which is the parent of the children being generated. This is the same kind of context, built into the probability model instead of the labels. The heads come from head rules.
  • Learned splits. Latent-variable PCFGs replace the fixed parent split by subcategories learned with EM. Petrov et al. (2006) start from a binarized grammar without parent labels and let the splits find such context where the data supports it.
  • Sequence models. A second-order hidden Markov model for tagging conditions each tag on the two previous tags. It is the same move on a chain: enlarge the state so that the model sees more history, at the price of more parameters.

Variations

  • Grandparent and higher orders. Annotate each node with its two or more nearest ancestors, as in NP^VP^S. Each order adds context and multiplies the number of rules, so the gain shrinks once the counts become sparse.
  • Tags too. Annotate the preterminals as well, so that a tag such as IN can tell a preposition under PP from a complementizer under SBAR. In the code this is the option tags=True.
  • Selective annotation. Annotate only the categories where it helps, chosen on development data. This keeps the grammar smaller.
  • Sibling context. Binarize the rules and keep only the last hh siblings in each intermediate symbol. This removes context from the right side of a rule, while parent annotation adds context from above. The two are usually tuned together.
  • Smoothing. Interpolate the annotated estimate with the plain one, as in smoothing for n-gram models, to give rules seen only in the plain treebank a nonzero probability.

Pitfalls

  • Pushing the new label. Writing line L6 as "push (c, label(u)^p, kids)" makes each label carry the whole chain of its ancestors, such as NP^VP^S^ROOT, which is a different and much sparser transform. The right line pushes the original label, "push (c, label(u), kids)".
  • Scoring annotated trees. PARSEVAL compares labels as strings, so NP^S never matches NP in the gold tree. Apply STRIP before evaluation.
  • The separator. Penn Treebank labels already contain - and =, as in NP-SBJ and NP=2. Using - as the separator makes STRIP cut off function tags as well, or cut at the wrong place. The code uses ^ and refuses labels that already contain it.
  • Function tags in the parent label. If function tags are kept, the parent part becomes S-TPC instead of S and the counts split further. Remove function tags and empty elements before annotation, as usual for treebank PCFGs.
  • Sparse rules. The annotated grammar has more rules, and each is seen fewer times. A rule that occurs under one parent but not under another gets probability 0 there, and a sentence can lose every parse. Smooth the annotated estimates, or back off to the plain grammar.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

parent_annotation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parent-annotation/. The authors are listed in prov/SJCKA7.jsonl.

"""Parent annotation of treebank trees, its inverse, and treebank rule estimates.

A tree is (label, word) for a preterminal, with word a string, and
(label, [children]) for any other node. annotate() gives every phrasal node
the label "X^P", where P is the original label of its parent, or root_parent
for the root. Preterminals are kept unchanged unless tags=True. strip() cuts
every label at the first separator, so strip(annotate(t)) == t whenever no
label of t contains the separator. Both walks use an explicit stack: the
children of a node are pushed in reverse, so they are popped, and appended
to the copy of their parent, from left to right.
"""

from collections import Counter
from fractions import Fraction
from typing import Dict, Iterable, List, Tuple, Union

Tree = Tuple[str, Union[str, list]]
Rule = Tuple[str, Tuple[str, ...]]


def is_preterminal(t: Tree) -> bool:
    return isinstance(t[1], str)


def _check_labels(t: Tree, sep: str) -> None:
    stack = [t]
    while stack:
        u = stack.pop()
        if sep in u[0]:
            raise ValueError("label %r already contains the separator %r" % (u[0], sep))
        if not is_preterminal(u):
            stack.extend(u[1])


def annotate(t: Tree, root_parent: str = "ROOT", sep: str = "^", tags: bool = False) -> Tree:
    """Return a copy of t in which each phrasal node X with parent label P is X^P."""
    _check_labels(t, sep)
    out: List[Tree] = []
    stack = [(t, root_parent, out)]  # @line L1
    while stack:  # @line L2
        u, p, dest = stack.pop()  # @line L3
        if is_preterminal(u):  # @line L4
            dest.append((u[0] + sep + p, u[1]) if tags else u)
            continue
        kids: List[Tree] = []
        dest.append((u[0] + sep + p, kids))  # @line L5
        for c in reversed(u[1]):  # @line L6
            stack.append((c, u[0], kids))
    return out[0]  # @line L7


def strip(t: Tree, sep: str = "^") -> Tree:
    """Return a copy of t with every label cut at the first separator."""
    out: List[Tree] = []
    stack = [(t, out)]
    while stack:  # @line L8
        u, dest = stack.pop()
        label = u[0].split(sep, 1)[0]
        if is_preterminal(u):
            dest.append((label, u[1]))
            continue
        kids: List[Tree] = []
        dest.append((label, kids))
        for c in reversed(u[1]):
            stack.append((c, kids))
    return out[0]


def rules(t: Tree) -> List[Rule]:
    """The rules of t, phrasal and lexical, in preorder."""
    out: List[Rule] = []
    stack = [t]
    while stack:
        u = stack.pop()
        if is_preterminal(u):
            out.append((u[0], (u[1],)))
        else:
            out.append((u[0], tuple(c[0] for c in u[1])))
            stack.extend(reversed(u[1]))
    return out


def treebank_pcfg(trees: Iterable[Tree]) -> Dict[Rule, Fraction]:
    """Relative frequency estimates q(A -> alpha) = count(A -> alpha) / count(A)."""
    counts: Counter = Counter()
    for t in trees:
        counts.update(rules(t))
    lhs: Counter = Counter()
    for (a, _), c in counts.items():
        lhs[a] += c
    return {r: Fraction(c, lhs[r[0]]) for r, c in counts.items()}


def tree_probability(t: Tree, q: Dict[Rule, Fraction]) -> Fraction:
    """The product of q over the rules of t (0 if a rule is missing)."""
    p = Fraction(1)
    for r in rules(t):
        p *= q.get(r, Fraction(0))
    return p


def read_tree(s: str) -> Tree:
    """Read a tree in bracket form, such as (S (NP (PRP she)) (VP (VBD left)))."""
    tokens = s.replace("(", " ( ").replace(")", " ) ").split()
    out: List[Tree] = []
    stack: List[Tree] = []
    pos = 0
    while pos < len(tokens):
        if out and not stack:
            raise ValueError("text after the tree")
        tok = tokens[pos]
        dest = stack[-1][1] if stack else out
        if tok == "(":
            if pos + 1 >= len(tokens) or tokens[pos + 1] in ("(", ")"):
                raise ValueError("a bracket needs a label")
            label = tokens[pos + 1]
            if pos + 2 < len(tokens) and tokens[pos + 2] not in ("(", ")"):
                if pos + 3 >= len(tokens) or tokens[pos + 3] != ")":
                    raise ValueError("expected ) after a word")
                dest.append((label, tokens[pos + 2]))
                pos += 4
            else:
                node: Tree = (label, [])
                dest.append(node)
                stack.append(node)
                pos += 2
        elif tok == ")":
            if not stack or not stack[-1][1]:
                raise ValueError("unbalanced ) or a phrase with no children")
            stack.pop()
            pos += 1
        else:
            raise ValueError("unexpected word %r" % tok)
    if stack or len(out) != 1:
        raise ValueError("unbalanced brackets or empty input")
    return out[0]
test_parent_annotation.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parent-annotation/. The authors are listed in prov/SJCKA7.jsonl.

import random
from fractions import Fraction

from parent_annotation import annotate, read_tree, rules, strip, tree_probability, treebank_pcfg

TREEBANK = [
    "(S (NP (PRP she)) (VP (VBD saw) (NP (DT the) (NN cat))))",
    "(S (NP (PRP he)) (VP (VBD fed) (NP (DT the) (NN dog))))",
    "(S (NP (DT the) (NN dog)) (VP (VBD saw) (NP (PRP her))))",
    "(S (NP (PRP they)) (VP (VBD left)))",
]


def test_annotate_example() -> None:
    t = read_tree(TREEBANK[0])
    assert annotate(t) == ("S^ROOT", [("NP^S", [("PRP", "she")]),
                                      ("VP^S", [("VBD", "saw"), ("NP^VP", [("DT", "the"), ("NN", "cat")])])])
    assert annotate(t, tags=True)[1][0] == ("NP^S", [("PRP^NP", "she")])
    assert strip(annotate(t)) == t
    assert strip(annotate(t, tags=True)) == t


def test_treebank_estimates() -> None:
    trees = [read_tree(s) for s in TREEBANK]
    q = treebank_pcfg(trees)
    assert q[("NP", ("PRP",))] == Fraction(4, 7)
    assert q[("NP", ("DT", "NN"))] == Fraction(3, 7)
    assert q[("VP", ("VBD", "NP"))] == Fraction(3, 4)
    qa = treebank_pcfg([annotate(t) for t in trees])
    assert qa[("NP^S", ("PRP",))] == Fraction(3, 4)
    assert qa[("NP^VP", ("PRP",))] == Fraction(1, 3)
    assert qa[("NP^VP", ("DT", "NN"))] == Fraction(2, 3)
    # every left-hand side sums to 1
    for grammar in (q, qa):
        sums = {}
        for (a, _), p in grammar.items():
            sums[a] = sums.get(a, 0) + p
        assert all(v == 1 for v in sums.values())
    # the tree probabilities of the page
    subj = read_tree("(S (NP (PRP she)) (VP (VBD saw) (NP (DT the) (NN cat))))")
    obj = read_tree("(S (NP (DT the) (NN cat)) (VP (VBD saw) (NP (PRP her))))")
    # the plain grammar cannot tell a pronoun subject from a pronoun object
    assert tree_probability(subj, q) == tree_probability(obj, q) == Fraction(3, 392)
    assert tree_probability(annotate(subj), qa) == Fraction(1, 64)
    assert tree_probability(annotate(obj), qa) == Fraction(1, 384)
    # a tree with a rule that is not in the treebank gets probability 0
    assert tree_probability(read_tree("(S (NP (PRP they)) (VP (VBD left)))"), q) == Fraction(1, 112)
    assert tree_probability(annotate(read_tree("(S (VP (VBD left)) (NP (PRP they)))")), qa) == Fraction(0)


def random_tree(rng: random.Random, depth: int):
    labels = ["S", "NP", "VP", "PP", "SBAR"]
    if depth == 0 or rng.random() < 0.3:
        return (rng.choice(["NN", "VB", "DT", "IN"]), rng.choice(["a", "b", "c"]))
    return (rng.choice(labels), [random_tree(rng, depth - 1) for _ in range(rng.randint(1, 3))])


def count_nodes(t) -> int:
    n, stack = 0, [t]
    while stack:
        u = stack.pop()
        n += 1
        if not isinstance(u[1], str):
            stack.extend(u[1])
    return n


def test_random_round_trip() -> None:
    rng = random.Random(1998)
    for _ in range(500):
        t = random_tree(rng, 5)
        a = annotate(t, root_parent="TOP")
        assert strip(a) == t
        assert count_nodes(a) == count_nodes(t)
        # the label of each annotated rule's children names the rule's own original label
        for lhs, rhs in rules(a):
            base = lhs.split("^")[0]
            for c in rhs:
                if "^" in c:
                    assert c.split("^", 1)[1] == base
        # the annotated grammar maps onto the plain one: the rule counts agree after stripping
        plain = sorted(rules(t))
        assert sorted((l.split("^")[0], tuple(c.split("^")[0] for c in r)) for l, r in rules(a)) == plain


def test_deep_tree() -> None:
    t = ("NN", "x")
    for _ in range(5000):
        t = ("NP", [t])
    a = annotate(t)
    assert a[0] == "NP^ROOT" and a[1][0][0] == "NP^NP"
    assert strip(a) == t


def test_errors() -> None:
    for bad in ["", "(S", "(S (NP x) y)", "(S (NP (NN x))) (S (NN y))", "( (NN x))", "(S )"]:
        try:
            read_tree(bad)
        except ValueError:
            continue
        raise AssertionError("accepted %r" % bad)
    try:
        annotate(("NP^S", [("NN", "x")]))
    except ValueError:
        return
    raise AssertionError("a label with the separator was accepted")

Exercises

  1. Show that a plain PCFG gives the same probability to a tree and to the tree in which the subject NP subtree and the object NP subtree are swapped. Use the example treebank to show that the parent-annotated grammar does not.
  2. If the plain grammar has the nonterminal set NN, show that the annotated grammar has at most ∣N∣(∣N∣+1)|N|(|N| + 1) nonterminals, and give a treebank where this bound is far from tight.
  3. Prove that STRIP(ANNOTATE(t)) = t. Then show that the statement is false if a label of tt may contain the separator.
  4. Write the grandparent version of ANNOTATE and compute, with exact fractions, the probability of she saw the cat under the grammar read off the example treebank.
Proof: Stripping undoes parent annotation, and the annotated parse of a sentence maps to exactly one plain parsefull

We use the pseudocode of the page: ANNOTATE (lines L1 to L7) and STRIP (line L8). A tree is a finite ordered tree whose leaves are words and whose internal nodes carry labels. A preterminal is an internal node whose only child is a word. Let #\# be the separator (the code uses ^), and assume that no label of the input tree contains #\#; the code checks this and raises an error otherwise. Write base(x)\mathrm{base}(x) for the part of a label xx before its first #\#, or xx itself if it has none.

Lemma 1: the shape is kept

ANNOTATE stops, and its output has the same shape as its input: there is a bijection ϕ\phi from the nodes of tt to the nodes of A(t)=ANNOTATE(t)A(t) = \text{ANNOTATE}(t) that keeps the root, the order of the children and the words. For every node uu with parent vv, the label of ϕ(u)\phi(u) is label(u)\mathrm{label}(u) if uu is a preterminal (in the default mode), and label(u) # label(v)\mathrm{label}(u)\,\#\,\mathrm{label}(v) otherwise. The root gets label(root) # ROOT\mathrm{label}(\text{root})\,\#\,\text{ROOT}.

Proof. Each node of tt is pushed exactly once: the root at line L1, and every other node at line L6, when its parent is popped. A preterminal is copied whole at line L4 and its word child is not pushed. So the loop of line L2 runs once per internal node of tt and stops. At line L3 the pair (u,p)(u, p) has p=label(v)p = \mathrm{label}(v) for the parent vv of uu, because line L6 pushes each child with the label of the node just popped, and p=ROOTp = \text{ROOT} for the root. Line L5 or L4 appends the copy of uu to the list of children of the copy of vv. The children of vv are pushed in reverse order, so the first child is popped first. All nodes pushed after it lie in its subtree, so the second child is popped only after the whole subtree of the first child, and so on. Hence the copies of the children of vv are appended in their original order. This defines ϕ\phi and proves the claim. □\square

Theorem 1: STRIP undoes ANNOTATE

STRIP(ANNOTATE(t))=t\text{STRIP}(\text{ANNOTATE}(t)) = t for every tree tt whose labels do not contain #\#. This also holds when the preterminals are annotated.

Proof. STRIP has the same walk as ANNOTATE, so by the argument of Lemma 1 it keeps the shape and replaces each label xx by base(x)\mathrm{base}(x). By Lemma 1, each label of A(t)A(t) is label(u)\mathrm{label}(u) or label(u) # p\mathrm{label}(u)\,\#\,p for the corresponding node uu of tt. Since label(u)\mathrm{label}(u) contains no #\#, in both cases base\mathrm{base} returns label(u)\mathrm{label}(u). □\square

Theorem 2: annotated parses map to plain parses

Let G′G' be the grammar read off the annotated treebank, and let GG be the grammar read off the plain treebank. Every rule X#P→Y1#X⋯Yk#XX\#P \to Y_1\#X \cdots Y_k\#X of G′G' maps under base\mathrm{base} to a rule X→Y1⋯YkX \to Y_1 \cdots Y_k of GG, and every parse of a sentence ww under G′G' is mapped by STRIP to a parse of ww under GG. Conversely, ANNOTATE maps every parse of ww under GG to exactly one tree over the annotated labels, and STRIP maps that tree back. So the parses that the annotated grammar can return, after stripping, are among the parses of the plain grammar, and two different annotated parses that are both images of ANNOTATE strip to two different plain parses.

Proof. A rule of G′G' comes from a node ϕ(u)\phi(u) of some A(t)A(t). Its left side is label(u) # p\mathrm{label}(u)\,\#\,p and its right side lists the labels of the copies of the children of uu, which by Lemma 1 are the labels of the children of uu, annotated or not. Applying base\mathrm{base} gives the rule that uu uses in tt, which is a rule of GG. A parse under G′G' uses only rules of G′G', so after STRIP, which keeps the shape and the words, it uses only rules of GG and has the same yield ww. ANNOTATE is a function, so it maps a plain tree to one annotated tree, and by Theorem 1 two different plain trees have different annotations. ■\blacksquare

The converse direction is not onto: an annotated tree whose labels do not follow the parent pattern, such as a child Y#ZY\#Z under a node X#PX\#P with Z≠XZ \ne X, is never produced by ANNOTATE. Grammars read off annotated trees contain no such rules, so a parser with G′G' only builds trees that follow the pattern.

References

  1. Mark Johnson, PCFG Models of Linguistic Tree Representations, pp. 613-632; the effect of the tree representation on a treebank PCFG, and the parent transform
  2. Dan Klein and Christopher D. Manning, Accurate Unlexicalized Parsing, ACL 2003, pp. 423-430; the orders of ancestor and sibling context and the F1 and grammar sizes of their Figure 2
  3. Eugene Charniak, Tree-bank Grammars, the plain treebank PCFG that parent annotation improves on

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/SJCKA7/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises