Discourse Relations and Coherence › Local coherence and the entity grid

Michael BrenndoerferNovember 17, 202614 min read
Language AI HandbookAll chapters
Part 9 of 67Coreference, Discourse, Pragmatics, and Dialogue
Chapter 57Discourse Relations and Coherence › Local coherence and the entity grid
Reading section 6 of 13 · Local coherence and the entity grid · 14 minSection 6 of 13 · 14 min

Section 6 of 13 · 14 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Barzilay and Lapata’s entity grid records grammatical roles for discourse entities across sentences. Their model uses the relative frequencies of short role sequences down each column as features. Barzilay and Lapata trained a preference ranker on those features and evaluated it on particular text ordering and summary comparison tasks. Barzilay and Lapata, 2008, §§3–5.

Mentions, roles, and the grid

The construction has three steps.

  1. Choose a set of entities that the document is about, after resolving mentions to entities.
  2. For each sentence and each entity, record the grammatical role of that entity in that sentence.
  3. Arrange the results as a matrix, with sentences as rows and entities as columns.

The resulting grid takes the form:

Gi,j=role of entity j in sentence iG_{i,j} = \text{role of entity } j \text{ in sentence } i

where:

  • Gi,jG_{i,j}: the cell at row ii (sentence position) and column jj (entity), recording the grammatical role of entity jj in sentence ii
  • ii: the sentence index, from 11 to the number of sentences in the document
  • jj: the entity index, from 11 to the number of tracked entities
  • the role value Gi,jG_{i,j}: one of SS (subject), OO (object or subject of a passive), XX (other grammatical role), or −- (entity not mentioned in that sentence)

The role alphabet is small.

  • S means the entity is the grammatical subject.
  • O means the entity is a direct object, or the subject of a passive construction.
  • X means the entity appears in some other grammatical role.
  • - means the entity is not mentioned in that sentence.

Absence is a claim about mentions, not about involvement. An entity can be central to what a sentence describes and still be absent from it.

A full parse preserves distinctions that the four role values collapse. Here those four values give each sentence and entity a single cell. This makes it easy to count which roles continue or change from one sentence to the next.

Our annotation conventions differ in detail from the parser-derived roles used in the original work, so let's state them.

  • Role is assigned from the main clause. A mention inside a subordinate, relative, or because-clause is X.
  • Prepositional objects are X.
  • Coordinated main clauses each contribute a subject, so both subjects get S.
  • The entity set is a deliberate choice. We track six entities and ignore others such as the flow and the alarm.

These conventions are defensible and they are ours. A different analyst would produce a slightly different grid, which is itself one of the failure modes to keep in view.

Key points:

  • The rules are conventions, not grammatical necessities.
  • A different analyst would produce a different grid from the same sentences.

The conventions matter because a role label is only meaningful relative to a set of rules. In the original work, roles come from an automatic parser, and the parser's decisions are the rules. Here we write rules by hand, and the rules are choices. The rule that a because-clause mention is X is a choice, and a different analyst could argue that the sensor in S2 is a subject because it is the subject of its own clause. The rule that the entity set is fixed at six is a choice, and the flow and the alarm are left out because we decided the six tracked entities tell the story. Recording these choices lets a reader reconstruct the grid, which is the point of annotating by hand.

The hand-annotated mention list shows each role decision. Before calling build_grid, resolve multiple mentions of the same entity in a sentence to one cell role. The list below already has at most one row per sentence and entity.

PythonIn [9]
CollapseExpand
entities = ["sensor", "system", "valve", "loop", "operator", "review"]

mentions = [
    ("S1", "sensor", "S", "the Line 3 pressure sensor"),
    ("S2", "system", "S", "the control system"),
    ("S2", "valve", "O", "valve V-7"),
    ("S2", "sensor", "X", "the sensor, subject of the because-clause"),
    ("S3", "valve", "X", "V-7, object of the preposition of"),
    ("S3", "loop", "S", "the bypass loop, subject of the second main clause"),
    ("S4", "loop", "S", "the bypass loop"),
    ("S5", "operator", "S", "an operator"),
    ("S6", "review", "S", "the review"),
    ("S6", "sensor", "X", "the sensor, inside the because-clause"),
    ("S6", "valve", "X", "the valve, inside the because-clause"),
    ("S6", "loop", "X", "the bypass loop, inside the because-clause"),
]


