Document-Level and Context-Aware Translation

Michael BrenndoerferNovember 25, 202645 min read

Use document context, decoding constraints, and translation memory to handle pronouns and terminology, then measure consistency and translation quality.

Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 195Document-Level and Context-Aware Translation
Reading the full chapter · 13 sections · 45 min13 sections · 45 min

All 13 sections · 45 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Document-Level and Context-Aware Translation

A product page can introduce a term in the first sentence and use it throughout. A pronoun in the fourth sentence can refer to someone introduced in the second. The opening paragraph can set a register that the rest of the document sustains or changes. A faithful translation preserves these relationships across sentences.

A conventional NMT baseline trains on aligned sentence pairs and translates one sentence at a time. Tiedemann and Scherrer (2017) use that setup as their baseline. In Voita et al. (2019), plausible translations of individual sentences sometimes disagreed on address, speaker gender, or repeated expressions when read together.

This chapter is about the gap between sentence-local fluency and document-level adequacy, and about the engineering that closes it. We will look at:

  • Why the sentence-level assumption fails, and what kinds of failures it produces.
  • How to measure and maintain terminology consistency.
  • Discourse context: pronouns, zero anaphora, honorifics, and connectives.
  • Architectures for conditioning translation on context.
  • Decoding-time constraints and the placeholder trick.
  • Document memory: translation memories, retrieval, and adaptive systems.
  • How to evaluate long-form translation without fooling yourself.

By the end you should be able to spot inconsistent terms or mismatched pronouns, choose a technique that supplies the missing information, and test whether it improves the document.

The Sentence-Level Boundary and Why It Leaks

Conventional supervised sentence-level NMT trains on sentence-aligned pairs (x(i),y(i))(\mathbf{x}^{(i)}, \mathbf{y}^{(i)}). Parallel data mining is one way to obtain those pairs. The model learns

Pθ(y∣x)=∏t=1mPθ(yt∣y<t,x),P_\theta(\mathbf{y} \mid \mathbf{x}) = \prod_{t=1}^{m} P_\theta(y_t \mid y_{<t}, \mathbf{x}),

Here x\mathbf{x} is the source sentence, yty_t is target token tt, and y<ty_{<t} is its preceding target prefix. For a complete target sentence y\mathbf{y}, the mm target tokens include the final end-of-sequence token (EOS). If the product stops at the last visible token, it gives the probability of that prefix. Conditioning on x\mathbf{x} alone omits any explicit document context.

The factorization itself is worth pausing on. The product over target tokens says that each target token depends on the source sentence and on the target tokens before it, and on nothing else. The model is therefore trained to treat each sentence as a complete communicative act, with no memory of what came before and no obligation to what comes after. When you deploy such a model on a document, you are asking it to do something it was never trained to do: maintain state across segments. The model has no mechanism for remembering that it translated "cloud storage" one way in the previous sentence, and no incentive to prefer the same choice again. Sampling or search uses those sentence-level probabilities. A likely sentence can still conflict with an earlier translation choice.

Document-level translation

Document-level translation uses information from other segments of the same document to inform the translation. The goal is to make choices such as terminology, pronouns, ellipses, and register coherent across segments.

Context from other segments can take the form of earlier sentences, a memory entry built from an earlier translation in the document, a running summary of terminology choices, or a learned document representation. A static project glossary or translation retrieved from an unrelated document supplies auxiliary guidance. Either can complement document context. A product manual may need exact term matches, while a dialogue may need consistent forms of address between characters.

What breaks at the sentence boundary

The failures cluster into a small number of categories. It is worth naming them carefully, because each category has a different cause and a different fix, and because practitioners often conflate them under the general label of "context."

  • Terminology drift. The same source concept receives inconsistent target terms across sentences, after allowing for required inflection and authorized variation. In the illustration, “Cloud storage” becomes almacenamiento en la nube in sentence 1, almacenamiento de nube in sentence 2, and nube de almacenamiento in sentence 3. A reader must infer from context that these phrases name the same product feature.
  • Pronoun ambiguity. The current source sentence may leave a pronoun or an omitted subject ambiguous. If an antecedent appears in an earlier sentence, a model that translates each sentence independently has no access to that cue.
  • Zero anaphora and ellipsis. Chinese and Japanese can leave a subject unexpressed. When nearby context supplies the referent, a translator can use it to choose an explicit subject in English.
  • Honorifics and address forms. French tu versus vous, German du versus Sie, Japanese keigo, Korean speech levels. The correct choice depends on the relationship between speaker and addressee, which may only be established across a whole document. A sentence-level model sees a bare you and has to guess, and its guess may shift mid-document as local context changes.
  • Discourse connectives. However, therefore, meanwhile, and instead signal relationships between parts of a text. The relationship can depend on a previous sentence. Check whether the target needs a connective or can leave the relationship implicit.
  • Register and style. A translation can switch how it addresses the same person within a conversation. Check whether a change in register reflects a change in the source.
  • Named entity consistency. “Acme Corp.” in sentence 1 becomes “Acme Corporation” in sentence 5 and “the Acme company” in sentence 9. In this example the three forms name one company. Check whether each rendering preserves that identity.

A single passage can give you several things to check. Resolve the referent before choosing a target pronoun (see Coreference Resolution). Check the form of address against the speaker relationship and target conventions (see Pragmatics, Implicature, and Presupposition).

The next sections compare ways to supply cross-sentence evidence and enforce fixed wording. The examples show how to restore glossary terms and how to choose a pronoun when the antecedent is supplied.

Terminology Consistency

A pharmaceutical leaflet, a product help page, and a contract each give translators reasons to preserve specific wording. A project glossary lets reviewers check a drug name, a UI label, or a defined term against the requested rendering.

Two resources serve different purposes in a translation workflow:

  • A translation memory (TM) stores previously translated source and target segments. A translation tool can retrieve those segments and offer their earlier wording as suggestions. memoQ 12.6 classifies 100% as exact, 95–99% as nearly exact, and 50–94% as fuzzy. It also distinguishes higher-scoring context matches. These thresholds belong to the tool’s scoring convention. Review a retrieved segment before reusing its wording.
  • A glossary, or termbase, records term-level equivalents. A project glossary can require almacenamiento en la nube for “cloud storage” wherever the product feature appears. The entry records a term choice without prescribing the rest of the sentence.

