Structured Prediction and Parsing Evaluation
Master structured prediction for parsing: exact Eisner and CKY decoding, constrained inference, training objectives, and UAS, LAS, and F1 evaluation.
Language AI HandbookAll chapters Structured Prediction and Parsing Evaluation
Suppose every word chooses its highest-scoring head. Each attachment may look reasonable on its own, yet the combined output can contain a cycle and fail to be a tree. Parsing therefore asks you to choose compatible decisions, not just individually attractive ones. The HMMs and CRFs from the preceding part already introduced this distinction for tag sequences; trees add constraints on heads, roots, and, when required, projectivity. The practical problem is to find a high-scoring legal structure and then measure which parts of it are correct.
That shift changes three things at once, and this chapter is organized around them:
- Decoding. How do you find the highest-scoring structure without enumerating every candidate? The exact chart decoders here exploit how the score is built from smaller pieces.
- Training. What objective do you optimize when the loss is defined over whole structures rather than individual predictions? Local cross-entropy over candidate heads remains a useful training objective. A globally normalized alternative assigns probabilities to legal trees. The distinction is the normalization domain and the constraints included during training, not whether cross-entropy has a meaning.
- Evaluation. How do you measure partial credit, and what does a single number like "92.4 LAS" actually tell you? Attachment scores average over a specified set of words. Frequent relations contribute more than rare ones, so the aggregate can hide errors on constructions that matter to your application.
The questions also arise in sequence labeling, semantic parsing, coreference, and constrained generation:
- Which outputs are legal?
- How are they scored?
- Which errors does the metric count?
Their algorithms need not be the same. A chain may admit Viterbi decoding, a restricted tree factorization may admit a chart, and a more general graph or output constraint may require approximate search or another optimization method. Parsing gives us a concrete setting in which to examine those distinctions.
We assume you have seen context-free grammars and dependency trees in Part VII, and that the chart-parsing idea is familiar. What we add here is the structured-prediction view: why the recurrences have the shape they do, how hard constraints enter the search, how labels decouple from structure, and how to read parser numbers without fooling yourself.
The Structured Prediction Problem
A structured predictor chooses a legal output for input , here a sentence of tokens. The legal set may depend on the input. A maximum-score decoder selects a highest-scoring legal output.
where:
- : the input, a sentence of tokens
- : a candidate output structure drawn from , the set of valid structures for
- : the legal output set for , such as all well-formed dependency trees over the tokens
- : the model's scalar score for structure given input ; higher is better
- : the highest-scoring structure, the decoder's output
In ordinary multiclass classification, the candidate labels usually form a fixed finite list. In parsing, sentence length sets the token positions for candidate attachments and the boundaries available for candidate spans. Constituent counts can vary between legal trees for the same sentence, for example through a unary chain. Well-formedness restricts which combinations are legal. A structured task can also have the same legal output set for every input. A decoder must account for output dependencies when they affect which outputs are legal or how those outputs score. The argmax chooses the highest score, with a fixed tie-breaking convention when several structures share that score.
For dependency parsing, is a set of arcs where is the head index, the modifier index, and a labeled relation. For constituency parsing, we use half-open token boundaries: covers token indices with label . Dependency chart intervals below are inclusive; the separate conventions will be stated where they are used. In both cases the parts must form one well-formed tree. Arcs or spans can be legal on their own and still be incompatible in the same tree.
Why the Output Space Is the Hard Part
For , the number of rooted directed trees on fixed word positions is when any word may be the root and arcs are directed from heads to dependents. Cayley's count gives undirected labeled trees; choosing one of roots fixes the outward orientation. Here we count the lexical arcs and omit an artificial-root edge. At the count is one by convention. For 20 words the unrestricted count is . If every lexical arc can independently take any of 40 labels, each unlabeled tree has labeled versions, giving about possibilities. This deliberately unconstrained label count ignores relation-specific grammatical restrictions.
Even an imaginary decoder examining a billion complete labeled trees each second would need about seconds to enumerate that example's labeled output space. The point is the count, not a hardware benchmark: exhaustive enumeration already fails at a sentence length that appears in ordinary text. Restricting the allowed structures helps, but it does not turn enumeration into a practical general decoder.
Projectivity helps, but not enough. A projective tree is one where every subtree occupies a contiguous span, so no two arcs cross. The projective-tree recurrence below gives an asymptotic exponential growth constant of , with a polynomial prefactor; this is much slower than the super-exponential count of unrestricted trees. The exponential factor alone is not a finite-length count. At , the recurrence gives exactly 47,365,474,641,870 projective trees, approximately , a reduction of eleven orders of magnitude that still leaves too many candidates for a practical exhaustive decoder.
The lesson is that exhaustive search is impractical. Exact maximization over an opaque table of candidate scores has no general shortcut: in the worst case every entry must be examined. The decoders here exploit the specified factorization and legal output structure.
Factorizing the Score
The exact charts below use decomposability of the score. Instead of scoring a tree as an opaque object, score it as a sum over its parts:
where:
- : the score assigned to structure given input , built as a sum over its parts
- : the scored part occurrences in , such as arcs, labeled span occurrences, or production uses. A repeated part contributes once per occurrence.
- : the local score for one part given input
If the parts are arcs, the model is called arc-factored or first-order:
where:
- : an arc in with head , modifier , and label
- : the model's weight vector, with one entry for each of features
- : the feature vector for that arc given the input
An arc score may use the head word, dependent word, their distance, tags, or contextual representations computed from the entire input sentence. Arc factorization restricts dependence on the selected output: the score of one arc does not change according to which other arcs the decoder selects. It does not require a narrow input window. This distinction lets a contextual neural encoder use sentence-wide information while the structural decoder still optimizes a sum of individual arc scores.
A factorization is a choice of which subsets of the output get their own score. The score of the whole is the sum of the scores of the parts. Changing the factorization can change the model family, decoding algorithm, and computational cost. Different factorizations need not have different asymptotic costs; the chart states and algorithm also matter.
The factorization and the decoder's state design jointly determine complexity. The examples below exclude the cost of computing neural or hand-built part scores; is the number of arc labels and the number of binary grammar rules.
| Parts | Model family | Exact decoder example | Time |
|---|---|---|---|
| arc | first-order | Eisner, projective | |
| arc | first-order | optimized Chu-Liu/Edmonds arborescence | |
| labeled arc , independent labels | labeled first-order | label maximization plus Eisner | |
| successive same-side sibling pair | second-order, two arcs | sibling chart | |
| grandparent chain | second-order, two arcs | grandparent-augmented chart | |
| grand-sibling, three arcs | third-order | Koo and Collins chart | |
| labeled spans with binary rule constraints | constituency | CKY enumerating binary rules | $O(n^3 |
| production | weighted CFG or PCFG | CKY | $O(n^3 |
Order counts arcs in a part, not the number of word indices: a grandparent chain has two arcs and is second-order. Richer parts can require extra state, but each increase in order does not automatically add a power of . Koo and Collins (2010) describe cubic parsing with successive modifiers on the same side of their head and quartic grandparent and selected third-order parsers. For non-projective arborescences the table gives an optimized bound; a straightforward recursive Chu-Liu/Edmonds implementation can take cubic time. Enforcing exactly one lexical root child may add work beyond an unconstrained arborescence call. McDonald et al. (2005) explain the edge-factored reduction and its decoder implementations.
Neural scoring can change the information used to assign each part's score without changing that factorization. This makes it useful to report encoder/scorer cost separately from structural decoding cost when comparing complete systems.
The chart below compares illustrative operation counts for candidate lexical arcs, cubic charts, and quartic charts. They are operation-count surrogates with their constants suppressed, not measured timings or a universal mapping from model order to runtime. In particular, adjacent-sibling and first-order projective parsing can both be cubic.
PythonIn [3]Expand
import numpy as np
n_values = np.arange(5, 41)
candidate_arc_counts = n_values.astype(float) * (n_values - 1)
cubic_growth = n_values.astype(float) ** 3
quartic_growth = n_values.astype(float) ** 4VisualizationOut [4]Expand

The Price of Richer Parts
Why not score every complete tree with an unrestricted neural network? Without additional exploitable structure, an exact maximization would need to examine candidates that cannot be merged into reusable chart states. Exact enumeration is possible on tiny inputs, but the sentence-length count above makes it impractical in general. A system may instead use a restricted candidate list, beam search, or another approximate method. The appropriate claim is about this unrestricted scorer: it does not itself supply an efficient exact decoder or partition-function computation.
For chart-based parsing, a useful factorization balances the distinctions retained in a state against the cost of combining states. Larger parts can express interactions among selected arcs, but their tractability depends on the interaction pattern and the chosen algorithm. Other structured predictors can exploit graph algorithms, integer programming, or special problem structure instead of a chart. Identifying that structure is a modeling step, not a property guaranteed by the words “structured prediction.”
Dynamic Programming over Trees
Dynamic programming reuses solutions to subproblems that recur. The maximum-score charts here use boundary states that preserve which continuations are legal and what score each continuation adds, regardless of the internal derivation. Once the state is fixed, we can keep its best internal derivation. A tree-shaped output alone is insufficient; the factorization and the chart state must make that replacement valid.
The Recursive Decomposition of a Projective Tree
Take a complete rooted subtree whose descendants occupy positions through . Its root is the one node whose parent lies outside this subtree, unless it is the sentence root. Projectivity requires every descendant subtree to occupy a contiguous interval. The child subtrees on each side of therefore partition the remaining positions on that side without gaps or overlaps. An arbitrary interval of a projective tree need not be a complete subtree and need not have only one node with an outside parent.
That gives the fundamental recursion: a projective tree over with head is a head plus a sequence of projective subtrees to its left and a sequence of projective subtrees to its right. Every subtree is itself a projective tree over a contiguous subspan, so the same problem recurs on smaller inputs.
Memoizing an arbitrary span together with a free internal head would create states: two endpoints and one head index. Eisner's construction instead uses one-sided structures whose head is always an endpoint. That reduces the state space to entries, with a small constant number of direction and completeness types. The four charts below encode those boundary distinctions.
Eisner's Four Charts
We use a four-chart formulation of the projective parsing approach introduced by Eisner (1996), indexed by span endpoints and a direction bit. The four charts are not arbitrary; each one corresponds to a distinct state of a partially assembled subtree, and the distinction between them is what allows the recurrence to close without circular dependencies.
- : a complete right half headed by endpoint . The represented descendants cover the inclusive interval , and that side is complete. The full subtree of may also have a left half outside this interval.
- : a complete left half headed by endpoint , covering . The full subtree of may also have a right half outside the interval.
- : an incomplete span. It contains the arc , plus the subtrees hanging between them. The dependent can still grow children to its right, outside the span.
- : the mirror, containing arc .
The distinction between complete and incomplete is the crux. A complete span is finished on its represented side; an incomplete span is a head that has claimed one dependent but not yet finished building that dependent's subtree. These recurrences need the incomplete item to record the chosen arc while its dependent’s outward side is still unfinished. Concretely, when takes as a dependent you have committed to the arc but you have not yet committed to everything that hangs off , and that unfinished business is exactly what the chart records.
The Recurrences
Each single-token span is complete with score zero, . Work in order of increasing span width. For each wider span, fill its two incomplete directions before either complete direction, because a complete item can use an incomplete item of that same span. Write for the arc score.
where:
- : the best score of an incomplete span from to headed at , with as a rightward dependent
- : the arc score for the head taking dependent
- : the best complete rightward span headed at covering
- : the best complete leftward span headed at covering
- : the last position of the complete rightward span headed at before attaching
To build the item for , put the split between and . The complete span headed at covers , and the complete span headed at covers . Either piece can consist of its head alone. The two pieces are contiguous and disjoint before the link. Adding the arc makes the descendants in 's left piece descendants of as well. Interleaving the two pieces would violate projectivity.
The mirror image, for a leftward arc.
where:
- : the best complete rightward span headed at covering
- : the best incomplete rightward span headed at with dependent
- : the best complete rightward span headed at covering , giving its right subtree
- : the rightmost child of that closes the span
The rightmost child of is some . The incomplete item already contains the arc . The complete item supplies the rest of 's subtree on the right. This finishes the subtree rooted at and completes the right half headed at .
In the mirror recurrence, is 's leftmost child. The incomplete item already contains . Its partner supplies 's left half and completes 's left half. For the whole sentence, choose a root . Everything to its left is a left-complete span headed at , and everything to its right is a right-complete span headed at .
where:
- : the score of the best projective tree over the whole sentence
- : the index of the sentence's root token
- : the best complete leftward span headed at covering tokens
- : the best complete rightward span headed at covering tokens
Because the root is chosen once and the two halves share only the root node (whose base score is zero), no arc is counted twice and exactly one root exists.
Every chart entry covers a contiguous span. Incomplete items combine two disjoint spans. Complete items join spans that share a boundary token. Neither join interleaves the spans. So the algorithm cannot produce crossing arcs. Projectivity is enforced by the shape of the state space, not by a check after the fact. No separate post-decoding crossing check is needed for this algorithm. Building and combining the chart states still has the computational cost derived below.
Complexity
There are inclusive intervals, two directions, and complete and incomplete states. Each recurrence considers split positions, giving time and space, including backpointers and excluding score preparation. The illustrative quantity is one million at and one billion at , but those are growth-function values, not exact instruction counts or wall-clock predictions. Constants, implementation, batching, and hardware still matter.
Adding output interactions can enlarge the chart, but the cost must be derived for the particular state design. An adjacent-sibling chart can retain cubic time by sharing sibling subproblems. Adding a free grandparent index gives a quartic example, while selected third-order grand-sibling and tri-sibling factorizations also admit quartic algorithms. These examples show why “second-order” or “third-order” alone is not a complexity bound. They also explain why a sentence-wide encoder and an arc-factored decoder can remain attractive: the encoder supplies input context without introducing interactions among selected output arcs.
When the Tree Is Not Projective
Some dependency annotations contain non-projective arcs. When a gold tree is outside the projective output space, a projective decoder cannot reproduce it exactly, regardless of its scores. A parser can retain those annotations and use a suitable non-projective decoder, or train with an explicitly described projectivization and recovery procedure. The prevalence of such cases depends on the language, annotation scheme, and treebank; it should be measured rather than inferred from a language label alone.
For an arc-factored score without projectivity constraints, Chu-Liu/Edmonds finds a maximum-weight directed arborescence rooted at a specified artificial root. Build candidate edges from a head to each possible dependent, omitting self-edges and edges into the artificial root. The arborescence gives every lexical word one incoming edge and reaches every word from that root. An additional annotation requirement may demand exactly one lexical child of the artificial root, as in UD basic trees. An ordinary arborescence does not enforce that degree-one requirement automatically; it needs an explicit single-root restriction or a procedure such as conditioning on the lexical root candidate.
The algorithm starts with the best incoming edge for each non-root node. If these edges already form a rooted arborescence, they are optimal: no competing tree can improve any node's selected incoming score. If a directed cycle appears, the algorithm contracts it to one node. An entering edge carries its original weight plus the total weight of the cycle edges that would remain after it displaces the selected edge into its destination. For an edge leaving the cycle, keep its original weight. When several edges collapse to the same endpoints, keep a highest-weight representative and remember its original endpoints. Solve the reduced problem, then restore every cycle edge except the one displaced by the chosen entering edge. Simply deleting the smallest original cycle edge is not a general solution. The independently maximized incoming-score sum is an upper bound on the constrained maximum, because the relaxed selection ignores tree constraints.
The non-projective search space contains the projective trees, so its maximum model score cannot be smaller when all other score and root conventions match. This inclusion gives no guarantee about gold attachment accuracy: a higher-scoring tree can still be wrong. Compare decoders on the relevant development data, record the output-space restrictions, and inspect the non-projective cases separately. This separates a mathematical inclusion result from an empirical choice of parser.
Constrained Decoding
An exact maximum-score decoder returns a highest-scoring legal output when one exists. Making that set explicit separates the model's preferences from structural requirements and externally supplied restrictions. A learned preference can be violated on an unfamiliar input; an exact hard constraint excludes the violation whenever a feasible output exists.
What Counts as a Constraint
Constraints come in several flavors:
- Well-formedness. Every non-root word has exactly one lexical head; a designated root has none, or has an explicit artificial-root head in an augmented representation. The graph is acyclic. There is exactly one root. For a projective tree, every descendant subtree occupies a contiguous interval. This rules out crossing arcs. Checking lexical arcs for crossings alone can miss a discontinuous subtree. The projective chart below builds these requirements into its legal states and combinations; other decoders may enforce them differently.
- Annotation-specific restrictions. A project may forbid selected label/POS combinations or specify a punctuation convention. These rules must come from the actual annotation scheme and must allow its exceptions; a determiner-root ban or a universal preposition-head restriction is not a general definition of grammaticality. An incorrect hard mask can exclude the gold tree.
- Annotation-derived. For example, suppose an annotator requires "bank" to be the object of "robbed" in a partially annotated sentence. A downstream component needs a specific attachment. A partial parse from a chunker fixes some spans. These are hard requirements, not preferences.
- Efficiency. An arc-length cap removes candidate arcs beyond distance . This can reduce scoring work or help a decoder exploit sparsity, but masking alone does not change the loops of the cubic implementation below. Any faster bound needs a separate algorithm and a clear account of which chart states remain necessary.
Greedy Decoding and the Cycle Problem
The naive decoder picks, for each token independently, the head with the highest score:
where:
- : the modifier (dependent) token whose head we are choosing
- : the chosen head for
- : the score for attaching to head
Independent head selection is easy to parallelize, but it does not enforce a global tree constraint. In the example below the choices contain only lexical heads, with no root option, so every word receives an incoming edge and a directed cycle is unavoidable in the finite graph. The purpose is to expose that missing structural constraint. Adding an artificial-root option would permit valid outputs, but it would still not rule out cycles or enforce a required single lexical root.
PythonIn [5]Expand
tokens = ["the", "dog", "that", "barked", "ran"]
n = len(tokens)
score = np.full((n, n), 0.1)
np.fill_diagonal(score, NEG)
score[4, 1] = 3.0 # ran -> dog
score[1, 0] = 2.5 # dog -> the
score[1, 3] = 2.0 # dog -> barked
score[3, 2] = 2.2 # barked -> that
score[4, 3] = 1.0 # ran -> barked
score[3, 4] = 0.05 # barked -> ranConsoleOut [6]Expand
greedy heads: [1, 4, 3, 1, 0] forms a cycle: True
Each token picks its individually best head, and the result contains a directed cycle: "the" attaches to "dog", "dog" attaches to "ran", and "ran" attaches to "the". The cycle contains no root and is not a tree. Its sum of arc scores is well defined for the relaxed head assignment, but the assignment is outside the legal tree output space.
The constrained decoder cannot make this mistake, because the chart only contains states that correspond to spans of a tree.
Enforcing Constraints by Masking
An arc-local constraint can be imposed by giving each forbidden candidate arc a score of . If arc is forbidden, set before decoding. If a finite-score feasible tree exists, an exact decoder will exclude that arc and return the best tree among those satisfying the mask. If chart construction and root scoring finish without an arithmetic exception but find no finite full-sentence completion, the implementation must report infeasibility before reconstruction. The decoder below checks the best root score before backtracking.
Forbidding a particular arc is a local mask. To require an arc between distinct lexical words, forbid every competing incoming arc to and disallow as a root candidate. In an artificial-root representation, this includes forbidding . The lexical-root helper below takes a forbidden mask and has no argument for restricting root candidates. To require with that helper, also skip in the final root loop. Then verify that the remaining constraints are jointly feasible. Arc-length and label restrictions can also be expressed this way when they depend only on a candidate part and the input. The forbidden score is , not zero: zero could be more attractive than allowed negative scores. The guarantee requires exact inference and at least one finite-scoring feasible tree.
A mask is insufficient when acceptance depends on a combination of otherwise allowed parts. For example, allowing each candidate nsubj arc separately does not impose “at most one nsubj dependent for this head.” That restriction needs additional state or another constraint mechanism. Some such restrictions can be handled by specialized dynamic programs; others motivate a different optimizer. Under a projective decoder, forbidding crossings between same-labeled arcs adds nothing because all crossings are already forbidden.
When Masking Is Not Enough
For constraints that couple several arcs, integer linear programming is one option. Introduce binary variables , one per candidate arc, and write:
where:
- : a binary variable that is 1 if the labeled arc is in the parse, 0 otherwise
- : the model's score for labeled arc
subject to:
Here indexes lexical words and head is an artificial root. The second equality specifies exactly one lexical root child; omit it only if the target formalism allows several. Candidate variables exclude self-edges and edges into node . Add an acyclicity formulation, for example with flow constraints, ordering variables, or violated-cycle cuts. Further coupled linguistic restrictions can be added explicitly. General integer programming has no polynomial worst-case guarantee, although a particular arborescence problem without those extra interactions already has a polynomial graph algorithm. Solver runtime depends on the formulation and input; no fixed millisecond claim follows from sentence length alone.
Other choices include beam search over transition sequences, postprocessing a predicted graph, and decomposition methods that coordinate easier subproblems. Beam search can discard the model-optimal output; post-hoc repair may return a legal tree without maximizing the original score. Lagrangian methods relax coupling constraints. If the relaxation drops only equalities between copies of shared decisions, exact subproblem optima at the same multipliers certify optimality when they agree and form a feasible original output. The method need not find such agreement on every instance. Report the actual inference guarantee rather than treating all of these methods as interchangeable approximations.
Grammar-constrained generation also restricts the legal output space. A decoder may mask next-token choices that cannot extend the current prefix to an accepted string, using a tokenizer-aware grammar state. A context-free grammar can require more than finite-state memory. Valid completion then depends on correct token-to-text handling, the mask's supported grammar or schema constraints, a nonempty continuation set, and successful termination. Syntactic validity does not establish that generated values are true or satisfy every semantic requirement. See the Constrained Generation section of Semantic Parsing and Meaning Representations for these distinctions in text-to-SQL.
Span Scores and Constituency Decoding
The dependency model above factors over arcs. A constituency model can instead factor over labeled spans or over grammar productions. Both can support dynamic programming, but they retain different states and combine different parts. Comparing them makes the general design visible without identifying CKY and Eisner as the same algorithm.
Span-Factored Scores
For scoring, collect the labeled spans in a multiset. This preserves repeated occurrences with the same span and label, but can lose the order of unary nodes over that span. The natural factorization scores each constituent independently:
where:
- : a constituent spanning token indices through , using half-open boundaries , with label
- : the model's local score for that constituent given input
In a span-factored neural model, can score a label using contextual representations of the input span. A PCFG instead assigns local scores to productions such as and lexical rules. Its score is not, in general, a sum of scores depending only on , because the chosen child labels and rule matter. Both admit chart recurrences under the appropriate factorization. A span-scored grammar-constrained chart adds the parent span score to the best licensed child combination; the PCFG recurrence below adds a production score. Stern, Andreas, and Klein (2017) give a neural example based on independent label and span scoring.
CKY as Structured Prediction
CKY fills a chart over half-open spans and labels. For a span and label , the best score is the best way to split the span into two children whose labels are licensed by a rule:
where:
- : the best score for label over token indices
- : the boundary dividing into children and
- : a binary grammar rule whose parent label is and whose child labels are and
- : the rule's score, for example a log PCFG probability
- and : the best scores of the left and right child constituents
A one-word span receives its lexical/preterminal score. The displayed recurrence assumes binary rules; unary rules require a separate closure procedure or a preprocessing representation, and arbitrary unary cycles require additional care. The tutorial grammar below has only binary and lexical productions, so it needs no unary closure. Its supplied preterminal tags are fixed inputs, not predictions from another model.
The two algorithms share the same split-and-combine shape. Eisner combines inclusive intervals, and its complete joins share the boundary token. CKY combines two disjoint half-open subspans, and . Eisner tracks which end holds the head and whether the span is complete. CKY tracks the category. Both combine reusable substructures. Eisner takes cubic time with quadratic chart storage; the shown CKY loops take time when every binary rule is inspected at every split, with chart entries for category set .
In log-score space, maximum-score decoding combines child scores by addition and alternatives by . Summing the weights of all derivations keeps the child-score additions but replaces the alternative maximum by log-sum-exp. In ordinary nonnegative weight space, these are max-product and sum-product recurrences instead. The change of algebra reuses the same legal decomposition; it does not mean that adding arbitrary raw scores sums probabilities. Decoding and partition-function computation are closely related chart operations when the factorization satisfies these assumptions.
Inside, Outside, and Marginals
The inside weight sums the nonnegative, unnormalized weights of all compatible subtrees rooted at a constituent:
where:
- : the inside weight for category over
- : a subtree rooted at that constituent
- : the raw score of subtree
- : the unnormalized weight of , summed across all such subtrees
The outside weight sums compatible surrounding contexts, with the constituent's entire inside derivation removed. Its factors must exclude those already counted by ; otherwise their product would count them twice. For the finite binary/lexical derivations considered here, the context leaves a single category- hole at . This yields:
The marginal probability that a parse contains the constituent is
where:
- : the marginal probability that a parse contains constituent
- : the inside weight of the constituent
- : the outside weight of the constituent
- : the partition function, the sum over all trees rooted at the start symbol
With one fixed start category , sums all accepted full derivations and the root outside weight is one. The product sums derivations containing the particular chart item; division by positive finite gives its marginal. This interpretation assumes the item occurs at most once in each derivation, as in the binary/lexical charts here. Inside-outside plays the role on these trees that forward-backward plays on chains, rather than being an identical recurrence with the indices renamed. For the chain recursions and their use in computing marginals, see Sutton and McCallum (2010), §3.1.
Decoding for the Metric
Viterbi decoding returns a highest-probability complete derivation. When each scored tree corresponds to exactly one modeled derivation, Viterbi also selects a most probable tree. A most probable tree minimizes expected exact-tree zero-one loss. If several derivations represent the same scored tree, sum their probabilities before comparing trees. Other evaluation losses can prefer another tree. Constituent marginals aggregate probability over all trees containing each span, so a span can have high marginal probability even when the single most probable full tree omits it.
For a fixed predicted constituent set and random gold set , linearity of expectation gives
Here is a labeled constituent and the probability comes from the model's distribution over legal gold trees. A chart that maximizes the sum of these marginal scores, while still requiring a legal predicted tree, maximizes expected overlap. Greedily selecting high-marginal spans without a tree constraint can instead select crossing or otherwise incompatible spans. A marginal probability is also different from a max-marginal score, which uses the best complete structure containing a part rather than summing probabilities.
Expected F1 requires more care. For a positive combined scored count, . If both scored constituent counts are fixed across all relevant trees and their sum is positive, maximizing expected overlap also maximizes expected F1. For multiset scoring, overlap counts matched occurrences with multiplicity. The fixed-count argument also applies to expected multiset overlap, but a single presence probability per constituent need not give that overlap. If a prediction contains copies of a labeled constituent and the gold count is , the expected number of matches for is . When both counts are zero, use the scorer’s declared convention. If unary chains, branching, or normalization make the counts vary, raw constituent marginals alone do not establish that equivalence. Goodman (1996) studies parsing algorithms matched to particular recall and tree criteria; it is important to retain the criterion and its assumptions when applying that result.
The practical lesson is to choose a decision rule for the intended loss and legal output space. Under additive per-token zero-one loss and unconstrained label choices, choosing the highest-marginal label at each token minimizes expected token error, but those choices may violate sequence constraints and they do not automatically optimize a sequence- or span-F1 metric. Loss-aware decoding is a modeling option, not a guarantee that one named decoder will improve every reported score.
Labeled Attachment
Labels add a dimension to the output space. In the lexical-root convention used for the dependency decoder, a tree with lexical arcs has labeled versions if each arc can take any of the same labels independently. Under that assumption, naive enumeration multiplies the candidate count by . Independent local label maximization can avoid enumerating those combinations.
Decoupling Structure and Labels
Suppose the score decomposes as
where:
- : a labeled arc with head , modifier , and label
- : the score for the unlabeled attachment of to
- : the score for assigning label to the arc given the attachment
Then
The inner label maximum is independent for each candidate arc. An arc with no legal label is unavailable to the structural decoder. Compute an augmented score and best-label backpointer for every allowed , run the unlabeled structural decoder, and then read the stored labels for its selected arcs. With possible lexical non-self arcs and labels, preparation takes comparisons; Eisner then takes time. This gives , excluding the model's score-computation cost. It is not an extra factor of .
The collapse is exact when both the score and the legal label assignments factor independently over the selected arcs. A constraint such as “this head has at most one nsubj dependent” couples labels across arcs and can invalidate it. In contrast, a rule that restricts one arc's labels using that arc's head POS tag is still local and can be folded into its label maximum. Coupled label models need an inference procedure for their actual interactions. The independent-label bound does not extend to arbitrary global constraints. Their representation and how they couple arcs can add to the cost.
This distinction is separate from a two-stage pipeline that first decodes only arc scores and then labels the selected arcs. Ignoring label scores during structure selection need not maximize the combined score displayed above. Whether the combined objective improves LAS is empirical and depends on training, scoring, and data; no universal accuracy gap follows from separability alone.
A simpler fixed-tree comparison makes the label-space reduction visible. On one already-selected tree with lexical arcs and 40 labels, enumerating all label combinations would examine assignments. Independent label maximization instead checks scores. The plot shows this fixed-tree comparison only; preparing labels for every candidate tree edge before structural decoding has the quadratic-in- cost derived above.
PythonIn [7]Expand
import numpy as np
label_n = np.arange(2, 13)
label_combinations = 40.0 ** (label_n - 1)
decoupled_checks = (label_n.astype(float) - 1) * 40.0VisualizationOut [8]Expand

When Labels Interact
Three distinctions help you decide whether a label model needs richer inference:
- Output coupling. A task-specific cardinality condition such as at most one subject label for a head depends on multiple selected arcs. An arc-local mask does not count them.
- Local label restrictions. Restricting labels according to a candidate head/dependent POS pair remains local, even though the allowed labels differ across arcs. It does not by itself defeat independent maximization.
- Linguistic coverage. A relative clause may lack an overt relativizer, and coordination or annotation conventions may complicate a subject-count heuristic. Do not promote such a heuristic to a universal grammar rule without examining the target scheme.
Higher-order factors can score selected sibling or grandparent combinations, while an explicit constraint may require a count or another additional state. Their complexity must be derived for the chosen model. Adjacent siblings, grandparents, and third-order grand-siblings are distinct factorizations with different possible chart designs, as the earlier table shows.
Training Objectives for Structured Predictors
The training objective shapes the scoring function. The following sections compare local cross-entropy, global likelihood, and margin-based objectives.
Local Cross-Entropy
A local approach treats each decision as an independent classification problem. For each token, predict a distribution over heads with a softmax, and minimize the cross-entropy against the gold head. For each arc, predict a distribution over labels and do the same.
This is local training: each head softmax is normalized over the possible heads of one dependent, so selecting from it already gives that word one head. What it does not impose is that all selected heads jointly form an acyclic tree with the required root convention. During supervised training, label cross-entropy can condition on a gold head, as in this biaffine dependency parser. During decoding, the trained label scorer can label selected candidate arcs; record the actual conditioning for the system. These are valid local conditional probabilities under the model, but multiplying them over all independent head choices does not generally give a normalized distribution restricted to legal trees. Local or global models can be miscalibrated on held-out data; consistency of the training annotations does not guarantee calibration.
Global Likelihood and the Inside Algorithm
A conditional random field defines a distribution over legal structures when its partition function satisfies .
where:
- : the conditional probability of structure given input
- : the model's score for structure
- : the set of valid structures for input
- : the partition function, summing over all valid
The inside algorithm sums derivation weights. To recover the structure weights in the definition above, sum the weights of all derivations representing each structure. Summing those grouped weights gives the intended when each group has its structure's intended weight. This holds, for example, if every legal structure has one derivation of the same weight. Training maximizes the gold tree’s log-likelihood. For the objective below to be finite, the gold tree must be legal and have a finite score.
For a fixed finite legal set and finite feature vectors, a linear score gives a negative log-likelihood gradient of expected feature counts minus observed feature counts.
Here is the complete structure's feature vector and the expectation ranges over the legal output set. Differentiating the positive log-likelihood reverses this sign. For decomposable features on the finite projective charts considered here, inside-outside marginals provide the expectations; differentiating a log-partition computation is another implementation route. A different output family can need a different partition-function algorithm. The Conditional Random Fields chapter introduces the corresponding negative log-likelihood objective for tag sequences. For a linear score, the negative log-likelihood gradient has the same expected-minus-observed form in both cases, with tree states replacing chain states for the expectation here.
The payoff is an explicitly normalized distribution over the selected legal structures, with marginals defined by that distribution. Its probabilities are only as useful as the model and data justify; global normalization alone does not establish calibration to real error frequencies. For the stated projective factorization, max decoding and sum-based partition computation have similar polynomial chart shapes, but local head normalization is a different computational problem and need not share their asymptotic cost.
Max-Margin and the Perceptron
The structured perceptron uses an online update: predict the highest-scoring structure and, when it differs from gold, add the gold-minus-predicted feature vector to the weights. With zero initialization, exact decoding, a positive separating margin on the finite training set, and bounded feature differences, the update makes only finitely many training mistakes. The same argument need not apply with approximate decoding or nonseparable data.
The structured SVM adds a margin and a loss term:
where:
- : the weight vector being learned
- : a positive weight on the hinge loss. A larger penalizes margin violations more relative to the squared norm.
- : an example (sentence) index, with gold structure and input
- : a legal candidate structure for , drawn from
- : the loss (for example Hamming or F1 loss) incurred by predicting when the gold is
- : the feature vector for a structure on input
The inner max is loss-augmented decoding: find the structure that maximizes score plus loss. For Hamming loss over aligned attachment decisions, add one to each incorrect candidate decision before maximizing, or equivalently subtract one from the gold decision up to a fixed additive constant. Boosting gold arcs would have the opposite effect. If the loss scores the root choice, apply the same adjustment when comparing the final root candidates. F1 loss generally does not decompose into independent arc penalties, so its loss-augmented inference needs a separately justified method.
The Loss-Metric Mismatch
These training objectives differ from the reported evaluation scores, even when the hinge uses a loss defined from one of those scores. With the same nonempty set of aligned scored words and the same root convention, head Hamming loss divided by the scored word count equals . Log-likelihood measures the probability assigned to gold structures on a log scale. UAS counts correct heads, and constituency F1 measures labeled constituent overlap. A model can improve likelihood while getting worse F1. Compare both on held-out data.
The mismatch has three practical consequences:
- Select with a declared development objective. If the deployment goal is LAS, monitor development LAS as well as loss and fix the model-selection rule before testing. Their optima need not occur at the same checkpoint.
- Measure calibration separately. Both local and globally normalized models produce probabilities in their specified domains. Check their reliability against observed outcomes if you intend to interpret confidence numerically.
- Separate training from decision rules. Minimum-risk inference chooses an output for a specified test-time loss. During margin-based training, loss-augmented inference finds a legal structure maximizing model score plus loss.
Evaluating Parsers
Two parsers can have similar LAS values and different error profiles. The aggregate score does not show which heads, labels, or constructions account for the difference.
Attachment Scores
The two standard dependency metrics are unlabeled attachment score and labeled attachment score:
where:
- : the number of evaluated tokens
- and : the predicted and gold heads for token
- and : the predicted and gold labels for token
- : the indicator that returns 1 when its condition holds and 0 otherwise
With the same aligned words and scoring mask, LAS is at most UAS. Their difference is the fraction of evaluated words whose head is correct but relation label is wrong. It is not the total rate of incorrect labels, because words with wrong heads already fail both metrics.
These formulas assume identical gold and predicted word segmentation, nonempty evaluation masks, and one predicted attachment per scored word. Otherwise word alignment and precision/recall denominators must be specified. Several choices change the quantity being measured:
- Punctuation. Declare the scorer's inclusion mask. The CoNLL 2018 UD shared-task protocol includes punctuation in LAS; another experiment may exclude it explicitly. Neither the direction nor size of a score change is universal.
- Root handling. In UD's CoNLL-U format, a lexical root has
HEAD=0, referring to a notional root, rather than pointing to itself. The hand-built fixtures below use zero-based lexical indices and a self-head root marker only as a documented local convention. The simulator later uses-1for the root; do not export either fixture representation as CoNLL-U without conversion. - Segmentation and alignment. UD distinguishes orthographic multiword tokens from syntactic words. In raw-text evaluation, the scorer aligns words and their heads before attachment comparison. The CoNLL 2018 scorer computes precision and recall over system and gold words, then F1, so segmentation failures cannot be handled merely by zipping rows.
- Labels and versions. Record the treebank release and label normalization. CoNLL 2018 truncates relation labels at the first colon for its primary LAS score.
objanddobjremain distinct base relations under that rule. The fixtures below compare literal labels on prealigned words using their declared root convention. - Basic versus enhanced dependencies. Basic UD annotations are trees; enhanced annotations can contain additional edges and empty nodes. Specify the target graph and edge-matching metric. An enhanced graph score cannot be compared with basic word-head accuracy as if the targets were identical.
For an aligned, fixed-word test set the simple attachment fractions are useful. For a shared-task result, use the published scorer and configuration rather than assuming that a short custom function reproduces every normalization and alignment rule. Keep the protocol beside the score so a reader can determine what a reported difference means.
What the Number Hides
UAS and LAS are averages, and averages hide distributions. Four breakdowns are worth computing routinely:
- UAS minus LAS. The gap counts label-only errors on correctly headed words. It motivates inspecting label decisions, but does not identify their cause: shared encoder features, label scoring, or training coverage may contribute.
- Accuracy by attachment distance. Measure accuracy by gold attachment distance rather than assuming all distances behave alike. For illustration, a system could have 92 UAS overall, 97 on distance-1 arcs, and 65 on distance-10 arcs; these are hypothetical values, not benchmark measurements. If your downstream task cares about long-distance dependencies, report accuracy for those attachments as well.
- Accuracy by direction. Compare accuracy on leftward and rightward gold attachments under the same scoring convention. Measure any difference for the target parser and corpus.
- Per-relation F1. A low-support relation can have poor precision or recall while contributing little to aggregate LAS. Report support alongside per-relation scores. Macro-averaging gives each included relation equal weight, with an explicit convention for absent labels.
Constituency Evaluation
PARSEVAL-style constituency scoring compares predicted labeled constituents with gold constituents after a specified normalization. Ordinary sets suffice when each labeled span occurs at most once in each scored output. Use multisets when repeated same-labeled unary constituents are scored separately:
where:
- : the multiset of scored labeled constituents the parser produced
- : the multiset of scored gold labeled constituents
- : matched constituent count, clipping each labeled-span multiplicity to the smaller gold/predicted count
- and : labeled precision and recall
A constituent matches only if its span endpoints and category label match under the declared normalization. Each displayed precision or recall ratio requires its own positive denominator. For F1, the equivalent count form gives zero when only one multiset is empty or when there are no matches. If both are empty, the denominator is zero and a scorer must declare a separate convention. PARSEVAL configurations also differ in the following ways:
- Punctuation.
EVALBuses a parameter file controlling removals and label equivalences, including punctuation treatment. Report that file and scorer version when comparing scores. - Unary rules. Whether unary productions count as separate constituents varies. PTB has many unary rules, so this matters.
- Preterminal tags. Specify whether POS preterminals are scored or excluded. Adding them changes the evaluated constituent population and can change the result; it does not guarantee an increase.
- Root. Whether the root node counts as a constituent.
- Sentence-level versus corpus-level averaging. Corpus micro-F1 pools matched, gold, and predicted counts before forming F1. Sentence macro-F1 averages the individual sentence F1 values. Relative to pooling, it gives sentences with fewer predicted and gold constituents in total more weight; either average can be larger depending on the error distribution.
Constituent F1 gives partial credit for each matched labeled span, regardless of whether that span controls an attachment distinction important to a downstream application. Producing only a few safe spans may preserve precision, but omitting other gold spans lowers recall; the metric does penalize that omission. Report sentence exact match alongside F1 when agreement on every scored constituent matters. It is the fraction of sentences whose entire scored multiset matches gold. To check full ordered-tree agreement, compare the normalized trees directly. A single wrong constituent makes exact match zero for that sentence even when most other spans are right. The relationship depends on sentence length and the evaluation configuration, so it should be measured rather than replaced by a universal benchmark percentage.
Exact Match and Sentence-Level Scores
Three dependency summaries answer different questions:
- Sentence exact match: the fraction of sentences for which every scored head and relation label agrees with gold. Name this criterion explicitly because metric labels differ between tools.
- Content-word attachment: a metric such as CLAS focuses attachment scoring on a declared content-relation subset. It remains a partial-credit attachment metric, not sentence exact match. The CoNLL 2018 protocol describes its morphology-aware extension MLAS and its relation inventory.
- Sentence macro-LAS: the mean of per-sentence LAS fractions, as opposed to micro-LAS over all scored words.
Sentence exact match cannot exceed sentence macro-LAS when both use the same positive-word masks: within each sentence, the exact-match indicator is at most that sentence's LAS. There is no fixed ordering against word-level micro-LAS because micro-LAS weights sentences by their scored word counts. Sentence macro-LAS and content-word LAS need not be lower than micro-LAS. Exact match records whether an error occurs anywhere in a sentence; it does not by itself establish that one error caused another. Distinguish this all-or-nothing criterion from causal error propagation in a particular parsing algorithm.
Statistical Significance
A small score difference may or may not be stable across samples. Compare systems on the same held-out inputs, report the effect size, and use an uncertainty procedure whose sampling unit matches the data. Dror et al. (2018) discuss how NLP tasks, metrics, and experimental designs affect significance-test selection.
- Paired bootstrap: for independent, identically distributed sentence pairs, resample the same sentence indices with replacement for both systems, recompute the corpus metric from pooled counts within each sample, and examine the distribution of score differences. If sentences within documents or speakers are dependent, resample those larger paired units when they are suitable and can be treated as independent and identically distributed. This ordinary paired bootstrap avoids a specified parametric score distribution, but still needs a representative sample of independent, identically distributed units. The interval construction and number of replicates should be stated.
- Paired binary tests: McNemar's test uses discordant outcomes where only A or only B is correct. Treating every attachment token as an independent observation can be inappropriate when errors within a sentence are dependent. A sentence-exact binary outcome can fit a paired test under independent sentence sampling; small discordant counts need an appropriate exact rather than large-sample approximation.
A measured 0.4-point LAS increase is an effect on the test set, even when its uncertainty includes zero. A significance result does not establish a practically useful difference, robustness to domain shift, or independence from training randomness. Keep development-based selection separate from the final test, and state whether uncertainty covers test sampling, training seeds, or both. This makes the comparison's claim narrower and more interpretable than treating an arbitrary point threshold as reliable or unreliable.
Worked Example: UAS and LAS by Hand
Take this hand-built teaching fixture with fixed tokenization. Heads are zero-based lexical indices and the root points to itself as a local marker. Labels follow an older dependency-label style, with a deliberately different predicted obj string; this is not a UD v2 or official EVALB/shared-task example. All 11 words, including punctuation and the locally marked root, are scored exactly as written.
| i | Token | Gold head | Gold label | Pred head | Pred label |
|---|---|---|---|---|---|
| 0 | The | 2 | det | 2 | det |
| 1 | old | 2 | amod | 2 | amod |
| 2 | man | 7 | nsubj | 7 | nsubj |
| 3 | who | 4 | nsubj | 4 | nsubj |
| 4 | lives | 2 | rcmod | 7 | rcmod |
| 5 | next | 6 | amod | 6 | amod |
| 6 | door | 4 | npadvmod | 4 | npadvmod |
| 7 | reads | 7 | root | 7 | root |
| 8 | many | 9 | amod | 9 | amod |
| 9 | books | 7 | dobj | 7 | obj |
| 10 | . | 7 | punct | 7 | punct |
Count the errors:
- Token 4: predicted head 7, gold head 2. Head wrong. Counts against both UAS and LAS.
- Token 9: predicted head 7 (correct), predicted label
obj(golddobj). Head right, label wrong. Counts against LAS only.
So , head errors , label-only errors .
The gap is , approximately 9.09 percentage points, and comes from the one label-only error. UAS alone would miss that label mismatch; LAS alone would combine it with the head error. Looking at the two scores and the token-level errors reveals both defects in this fixture. Whether either error matters more downstream cannot be read from their equal contribution to the aggregate.
Now suppose the model produced the exact same heads but every label was wrong. UAS would stay at approximately 0.909 while LAS dropped to 0.0. This is why reporting both matters, and why the UAS-LAS gap is a diagnostic rather than a nuisance.
Implementation: Decoders, Scorers, and Metrics
The rest of the chapter builds the pieces. The examples are small enough to trace the arithmetic. The two exact chart decoders are compared with exhaustive enumeration on their small fixtures.
Setting Up
The examples use Python 3.11, NumPy 2.4.2, and Matplotlib 3.10.8 in the book's locked environment. They train no model and download no corpus. The synthetic experiment uses its own default_rng(seed=7); the hidden shared plotting setup is seeded once before the chapter runs. The cells below calculate the implementation outputs and simulation values; the preceding 11-word table is a separate hand calculation. The later corpus pools that fixture with three other sentences, so its aggregate scores use 35 words.
Counting the Search Space
Before running the exact chart decoders, it helps to see how fast the space grows. The recurrence for projective trees counts a projective forest on each side of the root. The empty forest gives . If , the series for nonempty trees is , with marking the root. A forest is empty or starts with a tree followed by a forest, so . Set , so . Here is the coefficient of in , and is a dummy variable for the coefficient extraction. For , Lagrange inversion gives . Stirling’s formula gives the growth scale. The recurrences for the coefficients are:
where:
- : the number of projective dependency trees on tokens
- : the number of projective forests on nodes
- : the root position, splitting the sentence into left and right forests
- : the size of the leftmost tree in the forest decomposition
PythonIn [10]Expand
def projective_tree_counts(nmax):
P = [1] # P[0] = 1 by convention
A = [1] # A[0] = 1, empty forest
for n in range(1, nmax + 1):
p = sum(A[r] * A[n - 1 - r] for r in range(n))
P.append(p)
a = sum(P[m] * A[n - m] for m in range(1, n + 1))
A.append(a)
return P, A
P, A = projective_tree_counts(20)ConsoleOut [11]Expand
n= 3 unlabeled trees: all= 9 projective= 7 n= 5 unlabeled trees: all= 625 projective= 143 n=10 unlabeled trees: all= 1,000,000,000 projective= 690,690 n=15 unlabeled trees: all= 29,192,926,025,390,625 projective= 5,225,264,024 n=20 unlabeled trees: all=5,242,880,000,000,000,000,000,000 projective= 47,365,474,641,870
For a 20-token sentence there are about unlabeled dependency trees, of which about are projective. Both counts motivate efficient search; the dynamic programs also require the factorizations and sufficient states described above.
VisualizationOut [13]Expand

A Dependency Decoder
The implementation below follows the four Eisner recurrences and stores backpointers for reconstruction. A computed nonfinite total from adding finite reachable scores raises FloatingPointError. If chart construction and root scoring finish without an arithmetic exception but find no finite full-sentence completion, the decoder raises ValueError before reconstruction. Rounding can change which tree wins even when all reachable score sums stay finite. A sum just above the finite range can also round to a finite value. Backtracking is recursive, so a sufficiently deep reconstruction can exceed Python's recursion limit.
PythonIn [14]Expand
def eisner(score, forbidden=frozenset()):
"""Best projective dependency tree under an arc-factored score."""
score = np.asarray(score, dtype=float)
if score.ndim != 2 or score.shape[0] != score.shape[1] or not len(score):
raise ValueError("score must be a nonempty square matrix")
if np.isnan(score).any() or np.isposinf(score).any():
raise ValueError("scores may be finite or negative infinity")
n = score.shape[0]
C = np.full((n, n, 2), NEG)
I = np.full((n, n, 2), NEG)
Cb = np.full((n, n, 2), -1, dtype=int)
Ib = np.full((n, n, 2), -1, dtype=int)
for i in range(n):
C[i, i, 0] = 0.0
C[i, i, 1] = 0.0
def arc(h, d):
return NEG if (h, d) in forbidden else score[h, d]
def add_scores(left, right):
if left == NEG or right == NEG:
return NEG
total = float(left) + float(right)
if not np.isfinite(total):
raise FloatingPointError(
"Accumulated score exceeds floating-point range"
)
return total
for width in range(1, n):
for i in range(n - width):
j = i + width
best, arg = NEG, -1
for k in range(i, j):
v = add_scores(C[i, k, 0], C[k + 1, j, 1])
if v > best:
best, arg = v, k
I[i, j, 0] = add_scores(arc(i, j), best)
Ib[i, j, 0] = arg
best, arg = NEG, -1
for k in range(i + 1, j + 1):
v = add_scores(C[i, k - 1, 0], C[k, j, 1])
if v > best:
best, arg = v, k
I[i, j, 1] = add_scores(arc(j, i), best)
Ib[i, j, 1] = arg
best, arg = NEG, -1
for k in range(i + 1, j + 1):
v = add_scores(I[i, k, 0], C[k, j, 0])
if v > best:
best, arg = v, k
C[i, j, 0] = best
Cb[i, j, 0] = arg
best, arg = NEG, -1
for k in range(i, j):
v = add_scores(C[i, k, 1], I[k, j, 1])
if v > best:
best, arg = v, k
C[i, j, 1] = best
Cb[i, j, 1] = arg
best_root, best_score = -1, NEG
for r in range(n):
v = add_scores(C[0, r, 1], C[r, n - 1, 0])
if v > best_score:
best_score, best_root = v, r
def bt_C(i, j, d):
if i == j:
return []
k = Cb[i, j, d]
if d == 0:
return bt_I(i, k, 0) + bt_C(k, j, 0)
return bt_C(i, k, 1) + bt_I(k, j, 1)
def bt_I(i, j, d):
k = Ib[i, j, d]
if d == 0:
return [(i, j)] + bt_C(i, k, 0) + bt_C(k + 1, j, 1)
return [(j, i)] + bt_C(i, k - 1, 0) + bt_C(k, j, 1)
if best_root < 0 or not np.isfinite(best_score):
raise ValueError(
"No feasible projective tree satisfies the arc constraints"
)
arcs = bt_C(0, best_root, 1) + bt_C(best_root, n - 1, 0)
return best_score, arcsPythonIn [15]Expand
best_score, arcs = eisner(score)
print(f"best score: {best_score:.2f}")
print("arcs:", sorted(arcs, key=lambda a: a[1]))ConsoleOut [15]Expand
best score: 9.70 arcs: [(np.int64(1), np.int64(0)), (4, np.int64(1)), (np.int64(3), np.int64(2)), (np.int64(1), np.int64(3))]
The decoder finds the tree "ran" → "dog" → "the", "dog" → "barked" → "that", for a total of 9.70. It breaks the greedy cycle by choosing ran as the root instead of attaching it to the. The other four head choices stay the same.
Validating the Decoder Against Brute Force
Any new decoder should be checked against exhaustive search on small inputs. Here is the full enumeration of projective trees for five tokens, using the forest decomposition from earlier.
PythonIn [16]Expand
def all_projective_trees(n):
@lru_cache(maxsize=None)
def forest(i, j):
if i > j:
return ((frozenset(), ()),)
out = []
for k in range(i, j + 1):
for tarcs, troot in tree(i, k):
for farcs, froots in forest(k + 1, j):
out.append((tarcs | farcs, (troot,) + froots))
return tuple(out)
@lru_cache(maxsize=None)
def tree(i, j):
out = []
for r in range(i, j + 1):
for larcs, lroots in forest(i, r - 1):
for rarcs, rroots in forest(r + 1, j):
arcs = larcs | rarcs
for x in lroots:
arcs = arcs | {(r, x)}
for x in rroots:
arcs = arcs | {(r, x)}
out.append((arcs, r))
return tuple(out)
return [arcs for arcs, _ in tree(0, n - 1)]
trees = all_projective_trees(n)
brute_scores = [sum(score[h, d] for h, d in t) for t in trees]
best_i = int(np.argmax(brute_scores))ConsoleOut [17]Expand
projective trees on 5 tokens: 143 brute-force best score: 9.70 Eisner best score: 9.70 agree: True
The two scores match to machine precision. To test a decoder, generate random matrices with small integer scores and enumerate trees for . Keep the sums in the exact range and compare the maximum scores. For floating-point tests, state the score tolerance and how you handle ties. A boundary bug may show up at only one width or root. Vary the masks and include tie cases. Use these regression tests alongside a correctness argument that covers all sentence lengths.
Constrained Decoding
The example passes a forbidden arc to the decoder, which treats its score as negative infinity during lookup. Here we forbid the arc "dog" → "barked", which was the model's preferred attachment.
PythonIn [18]Expand
forbidden = {(1, 3)}
con_score, con_arcs = eisner(score, forbidden=forbidden)
print(f"unconstrained: {best_score:.2f} {sorted(arcs, key=lambda a: a[1])}")
print(f"constrained: {con_score:.2f} {sorted(con_arcs, key=lambda a: a[1])}")
print(f"score drop: {best_score - con_score:.2f}")ConsoleOut [18]Expand
unconstrained: 9.70 [(np.int64(1), np.int64(0)), (4, np.int64(1)), (np.int64(3), np.int64(2)), (np.int64(1), np.int64(3))] constrained: 8.70 [(np.int64(1), np.int64(0)), (4, np.int64(1)), (np.int64(3), np.int64(2)), (4, np.int64(3))] score drop: 1.00
The constrained tree attaches "barked" to "ran" instead of "dog", and the score drops by exactly the difference between those two arc scores. The constraint is respected exactly, and the decoder still returns the best tree that satisfies it. For a forbidden arc, a mask enforces the exclusion when an exact decoder has a finite-score feasible tree. A finite penalty may still let the forbidden arc win. To require a lexical arc, also exclude its dependent from the root candidates, as described above.
CKY with Lexical and Production Scores
Now the constituency side. We use a tiny binary grammar with hand-set additive scores so the arithmetic is transparent. These numbers are not normalized PCFG rule probabilities. The sentence "the cat saw the dog with a telescope" is the classic PP-attachment ambiguity: "with a telescope" can modify the verb "saw" or the noun "dog".
PythonIn [19]Expand
words = ["the", "cat", "saw", "the", "dog", "with", "a", "telescope"]
tags = ["Det", "N", "V", "Det", "N", "P", "Det", "N"]
lex = {
("Det", "the"): -0.1,
("Det", "a"): -0.1,
("N", "cat"): -0.1,
("N", "dog"): -0.1,
("N", "telescope"): -0.1,
("V", "saw"): -0.1,
("P", "with"): -0.1,
}
rules = {
("S", "NP", "VP"): -0.5,
("VP", "V", "NP"): -0.2,
("VP", "VP", "PP"): -0.3,
("NP", "Det", "N"): -0.1,
("NP", "NP", "PP"): -0.8,
("PP", "P", "NP"): -0.3,
}PythonIn [20]Expand
def cky(words, tags, lex, rules):
if len(words) != len(tags) or not words:
raise ValueError(
"CKY requires nonempty words and one supplied tag per word"
)
n = len(words)
chart = [[{} for _ in range(n + 1)] for _ in range(n + 1)]
back = [[{} for _ in range(n + 1)] for _ in range(n + 1)]
for i, (w, t) in enumerate(zip(words, tags)):
chart[i][i + 1][t] = lex.get((t, w), NEG)
back[i][i + 1][t] = None
for width in range(2, n + 1):
for i in range(n - width + 1):
j = i + width
for k in range(i + 1, j):
for (A, B, C), r in rules.items():
if B in chart[i][k] and C in chart[k][j]:
v = r + chart[i][k][B] + chart[k][j][C]
if v > chart[i][j].get(A, NEG):
chart[i][j][A] = v
back[i][j][A] = (k, B, C)
return chart, back
chart, back = cky(words, tags, lex, rules)Before reconstruction, require a finite full-span S score. In a multiword span, a candidate scored cannot create an S entry because the update requires a score above the default. For one token tagged S, a missing lexical score can seed an S entry at . The guard checks the completed start item; it does not detect every internal arithmetic overflow.
PythonIn [21]Expand
def build(i, j, A, back):
entry = back[i][j][A]
if entry is None:
return (A, None)
k, B, C = entry
return (A, [build(i, k, B, back), build(k, j, C, back)])
best_label = "S"
if not np.isfinite(chart[0][len(words)].get(best_label, NEG)):
raise ValueError("CKY reconstruction requires a finite full-span S score")
best_tree = build(0, len(words), best_label, back)ConsoleOut [22]Expand
S
NP
Det
N
VP
VP
V
NP
Det
N
PP
P
NP
Det
N
best score: -2.40The parser chooses the verb-attachment reading, where "with a telescope" modifies "saw". With the supplied scores, noun attachment scores half a point lower. With every other score fixed, exact arithmetic gives a tie when the noun-attachment rule rises from to , and gives noun attachment the higher score above . Floating-point sums can still tie close to that threshold. The choice depends on how the model scores the two attachments.
Enumerating the Ambiguity
For this fixture, enumerate the two licensed full-span parses and compare their scores. With missing lexical scores the helper can also return candidates at , since the final filter only checks the root category.
PythonIn [23]Expand
def enumerate_parses(i, j):
if j - i == 1:
t = tags[i]
return [(lex.get((t, words[i]), NEG), (t, None))]
out = []
for k in range(i + 1, j):
left = enumerate_parses(i, k)
right = enumerate_parses(k, j)
for (A, B, C), r in rules.items():
for sl, tl in left:
if tl[0] != B:
continue
for sr, tr in right:
if tr[0] != C:
continue
out.append((r + sl + sr, (A, [tl, tr])))
return out
parses = [p for p in enumerate_parses(0, len(words)) if p[1][0] == "S"]ConsoleOut [24]Expand
number of parses: 2
score -2.40
S
NP
Det
N
VP
VP
V
NP
Det
N
PP
P
NP
Det
N
score -2.90
S
NP
Det
N
VP
V
NP
NP
Det
N
PP
P
NP
Det
NThere are exactly two parses, differing only in where the prepositional phrase attaches. CKY found the higher-scoring one. The best enumerated score on this fixture matches chart[0][len(words)]["S"].
Scoring Constituents
The function below extracts a multiset of labeled half-open spans. It counts an internal root and skips every preterminal, including a preterminal root in a one-token tree. Repeated identical labeled spans in a unary chain retain their multiplicity through Counter. The toy grammar has no unary rules. Both trees in this comparison have internal roots and positive constituent counts, so precision and recall are defined. With positive total constituent count, the count formula for F1 gives zero when no constituents match.
PythonIn [25]Expand
def constituents(tree, start=0):
label, kids = tree
if kids is None:
return Counter(), start + 1
out = Counter()
j = start
for kid in kids:
spans, j = constituents(kid, j)
out.update(spans)
out[(start, j, label)] += 1
return out, j
pred_spans, _ = constituents(best_tree)
gold_spans, _ = constituents(parses_sorted[-1][1]) # the lower-scoring reading
tp = sum((pred_spans & gold_spans).values())
pred_count = sum(pred_spans.values())
gold_count = sum(gold_spans.values())
precision = tp / pred_count
recall = tp / gold_count
f1 = 2 * tp / (pred_count + gold_count)
exact = pred_spans == gold_spansConsoleOut [26]Expand
predicted constituents: 7 gold constituents: 7 matched: 6 precision=0.857 recall=0.857 F1=0.857 exact match: False
The parser gets six of seven constituents right and still produces the wrong structure. F1 is 0.857, while exact match is zero. The metric records one missing gold span and one spurious predicted span, while exact match records the difference in scored constituents. The fixture illustrates partial credit; it does not measure the downstream cost of that semantic distinction.
Attachment Scores on a Small Corpus
Now the dependency metrics on a hand-built, fixed-tokenization corpus, using the same zero-based/self-root convention and literal legacy-style labels as the worked table. It is a scoring fixture, not a measured parser benchmark or a UD conversion. The predictions are written to exhibit specific error types:
- The preposition "on" attaches to "cat" instead of "sat".
- The relative clause headed by "lives" attaches to "reads" instead of "man".
- A label confusion between
dobjandobj. - A passive-versus-active subject confusion.
PythonIn [27]Expand
corpus = [
{
"tokens": ["The", "cat", "sat", "on", "the", "mat", "."],
"gold": [
(1, "det"),
(2, "nsubj"),
(2, "root"),
(2, "prep"),
(5, "det"),
(3, "pobj"),
(2, "punct"),
],
"pred": [
(1, "det"),
(2, "nsubj"),
(2, "root"),
(1, "prep"),
(5, "det"),
(3, "pobj"),
(2, "punct"),
],
},
{
"tokens": ["She", "gave", "him", "a", "book", "about", "birds", "."],
"gold": [
(1, "nsubj"),
(1, "root"),
(1, "iobj"),
(4, "det"),
(1, "dobj"),
(4, "prep"),
(5, "pobj"),
(1, "punct"),
],
"pred": [
(1, "nsubj"),
(1, "root"),
(1, "iobj"),
(4, "det"),
(1, "dobj"),
(1, "prep"),
(5, "pobj"),
(1, "punct"),
],
},
{
"tokens": [
"The",
"old",
"man",
"who",
"lives",
"next",
"door",
"reads",
"many",
"books",
".",
],
"gold": [
(2, "det"),
(2, "amod"),
(7, "nsubj"),
(4, "nsubj"),
(2, "rcmod"),
(6, "amod"),
(4, "npadvmod"),
(7, "root"),
(9, "amod"),
(7, "dobj"),
(7, "punct"),
],
"pred": [
(2, "det"),
(2, "amod"),
(7, "nsubj"),
(4, "nsubj"),
(7, "rcmod"),
(6, "amod"),
(4, "npadvmod"),
(7, "root"),
(9, "amod"),
(7, "obj"),
(7, "punct"),
],
},
{
"tokens": [
"They",
"were",
"seen",
"by",
"the",
"committee",
"in",
"June",
".",
],
"gold": [
(2, "nsubjpass"),
(2, "auxpass"),
(2, "root"),
(2, "prep"),
(5, "det"),
(3, "pobj"),
(2, "prep"),
(6, "pobj"),
(2, "punct"),
],
"pred": [
(2, "nsubj"),
(2, "auxpass"),
(2, "root"),
(2, "prep"),
(5, "det"),
(3, "pobj"),
(5, "prep"),
(6, "pobj"),
(2, "punct"),
],
},
]PythonIn [28]Expand
def corpus_uas_las(corpus):
total = uas_ok = las_ok = 0
for sent in corpus:
if len(sent["gold"]) != len(sent["pred"]) or len(sent["gold"]) != len(
sent["tokens"]
):
raise ValueError("Fixed-token evaluation requires aligned arrays")
for g, p in zip(sent["gold"], sent["pred"]):
total += 1
if g[0] == p[0]:
uas_ok += 1
if g[1] == p[1]:
las_ok += 1
if total == 0:
raise ValueError("Attachment fractions require scored words")
return uas_ok / total, las_ok / total, total
uas, las, total_tokens = corpus_uas_las(corpus)ConsoleOut [29]Expand
evaluated tokens: 35 UAS = 0.8857 LAS = 0.8286 label-only error fraction (UAS - LAS) = 0.0571
Out of 35 tokens, 4 heads are wrong and 2 more have the right head with the wrong label. UAS is 0.886 and LAS is 0.829. The 5.7 percentage-point gap counts the two label-only errors in this fixture.
Per-Relation Precision, Recall, and F1
Micro-averaged scores hide which relations are failing. This breakdown computes precision, recall, and F1 per label. Pass matching gold and predicted lists for each sentence, with one head and relation pair per scored word in the same order.
PythonIn [30]Expand
def label_prf(corpus):
tp, fp, fn = Counter(), Counter(), Counter()
for sent in corpus:
for g, p in zip(sent["gold"], sent["pred"]):
if g == p:
tp[g[1]] += 1
else:
fn[g[1]] += 1
fp[p[1]] += 1
rows = []
for L in sorted(set(tp) | set(fp) | set(fn)):
prec = tp[L] / (tp[L] + fp[L]) if tp[L] + fp[L] else 0.0
rec = tp[L] / (tp[L] + fn[L]) if tp[L] + fn[L] else 0.0
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
rows.append((L, tp[L], fp[L], fn[L], prec, rec, f1))
return rows
rows = label_prf(corpus)ConsoleOut [31]Expand
label TP FP FN P R F1 amod 3 0 0 1.00 1.00 1.00 auxpass 1 0 0 1.00 1.00 1.00 det 5 0 0 1.00 1.00 1.00 dobj 1 0 1 1.00 0.50 0.67 iobj 1 0 0 1.00 1.00 1.00 npadvmod 1 0 0 1.00 1.00 1.00 nsubj 4 1 0 0.80 1.00 0.89 nsubjpass 0 0 1 0.00 0.00 0.00 obj 0 1 0 0.00 0.00 0.00 pobj 4 0 0 1.00 1.00 1.00 prep 1 3 3 0.25 0.25 0.25 punct 4 0 0 1.00 1.00 1.00 rcmod 0 1 1 0.00 0.00 0.00 root 4 0 0 1.00 1.00 1.00
The prep relation has both false positives and false negatives, because three of the head errors involve a prep arc. The dobj relation has a false negative with no compensating false positive, because the model predicted obj instead. The nsubj relation is contaminated by the passive construction, where the gold label is nsubjpass but the model predicted nsubj.
None of this is visible in the aggregate LAS.
Simulating a Parser to Study Error Structure
The four-sentence fixture shows the calculations; the next simulation supplies more attachment decisions for grouped diagnostics. To study error patterns by attachment distance and label, we simulate explicit error rules: head-change attempts use a distance-dependent probability capped at 0.8, and label changes follow a fixed confusion pattern.
PythonIn [32]Expand
LABELS = ["det", "amod", "nsubj", "dobj", "prep", "pobj", "aux"]
LABEL_P = np.array([0.24, 0.16, 0.20, 0.16, 0.10, 0.10, 0.04])
LABEL_P = LABEL_P / LABEL_P.sum()
CONFUSABLE = {
"det": "amod",
"amod": "det",
"nsubj": "dobj",
"dobj": "nsubj",
"prep": "pobj",
"pobj": "prep",
"aux": "prep",
}
def random_projective_parents(n, rng):
parent = [-1] * n
stack = [(0, n - 1, -1)]
while stack:
i, j, h = stack.pop()
if i > j:
continue
r = int(rng.integers(i, j + 1))
parent[r] = h
stack.append((i, r - 1, r))
stack.append((r + 1, j, r))
return parent
def creates_cycle(parent, d, new_head):
x = new_head
while x != -1:
if x == d:
return True
x = parent[x]
return FalsePythonIn [33]Expand
def simulate(n_sents=400, seed=7):
rng = np.random.default_rng(seed)
gold_all, pred_all = [], []
for _ in range(n_sents):
n = int(rng.integers(6, 16))
parent = random_projective_parents(n, rng)
labels = [
"root" if parent[d] == -1 else str(rng.choice(LABELS, p=LABEL_P))
for d in range(n)
]
gold_all.append((parent, labels))
pparent = parent[:]
for d in range(n):
if parent[d] == -1:
continue
dist = abs(parent[d] - d)
p_err = min(0.8, 0.03 + 0.05 * dist)
if rng.random() < p_err:
cands = [x for x in range(n) if x != d and x != pparent[d]]
rng.shuffle(cands)
for c in cands:
if not creates_cycle(pparent, d, c):
pparent[d] = c
break
plabels = []
for d in range(n):
if pparent[d] == -1:
plabels.append("root")
elif rng.random() < 0.18:
plabels.append(CONFUSABLE.get(labels[d], labels[d]))
else:
plabels.append(labels[d])
pred_all.append((pparent, plabels))
return gold_all, pred_all
gold_all, pred_all = simulate()PythonIn [34]Expand
def corpus_scores(gold_all, pred_all):
total = uas_ok = las_ok = 0
if len(gold_all) != len(pred_all):
raise ValueError("Gold and prediction corpora must align")
for (gp, gl), (pp, pl) in zip(gold_all, pred_all):
if not (len(gp) == len(gl) == len(pp) == len(pl)):
raise ValueError("Head and label arrays must align")
for gh, gL, ph, pL in zip(gp, gl, pp, pl):
total += 1
if gh == ph:
uas_ok += 1
if gL == pL:
las_ok += 1
if total == 0:
raise ValueError("Attachment fractions require scored words")
return uas_ok / total, las_ok / total, total
sim_uas, sim_las, sim_tokens = corpus_scores(gold_all, pred_all)ConsoleOut [35]Expand
simulated tokens: 4,230 UAS = 0.8901 LAS = 0.7475 gap = 0.1426
This simulation is not a trained parser or an empirical model of a language. Its recursive generator samples a restricted binary family of projective trees, not uniformly from every projective tree. Given a sampled tree, each non-root gold label is drawn independently from the chosen frequencies; the gold root label is fixed. The root is always preserved. Head-change attempts follow the distance-based probability in the code and are accepted only if they avoid a cycle; predicted trees need not remain projective. These deliberate assumptions make it possible to trace a diagnostic pattern to its generating mechanism, but they do not establish that real parser errors follow the same pattern. For distance bucketing, pass gold and predicted head lists aligned by sentence and word, with one prediction for each gold word.
PythonIn [36]Expand
EDGES = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 8), (9, math.inf)]
def accuracy_by_distance(gold_all, pred_all, edges):
stats = {e: [0, 0] for e in edges}
for (gp, _), (pp, _) in zip(gold_all, pred_all):
for d, gh in enumerate(gp):
if gh == -1:
continue
dist = abs(gh - d)
for lo, hi in edges:
if lo <= dist <= hi:
stats[(lo, hi)][1] += 1
if pp[d] == gh:
stats[(lo, hi)][0] += 1
break
else:
raise ValueError(
"Distance buckets must cover every non-root arc"
)
return stats
dist_stats = accuracy_by_distance(gold_all, pred_all, EDGES)
dist_acc = [
correct / total if total else np.nan
for correct, total in dist_stats.values()
]
dist_labels = [
f"{lo}+" if math.isinf(hi) else f"{lo}" if lo == hi else f"{lo}-{hi}"
for lo, hi in EDGES
]
non_root_correct = sum(v[0] for v in dist_stats.values())
non_root_total = sum(v[1] for v in dist_stats.values())
non_root_uas = non_root_correct / non_root_total if non_root_total else np.nanVisualizationOut [37]Expand

