Discourse Relations and Coherence › Local coherence and the entity grid
Language AI HandbookAll chapters 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.
- Choose a set of entities that the document is about, after resolving mentions to entities.
- For each sentence and each entity, record the grammatical role of that entity in that sentence.
- Arrange the results as a matrix, with sentences as rows and entities as columns.
The resulting grid takes the form:
where:
- : the cell at row (sentence position) and column (entity), recording the grammatical role of entity in sentence
- : the sentence index, from to the number of sentences in the document
- : the entity index, from to the number of tracked entities
- the role value : one of (subject), (object or subject of a passive), (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]Expand
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]Expand
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 - SThe 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 be the draft’s grid, be the count for the pair , and be the sum of all included counts.
where:
- : the grid induced by the candidate ordering
- : an ordered pair of adjacent-sentence roles for one entity, where is the role in sentence and is the role in sentence
- : the number of times the transition occurs in , skipping pairs where both roles are (absent)
- : the smoothed probability for the joint ordered pair in the toy examples
- : the total number of nontrivial transitions in , so the score is a mean log-probability per transition
The mean is defined for . 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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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()) / nAdding 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]Expand
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]Expand

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!