CAT tools can offer both resources. memoQ, for example, supports term bases that record preferred renderings. A translation memory can suggest phrasing in context, while a termbase can specify which equivalent a project requires.

The consistency metric

Before fixing anything, we need to measure it. Suppose a document DD contains sentences s1,…,sns_1, \ldots, s_n, and a glossary G\mathcal{G} maps each source term tt to a required target τ(t)\tau(t). For each glossary term that appears in the document, count how often each target variant is used in the output. Then define

Cons(D)=1∣GD∣∑t∈GDmax⁡({0}∪{nt,v:v∈Vt})Nt,\text{Cons}(D) = \frac{1}{|\mathcal{G}_D|} \sum_{t \in \mathcal{G}_D} \frac{\max\bigl(\{0\} \cup \{n_{t,v} : v \in \mathcal{V}_t\}\bigr)}{N_t},

Here GD\mathcal{G}_D contains the glossary terms that occur in DD, and NtN_t counts the source occurrences of tt. The set Vt\mathcal{V}_t contains the observed target variants, and nt,vn_{t,v} counts source occurrences aligned to variant vv. Each source occurrence contributes at most one rendering. The toy scorer treats distinct surface strings as distinct variants. If your protocol pools spellings or inflections, define the classes before scoring. Check that each form is allowed in its local context before awarding term accuracy, or report contextual grammar separately if the score measures term identity alone. If all occurrences of a term are missing, its numerator is zero. When the document has no glossary occurrences, report the document score as unavailable. A score of 1 means every occurrence of each term falls into the same scored variant.

In plain terms, the inner fraction asks: for this term, what share of its occurrences use the most popular variant? If a term appears four times and three of those use the same rendering, the inner fraction is 0.75. The outer average then combines these shares across all glossary terms in the document. Terms that do not occur in the document are excluded, because including them would dilute the score with terms the translator never had a chance to get wrong. The metric is intentionally forgiving about which variant is chosen: it rewards internal consistency, not correctness. That is why it needs siblings.

This metric has two useful siblings:

  • Term accuracy measures whether the chosen variant is the required one, τ(t)\tau(t). Consistency can be high while accuracy is low if the system consistently picks the wrong term.
  • Term coverage measures whether the system produced any translation for the term at all, or dropped it. An entirely omitted term scores zero on all three metrics. Coverage shows that there were no aligned renderings to evaluate.

Report all three. A system that translates "cloud storage" as almacenamiento en la nube in every sentence has consistency 1.0 and accuracy 1.0. A system that always says nube has consistency 1.0 and accuracy 0.0. If half the source occurrences are translated correctly and half are missing, all three scores are 0.5 for that term. Each pattern points to a different bug in the pipeline, and a single aggregate score would hide the difference.

How constraints enter decoding

The most direct approach is to force the target to contain the required term. In its cleanest form, constrained decoding solves

y⋆∈arg⁡max⁡y∈Y  log⁡Pθ(y∣x,C)subject to∀ t∈dom⁡(G)∩terms(x):  τ(t)∈y.\mathbf{y}^{\star} \in \arg\max_{\mathbf{y} \in \mathcal{Y}} \; \log P_\theta(\mathbf{y} \mid \mathbf{x}, C) \quad \text{subject to} \quad \forall\, t \in \operatorname{dom}(\mathcal{G}) \cap \text{terms}(\mathbf{x}): \; \tau(t) \in \mathbf{y}.

Here Y\mathcal{Y} is the set of completed target token sequences, x\mathbf{x} is the source, and CC is optional document context. PθP_\theta is the model distribution with parameters θ\theta, and dom⁡(G)\operatorname{dom}(\mathcal{G}) is the set of source terms in the glossary. The notation τ(t)∈y\tau(t) \in \mathbf{y} means that the tokens of the required target term occur contiguously in y\mathbf{y}. If the model assigns positive probability to at least one feasible output, choose any feasible output with the highest probability. A limited beam can prune viable prefixes and miss the optimum.

The term can appear anywhere in the output. A hypothesis that has yet to start a term can still include it later, so the search needs to retain different paths through the requirements.

Ordinary Beam Search keeps up to BB hypotheses at each step. Grid beam search (Hokamp and Liu, 2017) keeps a separate beam for each number of constraint tokens already covered. If the required phrases contain MM model tokens in total, there are up to M+1M+1 coverage levels, including zero. At output step jj, a hypothesis at coverage level cc has consumed exactly cc constraint tokens. A hypothesis can generate an ordinary token or start an unused phrase. Once it starts a phrase, it must continue emitting that phrase's tokens until it finishes. Starting or continuing a phrase increases cc by one. The search chooses the best-scoring retained hypothesis that ends with EOS and has covered all MM constraint tokens. If none survives, the search has found no valid output. A system with a fallback should report when it uses it.

This allocation can keep a lower-scoring prefix alive because it has made more progress on the required terms. With maximum output length LL, there are at most L(M+1)L(M+1) beams to update, each holding up to BB hypotheses. Runtime also depends on model scoring and how many candidate expansions the search considers. For a large glossary, constrain the terms that are mandatory for the current segment.

A fixed phrase may be a poor fit where the sentence calls for a different word form. Jon et al. (2021) give examples of this failure in morphologically rich languages. Check the required form in the completed sentence and send awkward cases for review.

The placeholder trick

An alternative that avoids modifying the decoder is the placeholder pipeline:

  1. Detect glossary terms in the source sentence.
  2. Replace each occurrence with a unique placeholder token.
  3. Translate the protected sentence with an ordinary NMT model.
  4. Replace each placeholder in the output with the required target term.