def build_grid(sentence_ids, mention_list, entity_list):
    grid = [{e: "-" for e in entity_list} for _ in sentence_ids]
    position = {sid: i for i, sid in enumerate(sentence_ids)}
    for sid, entity, role, *_notes in mention_list:
        if sid in position:
            grid[position[sid]][entity] = role
    return grid


grid = build_grid(SENT_IDS, mentions, entities)
ConsoleOut [10]
CollapseExpand
sentence   entity role                                            mention
      S1   sensor    S                         the Line 3 pressure sensor
      S2   system    S                                 the control system
      S2    valve    O                                          valve V-7
      S2   sensor    X          the sensor, subject of the because-clause
      S3    valve    X                  V-7, object of the preposition of
      S3     loop    S the bypass loop, subject of the second main clause
      S4     loop    S                                    the bypass loop
      S5 operator    S                                        an operator
      S6   review    S                                         the review
      S6   sensor    X              the sensor, inside the because-clause
      S6    valve    X               the valve, inside the because-clause
      S6     loop    X         the bypass loop, inside the because-clause

   sensor system valve loop operator review
S1      S      -     -    -        -      -
S2      X      S     O    -        -      -
S3      -      -     X    S        -      -
S4      -      -     -    S        -      -
S5      -      -     -    -        S      -
S6      X      -     X    X        -      S

The sensor, the loop, and the valve each appear in three sentences. The system, the operator, and the review each appear in one. An entity mentioned in every sentence would fill its column. The overall density also depends on the number and occupancy of the other columns.

The mention table is worth reading closely, because every row is a decision a reader can check. S3's valve mention is X because V-7 is the object of the preposition "of", and the prepositional-object rule says that is X rather than O. S3's loop mention is S because the bypass loop is the subject of the second coordinated main clause, and the coordination rule says both main-clause subjects count. S6 assigns S to the review, the main-clause subject. The three tracked mentions inside its because-clause take X under the subordinate-clause rule. None of these rules is forced by the grammar of English. They are conventions that turn a syntactic fact into a grid cell, and a different set of conventions would produce a different grid from the same sentences.

From grid to score

The grid becomes a model through its transitions. For each entity and each pair of adjacent sentences, record the ordered pair of roles, provided at least one of the two roles is not absent. An entity that is absent from two consecutive sentences contributes nothing, since "-" to "-" says nothing about how the document moves.

Each draft produces counts over ordered pairs. The toy model learns a distribution over the allowed pairs by pooling counts from three annotated examples and adding a small pseudocount to each possible pair. Score a draft by averaging the log probability of its pairs under that distribution. Let GG be the draft’s grid, nG(r,r′)n_G(r,r') be the count for the pair (r,r′)(r,r'), and NN be the sum of all included counts.