The longer-distance buckets have lower accuracy under this selected error process. The buckets cover every positive gold attachment distance, including distances above 99. An empty bucket has undefined accuracy (np.nan), shown without a bar; a corpus with no non-root arcs also has undefined non_root_uas. For a positive non-root total, weighting only occupied-bucket accuracies by their denominators recovers non_root_uas; the earlier sim_uas also includes perfectly preserved root words. This distinction matters when making a plot agree with an aggregate metric. On real outputs, compute bucket counts and inspect uncertainty before drawing a conclusion about particular constructions such as coordination or relative clauses.
For the confusion matrix, align the gold and predicted relation lists by sentence and word. Include each observed gold or predicted relation exactly once in labels.
PythonIn [38]Expand
def confusion_matrix(gold_all, pred_all, labels):
idx = {L: i for i, L in enumerate(labels)}
M = np.zeros((len(labels), len(labels)), dtype=int)
for (_, gl), (_, pl) in zip(gold_all, pred_all):
for g, p in zip(gl, pl):
M[idx[g], idx[p]] += 1
return M
CONF_LABELS = ["root"] + LABELS
M = confusion_matrix(gold_all, pred_all, CONF_LABELS)
def prf_from_matrix(M, labels):
rows = []
for i, L in enumerate(labels):
tp = M[i, i]
fp = M[:, i].sum() - tp
fn = M[i, :].sum() - tp
prec = tp / (tp + fp) if tp + fp else 0.0
rec = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
rows.append((L, prec, rec, f1))
return rows
label_prf_rows = prf_from_matrix(M, CONF_LABELS)
def attachment_prf(gold_all, pred_all, labels):
corpus_scores(gold_all, pred_all) # Validate the aligned arrays.
tp, fp, fn = Counter(), Counter(), Counter()
for (gh, gl), (ph, pl) in zip(gold_all, pred_all):
for gold_head, gold_label, pred_head, pred_label in zip(gh, gl, ph, pl):
if gold_head == pred_head and gold_label == pred_label:
tp[gold_label] += 1
else:
fn[gold_label] += 1
fp[pred_label] += 1
rows = []
for label in labels:
precision = (
tp[label] / (tp[label] + fp[label])
if tp[label] + fp[label]
else 0.0
)
recall = (
tp[label] / (tp[label] + fn[label])
if tp[label] + fn[label]
else 0.0
)
f1 = (
2 * tp[label] / (2 * tp[label] + fp[label] + fn[label])
if tp[label] + fp[label] + fn[label]
else 0.0
)
rows.append((label, precision, recall, f1))
return rows
prf_rows = attachment_prf(gold_all, pred_all, CONF_LABELS)VisualizationOut [39]Expand