Use this pipeline with a text-only translation engine when its output preserves recognizable markers. Check the engine’s behavior with the markers you use.

  • Tokenization. A tokenizer that emits one token per UTF-8 byte represents ⟦T0⟧ with eight tokens. Match the decoded string during restoration and measure whether the engine preserves the markers you use.
  • Reordering. In step 4, restoring a term puts it wherever the placeholder landed. If the model moved the placeholder to the wrong position, the sentence can be ungrammatical even though the glossary form is correct.
  • Morphology. A literal replacement cannot adjust the stored term to its surroundings. If the target text contains consultó dos followed by a marker, restoring the singular informe técnico gives consultó dos informe técnico. The context calls for the plural informes técnicos.
  • Over-matching. A naive substring replacement for “cloud” will also match “cloudy”. Use word boundaries and try the longest alternative first when multiple terms match at the same position.
  • Copy failures. Check the identity and count of every marker before restoration. Equal totals can hide a missing marker if the model duplicates another. The toy implementation below checks for exactly one copy of every expected marker and rejects unrecognized marker IDs in the reserved marker format. The toy implementation rejects literal source text in that format before inserting markers, so a source literal cannot pass for a marker lost in translation.

Run the pipeline sentence by sentence with the same glossary. Exact-form consistency from this mechanism requires detecting every occurrence, preserving its marker, and restoring the intended form. Detection recall and marker survival help locate failures. An engine can produce the desired term without the glossary: Dinu et al. (2019) observed this in their unconstrained baseline. When detection misses an occurrence, the wrapper has no marker to restore.

For one source occurrence, the chance of detection and marker survival is detection recall times the chance that an inserted marker survives. The second probability is conditional on detection and insertion. The product measures those two stages. The toy restorer also checks the rest of the segment, so it can reject a segment even if this occurrence’s marker survived.

PythonIn [3]
CollapseExpand
import numpy as np

detection_recall = np.linspace(0.70, 1.00, 7)
placeholder_survival = np.linspace(0.80, 1.00, 7)
protection_success = np.outer(detection_recall, placeholder_survival)

survival_step = placeholder_survival[1] - placeholder_survival[0]
recall_step = detection_recall[1] - detection_recall[0]
protection_extent = (
    placeholder_survival[0] - survival_step / 2,
    placeholder_survival[-1] + survival_step / 2,
    detection_recall[0] - recall_step / 2,
    detection_recall[-1] + recall_step / 2,
)
VisualizationOut [4]
CollapseExpand
Heatmap of the joint probability of detection and marker survival for one occurrence.
Probability that one glossary occurrence is detected and its marker survives. Each cell multiplies detection recall by marker survival conditional on insertion. The chart stops before the segment-level restoration checks.

Retrieval-augmented translation

A third family retrieves examples from a datastore. kNN-MT (Khandelwal et al., 2021) builds a token-level store from paired source and target examples. An isolated pair can supply a short translation example. To represent its use in a longer sentence, the datastore needs the paired sentence and target prefix. An entry pairs the decoder representation kjk_j of the source and a reference target prefix with the next reference token vjv_j. At inference, the current decoder representation st\mathbf{s}_t retrieves neighboring keys:

PkNN(yt∣st)∝∑(kj,vj)∈N(st)1[vj=yt] exp⁡(−β∥st−kj∥2),P_{\text{kNN}}(y_t \mid \mathbf{s}_t) \propto \sum_{(k_j, v_j) \in \mathcal{N}(\mathbf{s}_t)} \mathbb{1}[v_j = y_t] \, \exp(-\beta \lVert \mathbf{s}_t - k_j \rVert^2),

where N(st)\mathcal{N}(\mathbf{s}_t) lists the retrieved key-token pairs and 1[vj=yt]\mathbb{1}[v_j=y_t] is one when the tokens match and zero otherwise. The inverse temperature is β=1/T\beta=1/T for T>0T>0. With at least one neighbor, divide by the sum of their exponential weights to make the probabilities sum to one. If retrieval returns no usable neighbors, use the base model alone for that step. Otherwise, mix the two distributions:

P(yt)=λ PkNN(yt∣st)+(1−λ) Pθ(yt∣y<t,x).P(y_t) = \lambda \, P_{\text{kNN}}(y_t \mid \mathbf{s}_t) + (1 - \lambda) \, P_\theta(y_t \mid y_{<t}, \mathbf{x}).

You can update the datastore without retraining. With a positive retrieval weight, a token in a client-approved term becomes more likely when the retrieval distribution assigns it more probability than the base model does. Search adds inference latency. The weight λ∈[0,1]\lambda\in[0,1] sets the share of probability mass from retrieval. Within the retrieval distribution, a larger inverse temperature β\beta concentrates more weight on closer neighbors when their distances differ.

In Gu et al. (2018), a translation model conditions on bilingual examples retrieved by source-side similarity. The retrieved targets provide wording the model can reuse when it fits the current source.

Discourse Context and Pronoun Translation

A pronoun presents two questions. What does it refer to, and which form fits the target sentence? A model can pick the right referent and still use the wrong grammatical form. It can also generate a fluent sentence that refers to the wrong person.

Coreference across sentences

Cross-sentence coreference is a well-studied task (see our chapter on Coreference Resolution). In translation, it matters because target languages package the same information differently.

Consider Spanish to English:

María llamó al banco. Dijo que enviaría el contrato.

The verbs dijo and enviaría both have unexpressed subjects. In this reading, María is the subject of both, giving “She said she would send the contract.” The preceding sentence makes María a plausible referent. The Spanish verbs alone do not tell you whether the two subjects are the same person.

Now consider English to Spanish:

The engineer spoke with the manager. She said she would review the report.

The first she could refer to either person in the preceding sentence. The second could also refer to someone else. Spanish can leave these subjects implicit, depending on the phrasing. If the translation names one person, that choice adds an interpretation the English may leave open.

Pro-drop and zero anaphora

Languages that allow unexpressed subjects can leave a referent implicit. Translation into English often calls for an explicit subject. If context identifies the referent, the translator can choose a pronoun or use a name. If the referent remains ambiguous, the translator can look for a phrasing that preserves the ambiguity.

The reverse problem can arise with English it. Suppose it refers to a previously mentioned object and the target sentence uses a pronoun that agrees with its noun. You need the target noun and its grammatical gender, which may be established in a preceding sentence. Impersonal uses of it call for a different analysis.

Omitted or ambiguous arguments can arise in Chinese as well. For an empirical example, Cai and Xiong (2020) built an English-to-Chinese test suite covering pronouns, discourse connectives and ellipsis. Whether a translation needs to make a referent explicit depends on the sentence and the target construction.

Honorifics and address forms