score(G)=1N∑(r,r′)nG(r,r′)log⁡q(r,r′)\text{score}(G) = \frac{1}{N} \sum_{(r,r')} n_G(r,r') \log q(r,r')

where:

  • GG: the grid induced by the candidate ordering
  • (r,r′)(r,r'): an ordered pair of adjacent-sentence roles for one entity, where rr is the role in sentence ii and r′r' is the role in sentence i+1i+1
  • nG(r,r′)n_G(r,r'): the number of times the transition (r,r′)(r,r') occurs in GG, skipping pairs where both roles are −- (absent)
  • q(r,r′)q(r,r'): the smoothed probability for the joint ordered pair in the toy examples
  • N=∑(r,r′)nG(r,r′)N = \sum_{(r,r')} n_G(r,r'): the total number of nontrivial transitions in GG, so the score is a mean log-probability per transition

The mean is defined for N>0N>0. When there are no included pairs, both scorers below return NaN. Compare candidate scores only when both means are defined.

A higher score means the included pairs have higher average log probability under the fitted joint distribution. Taking a mean allows a comparison when two orderings contribute different numbers of pairs. The same role occurrence can belong to two adjacent windows. The result is a ranking statistic over those windows. A conditional prediction for the next role would require normalizing within the current role.

The score depends on roles only. The identity of the entity does not enter, so swapping two columns of the grid leaves the score unchanged. The model knows that some subject continued as a subject, not that the subject was the valve.

The score depends on adjacency only. Transitions are computed between neighbouring sentences. A fact established in S1 and contradicted in S6 is invisible to a model that only looks at S1 to S2, S2 to S3, and so on.

The score depends on a corpus. Whatever coherent text the transition distribution was estimated from determines what the model finds normal. A distribution estimated from news articles will have opinions about news articles.

They are the assumptions the model makes, and each assumption is also a claim about what coherence is. Role-only scoring claims that continuity of grammatical function is the signal that matters. Adjacency-only scoring claims that local smoothness is a good proxy for global structure. Corpus dependence claims that coherence is whatever the reference corpus exhibits. Each claim is approximately true for some genres and false for others, and knowing which claim is doing the work is what lets you decide whether the score applies to your document.

The original ranker and our two stand-ins

The original ranker learns weights that favor the preferred member of a pair of candidate documents. It uses grammatical roles extracted with a parser in the syntactically aware setting. Two small baselines below use the same grid representation with different scoring rules. All input annotations are supplied in the notebook. Barzilay and Lapata, 2008, §§3.3 and 4.1.

A pooled transition score. Annotate three short documents, pool the observed pairs, and add 0.5 to each potential pair. The example is small enough to reconstruct from a table of counts.

A hand-scored heuristic. We also write down a table of weights by hand, in the spirit of "subject to subject continuity is good, entity drop is bad". This heuristic has no empirical basis at all. Its only role is to let us check whether two scorers of the same grids can disagree, which they can.

The stand-ins make the arithmetic visible. To repeat the pooled estimator, collect a training corpus, annotate the entities under a stated convention, and estimate the smoothed joint pair probabilities. To replicate Barzilay and Lapata’s ranker, extract their grid features and train it on document preferences. The scores below illustrate the two stand-ins.

PythonIn [11]
CollapseExpand
from collections import Counter


def extract_transitions(grid, entity_list):
    counts = Counter()
    for i in range(len(grid) - 1):
        for entity in entity_list:
            left, right = grid[i][entity], grid[i + 1][entity]
            if left == "-" and right == "-":
                continue
            counts[(left, right)] += 1
    return counts


transitions_original = extract_transitions(grid, entities)
ConsoleOut [12]
CollapseExpand
Transition counts for the original order
  - -> S   4
  - -> X   3
  S -> -   3
  X -> -   2
  - -> O   1
  O -> X   1
  S -> S   1
  S -> X   1
Total transitions: 16

Eight of the fifteen possible transition types appear in the original order. A model fitted directly to these frequencies would give zero probability to the seven unseen types. The training example below uses smoothing to avoid zero probabilities.

The three short training documents are constructed examples. Their manually supplied grids track the named entities listed for each example and assign roles under the same stated rules used for the incident report.

PythonIn [13]
CollapseExpand
training_docs = {
    "pump": (
        [
            "The pump drew water from the tank.",
            "The tank had held water since the day before.",
            "The pump stopped at noon.",
        ],
        [
            ("T1", "pump", "S"),
            ("T1", "tank", "X"),
            ("T2", "tank", "S"),
            ("T3", "pump", "S"),
        ],
        ["pump", "tank"],
    ),
    "clerk": (
        [
            "The clerk filed the form on Monday.",
            "The clerk then sent the form for review.",
            "The auditor returned the form with a query.",
        ],
        [
            ("T1", "clerk", "S"),
            ("T1", "form", "O"),
            ("T2", "clerk", "S"),
            ("T2", "form", "O"),
            ("T3", "auditor", "S"),
            ("T3", "form", "O"),
        ],
        ["clerk", "form", "auditor"],
    ),
    "bench": (
        [
            "The sensor failed during the test.",
            "The technician replaced the sensor.",
            "The test resumed the next morning.",
        ],
        [
            ("T1", "sensor", "S"),
            ("T1", "test", "X"),
            ("T2", "technician", "S"),
            ("T2", "sensor", "O"),
            ("T3", "test", "S"),
        ],
        ["sensor", "technician", "test"],
    ),
}

pooled_transitions = Counter()
for name, (doc_sentences, doc_mentions, doc_entities) in training_docs.items():
    ids = [f"T{i + 1}" for i in range(len(doc_sentences))]
    doc_grid = build_grid(ids, doc_mentions, doc_entities)
    pooled_transitions.update(extract_transitions(doc_grid, doc_entities))
ConsoleOut [14]
CollapseExpand
Training documents: 3
Pooled transitions: 15
Distinct transition types seen: 8
  - -> S   4
  S -> -   4
  O -> O   2
  O -> -   1
  S -> O   1
  S -> S   1
  X -> -   1
  X -> S   1

The toy set contains 15 observations spanning eight of the 15 included pair types. Add-0.5 smoothing contributes a total pseudocount of 7.5. One third of the normalizer comes from smoothing, which gives positive mass to each of the seven unseen types.

The training texts and the incident report use the stated role conventions for their tracked entities. The pooled distribution reflects three short examples and the smoothing rule. On a larger corpus, check the consistency of role annotation and entity selection across the texts used for fitting and evaluation.

PythonIn [15]
CollapseExpand
import math

ROLE_ALPHABET = ("S", "O", "X", "-")
TRANSITION_TYPES = [
    (a, b)
    for a in ROLE_ALPHABET
    for b in ROLE_ALPHABET
    if not (a == "-" and b == "-")
]


def transition_probs(counts, types, k=0.5):
    total = sum(counts[t] for t in types)
    denominator = total + k * len(types)
    return {t: (counts[t] + k) / denominator for t in types}


transition_table = transition_probs(pooled_transitions, TRANSITION_TYPES, k=0.5)


def local_score(grid, entity_list, prob_table):
    counts = extract_transitions(grid, entity_list)
    n = sum(counts.values())
    if n == 0:
        return float("nan"), counts
    logp = sum(count * math.log(prob_table[t]) for t, count in counts.items())
    return logp / n, counts


# Illustrative hand weights. Not estimated from data and not taken from any paper.
HAND_WEIGHTS = {
    ("S", "S"): 1.0,
    ("S", "O"): 0.8,
    ("S", "X"): 0.3,
    ("S", "-"): -0.2,
    ("O", "S"): 0.6,
    ("O", "O"): 0.6,
    ("O", "X"): 0.2,
    ("O", "-"): -0.3,
    ("X", "S"): 0.5,
    ("X", "O"): 0.3,
    ("X", "X"): 0.1,
    ("X", "-"): -0.4,
    ("-", "S"): 0.2,
    ("-", "O"): 0.0,
    ("-", "X"): -0.2,
}


def hand_score(grid, entity_list, weights):
    counts = extract_transitions(grid, entity_list)
    n = sum(counts.values())
    if n == 0:
        return float("nan")
    return sum(count * weights[t] for t, count in counts.items()) / n

Adding discourse relations

Lin, Ng, and Kan illustrate a discourse-role matrix with annotated relations and use a discourse parser to supply relations in their experiments. Rows are sentences and columns are stemmed open-class terms. Cells record relation types and argument positions, and short role sequences become ranking features. On the task of ranking an original text above a sentence permutation, their discourse-role model with salience improved on the entity-grid baseline on the Wall Street Journal and Earthquakes test sets. The combined model improved on both components on all three test sets. Lin, Ng, and Kan (2011), §§4–5 and Table 4.

The design point is more general than the specific system. Entity transitions capture one kind of regularity, and relation transitions capture another. A document can keep its entities moving in plausible roles while attaching the wrong relations to them, which is exactly what the counterexample later in this chapter does.

The heatmap shows the smoothed probability for each permitted pair. Its cell labeled “excluded” identifies the absent-to-absent pair, which falls outside the fitted distribution.

PythonIn [16]
CollapseExpand
import numpy as np
from book_plot_style import PALETTE, polish_axes, use_book_style

role_order = ["S", "O", "X", "-"]
prob_matrix = np.array(
    [
        [transition_table.get((r, c), np.nan) for c in role_order]
        for r in role_order
    ]
)
VisualizationOut [17]
CollapseExpand
Heatmap of smoothed role transition probabilities for S, O, X, and absent roles.
Smoothed transition probabilities for the miniature entity-grid model. Rows are the role in sentence i and columns are the role in sentence i+1. The absent-to-absent transition is excluded by construction, and the add-0.5 smoothing keeps every permitted transition above zero. Use the color scale to compare probabilities. The cell marked excluded contributes no counts or probability.

The role grid encodes the same grammatical roles for the valve and bypass loop regardless of how the link between S2 and S3 is interpreted. An annotation of that link supplies information the grid lacks. A parser can still miss a real connection or supply a label whose interpretation the text does not support.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy