Structured Prediction and Parsing Evaluation › Constrained Decoding
Language AI HandbookAll chapters 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.
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!