The T-V distinction, named after Latin tu and vos, is the choice between familiar and formal second-person forms. Examples include French (tu/vous), German (du/Sie), Spanish (tú/usted), and Russian (ты/вы). Japanese and Korean also mark honorific distinctions with verbal forms and other lexical or grammatical choices.

English you can leave the target address form open. Look for cues in the current sentence and surrounding dialogue, including how the same speakers addressed each other earlier.

A style sheet can record how characters address one another. The IGDA Game Localization Best Practices gives a related example: record how a character should sound and include examples of their wording.

Discourse connectives

Connectives such as however and because signal relations between spans of text. An explicit connective can be added or omitted in translation. Denturck (2012) studies this for causal connectives in French and Dutch translations.

Look at what the previous sentence establishes and how the current one follows. Where a source connective is ambiguous, the relation can help you choose the target equivalent. See Discourse Relations and Coherence.

For example, compare “The export failed. Therefore, the file appeared” with “The export failed. Nevertheless, the file appeared”. Both connectives fit the syntax, but the first signals a consequence and the second signals an unexpected contrast. In review, check that the target expresses the relation intended by the source.

Architectures for Context-Aware Translation

We now turn from phenomena to mechanisms. How do you condition an NMT model on document context? The answer depends on what kind of context you need and what kind of model you have. The mechanisms below are not mutually exclusive, and a production system may combine several of them.

Context concatenation

Prepend up to a fixed number of preceding source sentences to the current one. Here jj is the current sentence index and kk is the number of preceding sentences available within that limit:

x′=[xj−k;…;xj−1;xj],\mathbf{x}' = [\mathbf{x}_{j-k}; \ldots; \mathbf{x}_{j-1}; \mathbf{x}_j],

and translate x′\mathbf{x}' as a single input. In the concatenate-both-sides design, the model emits target segment boundaries. When the expected boundaries appear in the right places, the segment after the last boundary translates the current sentence. Missing or misplaced boundaries can mix contextual and current text.

Decide which of the concatenated segments you want to translate. If you want only the current sentence, check that the output excludes the earlier ones. Concatenation lengthens the input. Its token count is the sum of the sentence token counts, plus any separator tokens. With equal-length sentences and no separators, the input has k+1k+1 times as many positions as the current sentence alone. Extra context can help or hurt depending on which sentences you include.

A separator gives a model trained on concatenated input a cue about where the context ends and the current sentence starts. Ordinary positional embeddings encode token positions across that combined input. Attention can still cross the boundary, and the separator increases the input length by its own token count.

Multi-encoder models

A more principled architecture uses separate encoders:

Hcur=Enccur(xj),Hctx=Encctx(C<j),\mathbf{H}^{\text{cur}} = \text{Enc}_{\text{cur}}(\mathbf{x}_j), \qquad \mathbf{H}^{\text{ctx}} = \text{Enc}_{\text{ctx}}(C_{<j}),

Here C<jC_{<j} is the auxiliary input, such as preceding sentences or retrieved examples. One design concatenates [Hctx;Hcur][\mathbf{H}^{\text{ctx}}; \mathbf{H}^{\text{cur}}] along the position axis for decoder cross-attention. The two sequences need a shared feature width, so project them to a common width if necessary. A different design can calculate a context representation separately and learn how to mix it with the current-sentence representation.

The two encoders can have different capacities. When the current-sentence encoder matches an existing sentence-level encoder’s architecture, you can initialize it with those weights. To train a context encoder on aligned neighboring segments, you need examples that preserve those neighborhoods. Other approaches have different data requirements. DocRepair, for example, trains a second-pass repair model using target-language monolingual documents.

Hierarchical and cache models

A hierarchical model can give the decoder both a current sentence encoding and context summarized at the sentence level. Miculicich et al. (2018) attend over words within contextual sentences, then over the sentence representations. With a recurrent or pooled sentence-level summary, the document layer can skip attention across all pairs of original document tokens. The cost depends on the word-level encoder and the design of the document layer.

A related idea is a cache or memory that persists across segments. Early work on context-aware NMT used a cache of recent target-side hidden states, so the model could use information from recently generated output. This resembles the mechanisms in Recurrent Memory. A decoder can read a bounded cache without attending to the full document. What it learns about a recent term depends on what those retained states encode.

A cache with a fixed capacity can evict older evidence. It might still contain the recent translation of "cloud storage" and supply a cue for the next mention. If it has evicted the only evidence for an earlier antecedent, the decoder cannot retrieve that evidence from the cache.

LLM-scale context

When the whole document fits within a model’s context window, you can include it in a prompt with the glossary, prior decisions, and instructions that identify the segment to translate. Leave enough room for the model’s output. Check the translation against the glossary and style sheet.

The tradeoffs are different but not absent:

  • Cost and latency. Compare measured time to first token, total completion time, and input-token charges for the same documents under the serving configurations you plan to use. For interactive translation, test whether a shorter window meets the quality target.
  • Position in long prompts. Liu et al. (2024) found that position affected how well models used relevant information in multi-document question answering and key-value retrieval. For translation, test whether moving a relevant sentence or a glossary entry changes the output in your setup.
  • Copying and segment boundaries. Compare the output with the current input. Flag wording copied from a previous translation if it refers to a different source segment.
  • Segment boundaries. Compare translating the whole document with translating one segment at a time using a running glossary and a summary of prior choices. The segment-based layout gives you one output per requested segment to check.

A practical pattern is a hybrid: a long-context LLM translates a window of segments, with an explicit glossary block and a short "style sheet" built from earlier segments. The window limits how much text the model sees at once. The style sheet carries earlier decisions forward as guidance for later segments. The style sheet might record the chosen rendering of key terms, the address form, and a few examples of the desired tone. It is updated as the translation progresses, so it accumulates document-level knowledge without requiring the model to attend over the full document.

Context-Aware Decoding

You can intervene at decoding time without retraining when the decoder exposes the controls you need. Grid beam search requires control of candidate token expansion and scoring. A hosted service can enforce the constraints if it provides such a feature. When an endpoint accepts text and returns text without exposing search controls, use an external placeholder pipeline if the engine can preserve its markers.

Grid beam search in more detail

The requirement that the output contain τ(t)\tau(t) is a regular language. A finite-state recognizer can track whether a model prefix has met the requirement. A hard-constrained decoder can use that state to prevent accepting an end-of-sequence token before the term appears.