VisualizationOut [41]Expand

The off-diagonal label confusions follow the declared mapping: nsubj/dobj, prep/pobj, and det/amod, plus the one-way replacement aux → prep. This is a check of the generator and diagnostic, not evidence about the linguistic cause of errors in a real system. The paired F1 bars distinguish label-only agreement from attachment-aware relation correctness. An arc-factored scorer may use rich contextual input representations, so first-order output factorization does not imply that it cannot distinguish a particular relation pair.
Error Analysis That Teaches You Something
Error analysis locates errors that an aggregate metric cannot identify. The following techniques help organize that inspection. Align the gold and predicted sentences and words before using these helpers on new outputs. Check that each scored word has one prediction. For a label confusion matrix, list each observed gold or predicted relation once in the label inventory.
Confusion Matrices
A confusion matrix over labels shows which relations the model confuses and in which direction. Asymmetry matters. Compare conditional error rates as well as raw counts: unequal class support can produce asymmetric counts even with symmetric conditional errors. A word-order explanation requires a separate test.
For non-root attachments, group by the reference POS tags of the gold head and its dependent. Build a relation confusion matrix for each group and report how many attachments it contains. Confusions between prep and pobj are different from confusions between nsubj and dobj, even if both show up as label errors.
Distance, Direction, and Length
The simulation illustrates an imposed distance effect. To determine whether a real system has that effect, measure its outputs, including support counts in each bucket. Two further breakdowns can be useful:
- Direction. Compare leftward and rightward gold attachments. Any difference can depend on the data, encoder, and decoder; a fully bidirectional graph scorer does not have to delay a decision in the same way as an incremental transition parser.
- Sentence length. Group sentences by length and examine their relation and distance composition. Lower exact match can arise simply from having more opportunities for error, whereas causal error propagation is an additional claim about the parser that needs evidence.
Report these as buckets, not as single numbers. A parser that wins on aggregate but loses on long sentences may be the wrong choice for a downstream task that cares about complex syntax.
Oracle Analysis
A candidate-set oracle chooses the output with the highest evaluation score against gold among a nonempty family of feasible candidates. For top- head lists, the fraction of scored words whose gold head appears in its list upper-bounds oracle UAS when the lists admit a legal tree. Even then, keeping all individually available gold heads may violate a tree constraint. If the lists admit no legal tree, the legal-tree oracle has no output. Applying the metric oracle to a beam can reveal whether it contains a useful parse.
Suppose a candidate-set oracle has 98 UAS and the model-selected output from that same family has 92 UAS, both against the same reference on the same scored words. That gap can reflect the scoring function ranking a worse candidate above a better one, approximate search failing to find the model-score optimum, or both. It does not by itself show that six points are search error. A better-scoring legal candidate demonstrates a search error under the same model score and feasible set. Compare with the exact maximum to measure the full search gap. An exact decoder may still have low gold accuracy because its objective ranks the wrong tree highest.
With the selected parse in the oracle’s candidate family and both evaluated against the same reference with the same scoring protocol, a small accuracy gap means little additional head accuracy is available within that family. It does not prove that the encoder, score model, or annotation scheme is the sole bottleneck. Candidate generation, pruning, and the distinction between per-token and whole-tree oracles should all be recorded. These experiments guide a repair only when the oracle answers the question you actually intend to ask.
Annotation Noise and Agreement
Gold trees are reference annotations produced under a scheme, sometimes with adjudication. Disagreements can reflect ambiguity, different analyses, or mistakes, so manual error inspection should separate clear system errors from defensible alternatives. Report an agreement study's population, protocol, and scorer if you use it as context; there is no universal agreement percentage for all dependency or constituency treebanks.
Inter-annotator agreement is not a mathematical ceiling on matching a fixed reference. For a simple counterexample, suppose annotators A and B disagree on 10 of 100 scored decisions, and the chosen reference is A's annotation. Their agreement is 90%, but a system that reproduces that fixed reference scores 100%. This hypothetical example does not describe a real corpus; it shows why agreement cannot be used as a universal numerical upper bound on parser accuracy.
Annotation uncertainty can still affect what a score means and what a model learns. An observed disagreement rate is not automatically a proportion of randomly corrupted labels, and it does not determine a training-loss floor: a sufficiently flexible model could memorize its training annotations. On held-out data, document disputed cases, assess adjudication where available, and measure whether conclusions survive reasonable annotation choices. Such analysis complements attachment scores without replacing them by an unsupported “human ceiling.”
Limitations & Impact
The arc-factored view of parsing gives a useful, conditional exactness guarantee. With exact arithmetic, an exact decoder finds the model-score optimum for a finite feasible output space and the stated sum of arc scores. It need not find the linguistically preferred tree. Contextual scorers may read the whole input sentence, while the output factorization still excludes explicit score interactions among selected arcs. A hard subject-count rule or a sibling preference therefore needs the appropriate additional factor or constraint. Higher-order design can increase cost, but its exponent depends on the algorithm rather than increasing automatically with order.
Projectivity restricts which reference trees are representable. The Eisner implementation cannot return a non-projective tree, and a gold annotation outside its search space is unreachable even with ideal scores. A non-projective arborescence decoder expands that space for arc-factored models, while root conventions and any extra grammatical constraints remain separate obligations. Compare these choices using the target treebank and development protocol, including runtime and the coverage of excluded structures, instead of assuming a universal accuracy ranking by decoder family.
Evaluation imposes another restriction: each score answers a particular question. Micro-LAS weights words, relation macro-F1 weights the included relations, constituent F1 gives partial span credit, and sentence exact match asks for complete scored agreement. None directly measures every semantic or downstream consequence of an error. The tutorial's fixtures and simulation expose these arithmetic differences, but they are not empirical evidence about a trained parser. Real comparisons need a declared scorer, alignment and masking rules, held-out data, support counts, uncertainty, and errors inspected in context. Annotation agreement adds context to that assessment without acting as a strict numerical ceiling.
The broader impact is a set of design questions that transfer to other structured tasks. Viterbi decoding supplies a chain example; inside-outside supplies a tree example under the specified grammar and factorization. Semantic graphs, coreference decisions, and grammar-constrained generation may need other inference procedures. For each one, state the legal outputs, the score decomposition, the search guarantee, and the evaluation loss. Use those statements to check representation limits, scoring and inference mistakes, and evaluation mismatches.
Summary
Structured prediction chooses a legal combination of related output components, such as arcs that form a parse tree. Parsing is the canonical instance, and the lessons transfer.
- Exhaustive enumeration grows rapidly. A 20-token sentence has roughly unlabeled dependency trees, of which roughly are projective. At this length, exhaustive enumeration is impractical as a general decoding method.
- Factorization specifies the scored parts. Score the structure as a sum over parts. The choice of parts controls which output interactions receive scores; the chart states and algorithm determine the computational cost.
- Eisner's algorithm decodes projective dependency trees in by combining complete and incomplete spans. The displayed recurrences combine contiguous spans and retain the boundary information required by their factorization.
- CKY combines licensed child constituents in a chart. In log-score space, replacing alternative maxima by log-sum-exp computes a log-partition function; inside-outside gives marginals under the stated factorization.
- Exact constrained decoding. With masks, exact inference excludes forbidden parts and selects a highest-scoring legal output when a finite-scoring completion exists. Coupled constraints may need additional chart states, another exact optimizer, or approximate search.
- Labels decouple from structure when scores and legal label choices factor over arcs. Preparing labels for all candidate lexical arcs costs ; labeling a fixed tree costs . Coupled output-label constraints need inference that accounts for the coupling.
- Independent head choices need a tree constraint. They may contain cycles even when each local choice has a high score. A decoder must also use the target root convention.
- Training objectives differ from evaluation metrics. Log-likelihood, hinge loss, and F1 measure different things. Decoding for the evaluation metric can change the score even when the trained model is fixed.
- UAS and LAS measure attachment accuracy. With the same scored words, UAS minus LAS is the fraction with a correct head and a wrong relation label. Declare punctuation, root, label, and token-alignment conventions before comparing the numbers.
- PARSEVAL F1 gives partial credit for constituents and can remain high despite complete-tree disagreement. Sentence exact match separately reports complete scored agreement.
- Error analysis by distance, direction, relation, and sentence length exposes effects hidden by aggregates. Candidate-set oracles assess available accuracy; a search-error claim requires comparing model scores under the same feasible set. Annotation agreement contextualizes a reference but is not a strict ceiling.
- The questions generalize. Sequence labeling, semantic parsing, coreference, and constrained generation all require clear output spaces, objectives, inference procedures, and evaluation targets. They do not all admit the same dynamic program.
The next part moves from form to meaning, starting with lexical semantics and word senses. Some meaning-related tasks also couple several decisions, while others are introduced as local classification problems. The distinction between local scores, joint constraints, and the evaluation target will remain useful as we move into that material.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about structured prediction and parsing evaluation.
Structured Prediction and Parsing Evaluation
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!