---
title: Grid Beam Search for Constrained Decoding
url: https://www.emergentmind.com/topics/grid-beam-search
type: topic
---

# Grid Beam Search for Constrained Decoding

Grid Beam Search (GBS) is an extension of standard beam search algorithms for sequence generation that guarantees the inclusion of pre-specified lexical constraints—sequences of tokens that must appear verbatim in the output. GBS forms a two-dimensional search space, or "grid", organizing partial output hypotheses according to both the generated-token position and the number of constraint tokens covered. Originating with Hokamp and Liu [1704.07138], GBS was motivated by the challenges of enforcing terminology coverage in tasks like neural machine translation (NMT) without retraining or modifying model parameters.

## 1. Problem Formulation and Motivation

Consider a sequence-generation model such as an attentional encoder–decoder that defines the output probability as
$$
p_\theta(y|x) = \prod_{t=0}^{T} p_\theta(y_t | x; y_{<t}),
$$
where $y$ is the generated sequence, $x$ the input, and $y_{<t}$ the prefix up to $t-1$. For lexically constrained decoding, a set of $n$ constraints $C = \{c_0, \ldots, c_{n-1}\}$ is specified, where each $c_i$ is a contiguous phrase (token sequence) to be covered exactly once in the hypothesis.

Traditional beam search lacks a mechanism to enforce arbitrary multi-token or phrase-level constraints. GBS instead ensures that all constraints appear as intended in any valid output. This is crucial in machine translation pipelines for accurate terminology injection—particularly in specialized or rapidly-evolving domains, where correct translation of technical terms is imperative [1704.07138, 2305.14538].

## 2. Algorithmic Framework

GBS structures the search space as a $(T_{\max}+1) \times (N+1)$ grid, where $T_{\max}$ is maximum output length and $N = \sum_{i} L_i$ is the total number of constraint tokens across all $n$ constraints (with $L_i$ the length of $c_i$). Each cell $Grid[t][k]$ maintains up to $B$ hypotheses having produced $t$ tokens and covered exactly $k$ constraint tokens.

Hypotheses are classified as:
- **Open**: not in the midst of outputting a multi-token constraint; may generate freely or start a new constraint.
- **Closed**: currently outputting a constraint; must continue it until completion.

Transitions into $Grid[t][k]$ at each time step are:
- **Generate**: From $Grid[t-1][k]$, open hypotheses consider free generation from the vocabulary $V$.
- **Start Constraint**: From $Grid[t-1][k-1]$, open hypotheses optionally start a yet-unused constraint $c_j$ by emitting its initial token $c_{j0}$, entering closed state.
- **Continue Constraint**: From $Grid[t-1][k-1]$, closed hypotheses continue emitting tokens of the currently active constraint $c_j$.

After generating candidates for each transition type, only the top $B$ scoring hypotheses at $Grid[t][k]$ are retained (beam pruning by cumulative log-probability). At $t = T_{\max}$, the top-scoring complete hypothesis in $Grid[T_{\max}][N]$ emitting the EOS token is selected as output [1704.07138].

## 3. Mathematical Details and Complexity

Each hypothesis $h$ in $Grid[t][k]$ encapsulates:
- A generated prefix $y_{0:t-1}$
- Pointer $r$ (position in constraint, or $-1$ if open)
- Constraint coverage vector (indicating completion status)
- Score $Score(h) = \sum_{s=0}^{t-1} \log p_\theta(y_s | x ; y_{<s})$