For a single required phrase of mm model tokens, use states 00 through mm. Before a full match, the state is the length of the longest suffix of the output so far that matches a prefix of the phrase. State 00 means no prefix matches. The intermediate states correspond to nonempty proper prefixes. If a token breaks a partial match, keep any shorter prefix that still matches a suffix. State mm means the phrase has appeared, and all later tokens leave the recognizer in that satisfied state. A one-token requirement therefore has two states.

For multiple phrases, a product recognizer can track a tuple of these states and accept when every phrase has appeared. One token can advance more than one recognizer. For example, the output tokens A B C satisfy both substring requirements A B and B C because they share the token B. The original grid beam search credits each emitted token to at most one constraint position, so separately covering those two phrases takes four emitted constraint tokens. Even at the same coverage level, hypotheses can have covered different phrases. Each hypothesis therefore also tracks which constraints it has covered and whether it is in the middle of emitting one.

You can also allow soft constraints by penalizing missing terms in the score. This lets a decoder prefer the glossary form while still accepting a different form if it scores well enough. The penalty can be term-specific. A legal term might be mandatory, while a stylistic preference carries a small penalty.

Source-side terminology tagging

Another approach is to train the model to use inline terminology annotations. Dinu et al. (2019) augmented the source with the desired translation and used an auxiliary stream to mark token roles. They selected training examples whose target reference already contained the desired term. At inference, the annotations guide generation without adding a separate grid search.

This setup requires glossary-annotated training data. Evaluate term use and fluency separately, including terms held out from the annotations. Compare runtime against your configured constrained decoder under the same hardware and decoding settings.

Placeholder protection as a decoding substitute

The placeholder pipeline enforces its replacement rule after generation, wherever a recognizable marker survives. Constrained decoding instead requires the specified token sequence in an accepted output. If either approach uses a fixed form, check whether that form is grammatical in context.

Use placeholders when you only control the text sent to the engine and the marker survival rate is acceptable. If you control decoding, test in-search constraints for terms that must appear in the output. You can combine the two for different terms, then check which requirements each stage satisfied.

Document Memory

A translation system can carry prior choices in a translation memory or glossary, a cache of hidden states, or text copied into the next prompt. A translation memory stores translated segment pairs. A cache supplies model representations, and a prompt supplies previous wording as text.

Translation memory retrieval

Given the current source segment, retrieve similar source segments from the translation memory and present their translated pairs to the model. Compare a lexical ranking such as BM25, an embedding ranking, or a combination on examples from the target domain.

A retrieved target provides wording the model can copy or adapt. If the old source says “enable Cloud Storage” and the current one says “disable Cloud Storage”, copying the old target preserves the product term but reverses the instruction. Check the changed part of the source before reusing retrieved text.

Adaptive and interactive MT

Adaptive MT uses a translator’s corrections to influence later output. Domingo et al. (2019) demonstrate online learning that updates model parameters after a translator confirms a correction. In a system that uses retrieved examples or a prompt, you can instead add the correction to those inputs and reuse it on later segments without changing the model parameters.

An interactive system can treat the translator’s validated prefix as fixed text and propose a continuation. Check whether your interface also supports selecting required terms.

Save reviewed corrections with their source context so later segments can reuse the wording. Check that an earlier correction still applies when the source wording or context changes.

Glossary memory in LLM pipelines

One way to supply document memory to an LLM is to put it in the prompt. Try a prompt with four blocks:

  1. Instructions: "Translate the following segment from English to Spanish. Use the glossary exactly. Match the style of the prior translations."
  2. Glossary: a list of source-target term pairs.
  3. Prior translations: the last kk translated segments, possibly with a summary of terminology choices.
  4. Current segment: the source sentence to translate.

The prior translations give the model examples of style and terminology. Prompted glossary entries and conflict-resolution instructions guide generation. If exact forms are mandatory, decoding constraints can ensure their presence in accepted outputs. Then check that each required source occurrence has the intended translation at the corresponding target location. If a check fails, retry or send the segment for review. As a starting layout, put the current segment last and the glossary near the instructions. Test the ordering on the translation model and task you intend to use.

For prompted translation, test context length and glossary size on the documents you expect to handle. Mark the current segment explicitly, then check whether the output repeats an earlier translation or includes material from neighboring segments. Update the prompt’s glossary and style decisions as the document progresses.

Evaluating Long-Form Translation

You can report BLEU, chrF, COMET, BLEURT, or human assessments on aligned segments. For document-level evaluation, add tests whose units span sentences, such as repeated terms or a pronoun with an antecedent in a preceding sentence.

Document-level metrics

One document BLEU convention joins the hypothesis sentences within each document and joins the corresponding reference sentences the same way. Use the resulting document pairs as the scoring segments. The BLEU algorithm clips n-gram matches against the reference within each scoring segment. Joining sentences lets n-grams cross their boundaries and changes where counts are clipped. With one reference, the corpus brevity penalty stays the same if each joined token sequence consists of the existing sentence tokens in order, with no added boundary tokens. The total hypothesis and reference lengths then stay the same. Report the segmentation and aggregation convention. The resulting BLEU score does not directly measure terminology consistency.

One way to extend a learned metric is to give it context at scoring time. Vernikos et al. (2022) adapted pretrained COMET and COMET-QE to use neighboring sentences. They used WMT 2021 human MQM annotations to evaluate the extension. In separate contrastive tests for pronoun resolution and word-sense disambiguation, the document-level, reference-free COMET-QE ranked the correct translation highest more often than sentence-level COMET-QE. Use the scores to compare systems on a specified evaluation set, and inspect individual errors to see where the systems differ.

Use automatic metrics to screen systems on a specified evaluation set. Check terminology and discourse separately, and ask reviewers to inspect the translated documents for the properties that matter to readers.

Terminology metrics

With source occurrences aligned to observed target variants, compute all three scores for each glossary term. Use the same denominator throughout. It is the total number of source occurrences, including those without an aligned rendering. Report whether you match surface forms exactly or group acceptable forms into predefined variants.

  • Term accuracy counts occurrences with the required target τ(t)\tau(t).
  • Term consistency counts occurrences with the most frequent observed variant.
  • Term coverage counts occurrences with any aligned rendering, whether correct or incorrect.

The scores help distinguish omissions from a uniform choice of the wrong term. You can report them per term or aggregate them by document or corpus. A system with 95% term accuracy overall might still fail on a specific term, which the per-term view can reveal.

Pronoun and discourse evaluation

A Spanish reference for the engineer–manager example can preserve the ambiguity with a clause such as Dijo que revisaría el informe. Both subjects are unstated. To isolate a phenomenon, you can use a targeted test suite. Cai and Xiong (2020) test pronouns, discourse connectives and ellipsis in English-to-Chinese translation. WMT 2021 instead asked human evaluators to assess translation with surrounding context in view. These procedures answer different questions about the system.

Ask raters to mark specific errors so you can see where a system struggles. The full MQM typology includes a coherence error type. Accuracy and terminology are among the high-level dimensions in MQM Core. State which version and error types you used so readers can interpret the breakdown.

Contamination and benchmark hygiene

Check whether benchmark documents or their translations might have reached the model during training. Li et al. (2024) found that the effect of contamination on scores varied across the question-answering benchmarks they examined. For document translation, report what you could check about overlap and evaluate on newly collected or held-out material where possible.

When reporting document-level results, include:

  • The source of the test documents, with dates and licenses.
  • Whether the documents could plausibly appear in web-crawled pretraining data.
  • A held-out or newly collected set, if possible.
  • The exact decoding configuration and model version.
  • Human evaluation results alongside automatic metrics.

Measure targeted discourse performance alongside aggregate scores. In Voita et al.'s English-to-Russian study, the context-aware decoder CADec improved on targeted tests of deixis, ellipsis and lexical cohesion. Its BLEU difference from the context-agnostic system trained on 6 million sentence pairs did not reach statistical significance. Report the language pair, data and comparison system before generalizing a gain. For a result on public text, check overlap and try to replicate it on a separate test set.

Worked Example

Compare two illustrative translations of a short document. The first varies a term across sentences. The second uses the project glossary throughout.

Source document (English):

  1. Acme Cloud Storage keeps your files safe.
  2. With Cloud Storage, Acme offers unlimited space for teams.
  3. The Cloud Storage dashboard shows usage in real time.
  4. Teams rely on Cloud Storage every day.

Glossary:

  • Cloud Storage →\to almacenamiento en la nube
  • Acme →\to Acme

Sentence-level NMT output (an illustrative example used separately from the code simulation below):

  1. El almacenamiento en la nube de Acme mantiene tus archivos a salvo.
  2. Con almacenamiento de nube, Acme ofrece espacio ilimitado para equipos.
  3. El panel de nube de almacenamiento muestra el uso en tiempo real.
  4. Los equipos confían en almacenamiento en la nube todos los días.

The four translations use three different target forms for Cloud Storage. The required form, almacenamiento en la nube, appears twice: accuracy and majority-variant share for this term are both 50%. All four occurrences have an aligned rendering, so coverage for Cloud Storage is 100%.

Glossary-protected output:

  1. El almacenamiento en la nube de Acme mantiene tus archivos a salvo.
  2. Con almacenamiento en la nube, Acme ofrece espacio ilimitado para equipos.
  3. El panel de almacenamiento en la nube muestra el uso en tiempo real.
  4. Los equipos confían en almacenamiento en la nube todos los días.

The required term now appears in all four places, so Cloud Storage scores 100% on accuracy, consistency and coverage. These are per-term results. A reviewer would still need to assess fluency and whether each sentence preserves the source meaning.

Literal replacement can produce less idiomatic wording, and protection depends on detection. A case-sensitive matcher for "Cloud Storage" would miss "cloud storage" in lowercase. Evaluate recall for the forms and inflections the matcher should cover. For a different kind of context cue, return to the Spanish example. The earlier sentence supplies María as a candidate for the subject of Dijo. The pronoun fixture below supplies that interpretation explicitly.

Code Implementation

We will build a small, self-contained pipeline that demonstrates the core mechanics: segmenting a document, simulating sentence-level terminology drift, measuring consistency, and enforcing glossary terms with placeholders. The point is to make the concepts concrete, not to build a production system. Real systems replace the toy translator with an NMT model or an LLM and add the safeguards discussed above.

Setup

The examples use NumPy and Matplotlib. The hidden first cell calls the book helper to seed the random number generators.

Segmenting a document

We start with a short English document and split it with a regular expression. This pattern splits after an abbreviation followed by a space, as in “Dr. Tan,” and misses a break when a closing quote follows the punctuation. Use a sentence segmenter when those cases matter.

PythonIn [5]
CollapseExpand
import re
from collections import Counter

document = (
    "Acme Cloud Storage keeps your files safe. "
    "With Cloud Storage, Acme offers unlimited space for teams. "
    "The Cloud Storage dashboard shows usage in real time. "
    "Teams rely on Cloud Storage every day."
)


def segment(text):
    return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]


sentences = segment(document)
ConsoleOut [6]
CollapseExpand
1. Acme Cloud Storage keeps your files safe.
2. With Cloud Storage, Acme offers unlimited space for teams.
3. The Cloud Storage dashboard shows usage in real time.
4. Teams rely on Cloud Storage every day.

The document contains four sentences, each mentioning the glossary term "Cloud Storage".

Simulating sentence-level terminology drift

The scripted baseline assigns one of three Spanish variants to each source sentence. Its fixed rule makes the example reproducible. It does not run a translation model.

PythonIn [7]
CollapseExpand
VARIANTS = [
    "almacenamiento en la nube",
    "almacenamiento de nube",
    "nube de almacenamiento",
]


def sentence_level_term(sentence, options):
    key = sum(ord(c) for c in sentence)
    return options[key % len(options)]


sentence_choices = [sentence_level_term(s, VARIANTS) for s in sentences]
ConsoleOut [8]
CollapseExpand
'nube de almacenamiento'               <- Acme Cloud Storage keeps your files safe.
'almacenamiento de nube'               <- With Cloud Storage, Acme offers unlimited space for teams.
'almacenamiento de nube'               <- The Cloud Storage dashboard shows usage in real time.
'almacenamiento en la nube'            <- Teams rely on Cloud Storage every day.