The score of successor hypothesis $h'$ after transition is:
$$
Score(h') = Score(h) + \log p_\theta(y_t | x ; y_{<t}),
$$
where $h$ is a predecessor from the relevant cell depending on the transition type.

Standard beam search has complexity $O(B T_{\max} |V|)$. GBS increases this to $O(B T_{\max} N |V|)$ in the worst case, due to maintaining additional beams per level of constraint coverage. However, many cells remain empty in practice, and significant parallelization across the constraint-coverage dimension is possible. Empirical evidence confirms practicality for moderate beam/constraint sizes [1704.07138].

## 4. Applications and Empirical Results

**Neural Interactive-Predictive Translation**: In interactive scenarios, human correction is modeled by successively adding missing constraints and re-decoding with GBS. Each additional three-token constraint yields 4–9 BLEU improvement per iteration; four corrections surpass 20 BLEU total gain on WMT EN→DE/FR/PT benchmarks.

**Domain Adaptation via Terminology Injection**: Source–target domain-specific phrase pairs are extracted (e.g., by high PMI). For test sentences triggering constraints, GBS improves BLEU by +1.8 (EN→DE), +2.6 (EN→FR), and +13.7 (EN→PT) compared to a strong general-domain baseline, without retraining. Ablations show proper constraint placement by GBS is essential for these gains [1704.07138].

**Plug-and-Play Extensions**: Cascaded Beam Search [2305.14538] integrates GBS with logit-boosting for constraint tokens and demonstrates competitive performance on terminology-forcing tasks, rivaling systems with heavily customized models.

## 5. Worked Example

Suppose $C = \{("black","box"), ("failure")\}$ for translation of “the system suffered a failure in the black box” ($N=3$). The grid tracks progress both in the number of output tokens and number of constraint tokens covered. Emitting "black" via a start-constraint transition moves from $(t-1, k)$ to $(t, k+1)$ and closes the hypothesis on $c_0$; the next step continues with "box", incrementing $k$. Separately, "failure" can also be started and completed at any time. Remaining positions generate unconstrained output. The grid ensures all constraint tokens are incorporated exactly once, with the path alternating between constraint emission and free generation [1704.07138].

## 6. Relation to Other Beam Search Extensions

GBS generalizes standard beam search by adding constraint-coverage as a secondary axis, yielding guaranteed constraint satisfaction for multi-token or phrase constraints. By contrast, classical beam search tracks only hypothesis score at each time step and cannot ensure that any constraints appear.

Variants like Cascaded Beam Search [2305.14538] incorporate logit manipulation to bias the model towards constraint tokens, optionally relaxing tokenization requirements (e.g., via character-prefix matching) and enabling more flexible integration with language models. Disjunctive constraints and advanced filtering (e.g., ordering, minimum separation) can be integrated atop GBS with minimal algorithmic changes.

| Method                 | Constraint Guarantee | Training Modification | Complexity Increase (vs. Beam) |
|------------------------|---------------------|----------------------|-------------------------------|
| Standard Beam Search   | None                | No                   | Baseline                      |
| Grid Beam Search [1704.07138] | Hard                 | No                   | $O(N)$ in constraint tokens   |
| Cascaded Beam Search [2305.14538] | Hard (with extensions) | No                   | $O(m)$ in constraints         |

## 7. Advantages, Limitations, and Practical Considerations

**Advantages**:
- Guarantees satisfaction of arbitrary lexical or phrase constraints, given sufficient beam width and reachable search space.
- Does not require training or parameter modification; operates as a generic decoding procedure for any autoregressive model.
- Flexible for interactive, domain adaptation, and plug-and-play applications.

**Limitations**:
- Linear increase in runtime and memory with the number of constraints/constraint tokens.
- Decoding latency grows by approximately $(N+1)$ in the worst case, though parallelization mitigates impact.
- Hypotheses require augmented state (coverage vector, open/closed status), increasing computational overhead.
- Constraints must align exactly with model tokenization unless extended approaches (e.g., character-based matching) are employed [2305.14538].
- Overlapping or discontinuous constraints require custom handling for correctness.

*This suggests GBS is most practical when the number of constraints is moderate and precise placement of reserved terminology is essential, such as technical NMT or post-editing pipelines.*

## References

- Hokamp, C., & Liu, Q. (2017). "Lexically Constrained Decoding for Sequence Generation Using Grid Beam Search" [1704.07138].
- Odermatt, F., Egressy, B., & Wattenhofer, R. (2023). "Cascaded Beam Search: Plug-and-Play Terminology-Forcing For Neural Machine Translation" [2305.14538].

Source: https://www.emergentmind.com/topics/grid-beam-search