Each sentence gets a target term, but the choices are not coordinated. This is the sentence-level baseline.

Measuring consistency

We compute the majority-variant share, as defined earlier. The demonstration has one source occurrence per sentence. A score of 1.0 requires every occurrence to have the same rendering.

PythonIn [9]
CollapseExpand
def consistency(choices):
    # One entry per source occurrence, with None for a missing rendering.
    counts = Counter(choice for choice in choices if choice is not None)
    majority_count = max(counts.values(), default=0)
    share = majority_count / len(choices) if choices else None
    return share, counts


sentence_consistency, sentence_counts = consistency(sentence_choices)
ConsoleOut [10]
CollapseExpand
Majority-variant share: 50.00%
Distinct variants used : 3
  2x almacenamiento de nube
  1x nube de almacenamiento
  1x almacenamiento en la nube

The code fixture yields a different assignment from the hand-written illustration. It uses the required form once in four occurrences, so term accuracy is 25%. Its most common variant, almacenamiento de nube, appears twice, so the majority-variant share is 50%.

@fig-term-variant-counts shows the distribution.

VisualizationOut [11]
CollapseExpand
Horizontal bar chart showing how many sentences use each target-language variant.
Counts of three Spanish renderings of *Cloud Storage* in the four-sentence toy simulation. These counts come from the scripted baseline.

The chart makes the drift visible. A document reader would see the same thing, spread across paragraphs.

Protecting glossary terms

Now we implement the placeholder pipeline. The function finds glossary terms, replaces them with placeholders, and returns the mapping needed to restore them. Terms are sorted by length so a multiword term takes precedence over a shorter match at the same starting position. The search scans left to right.

PythonIn [12]
CollapseExpand
marker_pattern = re.compile(r"⟦T[0-9]+⟧", flags=re.IGNORECASE)


def protect(text, glossary):
    if marker_pattern.search(text):
        raise ValueError("Source text contains a reserved glossary marker")
    if not glossary:
        return text, {}
    terms = sorted(glossary, key=len, reverse=True)
    alternatives = "|".join(re.escape(term) for term in terms)
    pattern = re.compile(rf"(?<!\w)(?:{alternatives})(?!\w)")
    mapping = {}

    def insert_marker(match):
        placeholder = f"⟦T{len(mapping)}⟧"
        mapping[placeholder] = glossary[match.group()]
        return placeholder

    return pattern.sub(insert_marker, text), mapping


def restore(text, mapping):
    targets = {marker.casefold(): target for marker, target in mapping.items()}
    observed = Counter(
        match.group().casefold() for match in marker_pattern.finditer(text)
    )
    if observed != Counter(targets.keys()):
        raise ValueError(
            "Expected markers to appear exactly once after translation"
        )
    return marker_pattern.sub(
        lambda match: targets[match.group().casefold()], text
    )
ConsoleOut [13]
CollapseExpand
Protected : With ⟦T0⟧, ⟦T1⟧ offers unlimited space for teams.
Mapping   : {'⟦T0⟧': 'almacenamiento en la nube', '⟦T1⟧': 'Acme'}
Restored  : with almacenamiento en la nube, Acme offers unlimited space for teams.

The toy translator changes ⟦T0⟧ to ⟦t0⟧. Restoration matches markers without regard to case and checks that each expected marker appears exactly once. The check also catches a marker dropped or duplicated by an engine.

Applying the pipeline to the document

We run every sentence through the pipeline. The toy translator lower-cases its input to simulate a transformation, then we restore the glossary targets.

PythonIn [14]
CollapseExpand
def toy_mt(protected_text):
    return protected_text.lower()


document_outputs = []
for s in sentences:
    p, m = protect(s, glossary)
    document_outputs.append(restore(toy_mt(p), m))

variant_pattern = re.compile(
    r"(?<!\w)(?:"
    + "|".join(re.escape(variant) for variant in VARIANTS)
    + r")(?!\w)"
)
protected_choices = []
for output in document_outputs:
    matches = variant_pattern.findall(output)
    protected_choices.append(matches[0] if len(matches) == 1 else None)
protected_consistency, protected_counts = consistency(protected_choices)
ConsoleOut [15]
CollapseExpand
Acme almacenamiento en la nube keeps your files safe.
with almacenamiento en la nube, Acme offers unlimited space for teams.
the almacenamiento en la nube dashboard shows usage in real time.
teams rely on almacenamiento en la nube every day.

Protected majority-variant share: 100%

The scorer checks the restored output text for one recognized rendering per sentence because this fixture has one source occurrence per sentence. Every restored output contains the required term, giving a consistency score of 1.0 in @fig-term-consistency-before-after. The scripted baseline assigns variants by a separate rule. The bars compare the two fixtures and do not estimate the effect of enabling glossary protection on one translation model.

VisualizationOut [16]
CollapseExpand
Bar chart of the majority-variant shares for Cloud Storage in two separate toy generators.
Majority-variant share for the scripted baseline and a separate placeholder fixture. The placeholder output uses one target term at all four occurrences.

These graphs score Cloud Storage alone. The scorer recognizes a rendering at all four occurrences in both fixtures, so the term has 100% coverage in each. The accuracy check uses the glossary as its reference. A mistaken glossary entry could still score 1.0 against that reference, so verify the entries before scoring.

Consistency alone can hide systematic wrongness. The next cell computes matching term-accuracy values for the same four-sentence toy document and glossary, using the glossary target as the reference.

PythonIn [17]
CollapseExpand
required_term = glossary["Cloud Storage"]
accuracy_sentence = sum(v == required_term for v in sentence_choices) / len(
    sentence_choices
)
accuracy_protected = sum(v == required_term for v in protected_choices) / len(
    protected_choices
)
metric_labels = ["Consistency", "Accuracy"]
sentence_metrics = [sentence_consistency, accuracy_sentence]
protected_metrics = [protected_consistency, accuracy_protected]
metric_positions = np.arange(len(metric_labels))
VisualizationOut [18]
CollapseExpand
Grouped bars of Cloud Storage consistency and accuracy in the scripted baseline and placeholder fixture.
Consistency and accuracy for two separate scripted fixtures. Consistency counts the fraction using the most common target variant. Accuracy counts the fraction using the required glossary form, even when another variant is more common.

Choosing a pronoun from a supplied antecedent

The pronoun example illustrates a different step. Given an antecedent whose features are already known, the toy function uses its gender and number to choose an English pronoun. The example supplies the antecedent directly.

PythonIn [19]
CollapseExpand
def english_pronoun(entity):
    if entity["number"] == "pl":
        return "they"
    return "he" if entity["gender"] == "m" else "she"


entities = [
    {"name": "María", "gender": "f", "number": "sg"},
    {"name": "el gerente", "gender": "m", "number": "sg"},
]

sentence_level_default = "he"
document_level_choice = english_pronoun(entities[0])
ConsoleOut [20]
CollapseExpand
Source (es): María llamó al banco. Dijo que enviaría el contrato.
Sentence-level default pronoun : he
Pronoun from supplied antecedent: she

The fixture assumes that María is the intended subject of Dijo and supplies her features directly. A translation system that resolves the subject would have to infer it before choosing the pronoun.

Limitations & Impact

Document-level and context-aware translation is one of those areas where the concept is obviously right and the engineering is stubbornly difficult. The limitations fall into five groups.

Context adds computation, data requirements, or both. Concatenation lengthens the input. A supervised context encoder needs examples with annotated or aligned context of the kind it will use. Retrieval adds search and can return a near match that the model copies. Compare a small relevant context window with a longer one on your own document tasks.

A hard lexical constraint can require an exact phrase in each accepted decoded segment where the constraint applies. Checking that each source occurrence was rendered as intended still requires alignment. The prescribed phrase may already be the most fluent choice. When the target context requires reordering or inflection, an exact stored form can sound awkward. Choose where to enforce the form and where to allow variation based on the document’s purpose.

The target language may require distinctions the source leaves implicit. On a test with 85% pronoun accuracy, 15% of the evaluated pronouns are wrong. A grammatical sentence can still pick the wrong antecedent. In the toy example, “he” would fit the English sentence syntactically and still point away from María.

Report each automatic metric’s agreement with human judgments on the evaluation set when both are available. Vernikos et al. (2022) report imperfect correlations with human MQM annotations for several document-level metrics. Review individual errors alongside the aggregate scores.

Benchmark contamination is a real risk. An aggregate score cannot tell you whether a model handled the surrounding discourse or reproduced familiar text. Record test-set provenance and the limits of your overlap checks. A newly collected or separately held-out set can make the comparison easier to interpret.

These mechanisms address different production needs. memoQ's term bases illustrate how a translation tool can record required wording and look it up during translation. A system can also supply glossary entries and selected document context to a translation model. Evaluate terminology, fluency and discourse on the documents you expect it to handle.

The most important shift is conceptual. Sentence-level NMT encouraged us to think of translation as a function from one sentence to another. Document-level translation reminds us that translation is a communicative act situated in a text, a context, and a relationship between writer and reader. The techniques in this chapter are attempts to encode that situatedness in systems that were originally designed without it. They are partial solutions, but they point toward a more adequate picture of what translation is.

Summary

  • A model given only the current sentence receives no earlier sentence as input. Include context when the translation depends on an earlier term choice, antecedent, or form of address.
  • Report term accuracy, term consistency, and term coverage separately.
  • Glossaries supply terms for constrained decoding, placeholder protection, or training methods such as source tagging. Translation-memory examples can support fine-tuning or inference-time retrieval, as in the indexed kNN-MT example.
  • Hard lexical constraints enforce phrase presence in accepted outputs. Soft constraints can favor a term while leaving room for a more natural alternative. Check alignment when you need consistency for every source occurrence.
  • Test pronoun and discourse choices with examples whose disambiguating cues occur in another sentence.
  • Architectures for context include concatenation, multi-encoder models, hierarchical models, caches, and long-context LLMs. Each has different costs and failure modes, and more context is not always better.
  • Document memory can be implemented with TM retrieval, adaptive MT, or prompt-based glossary and style sheets in LLM pipelines.
  • Evaluation is the weak link. Document BLEU and document COMET capture some cross-sentence effects, but terminology metrics and human evaluation remain essential. Watch for contamination in long-document benchmarks.
  • Report targeted discourse results alongside aggregate translation scores. Within each test, compare systems on the same examples. Name each test set and describe what you know about overlap.
  • Read the translated document as a whole to check relationships that individual segment reviews can miss.

The next chapter, Speech-to-Speech Translation, covers streaming, latency, and how recognition errors can propagate into translation.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about document-level and context-aware translation.

Document-Level and Context-Aware Translation

Question 1 of 80 of 8 completed
Why can a sentence-level NMT system make inconsistent choices across a document?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 8

Parallel Data Mining and Quality Control

Mine parallel text from the web, align sentences, filter candidate pairs, and screen for training-evaluation contamination in translation corpora.

53 min read
Language AI Handbook · Vol. 8

Neural Machine Translation

Train a toy encoder-decoder Transformer for machine translation. Compare decoding policies, inspect cross-attention weights, and diagnose NMT failure modes.

49 min read
Language AI Handbook · Vol. 8

Statistical Machine Translation Foundations

Learn how noisy-channel IBM word alignment, EM training, phrase extraction, log-linear scoring, and beam decoding build a statistical machine translation system.

59 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026documentlevel, author = {Michael Brenndoerfer}, title = {Document-Level and Context-Aware Translation}, year = {2026}, url = {https://mbrenndoerfer.com/writing/document-level-context-aware-translation-terminology-pronouns-decoding}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Document-Level and Context-Aware Translation. Retrieved from https://mbrenndoerfer.com/writing/document-level-context-aware-translation-terminology-pronouns-decoding
MLAAcademic
Michael Brenndoerfer. "Document-Level and Context-Aware Translation." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/document-level-context-aware-translation-terminology-pronouns-decoding>.
CHICAGOAcademic
Michael Brenndoerfer. "Document-Level and Context-Aware Translation." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/document-level-context-aware-translation-terminology-pronouns-decoding.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Document-Level and Context-Aware Translation'. Available at: https://mbrenndoerfer.com/writing/document-level-context-aware-translation-terminology-pronouns-decoding (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Document-Level and Context-Aware Translation. https://mbrenndoerfer.com/writing/document-level-context-aware-translation-terminology-pronouns-decoding
Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy