Subset Retrieval Nearest Neighbor Machine Translation
Paper · 2023 · Hiroyuki Deguchi, Taro Watanabe, Yusuke Matsui et al.
Summary
A translation system can improve its output by consulting earlier translations as it writes. The difficulty is that looking up relevant examples for each new token can take far longer than generating the translation itself. Subset kNN-MT addresses that cost by narrowing the search before generation begins. For each input sentence, it finds similar source sentences in a collection of earlier translations and makes their target tokens available to the decoder. The decoder still looks for examples at each step, but it searches only within the selected sentences. This gives machine translation a way to draw on a large, mixed-domain collection without repeatedly searching across it.
The method combines two kinds of similarity. Sentence similarity determines which examples are eligible. At each decoding step, similarity between decoder states determines which tokens from those examples should influence the prediction. The translation system combines the resulting evidence with its own next-token probabilities. To make the remaining search cheap, the authors store compressed representations of the example tokens and build a lookup table for each query. The same table entries can then be reused to score different candidates. The underlying translator can use the examples without further translation training, although the method requires preparing both sentence and token stores.
On the WMT’19 German-to-English news test, Subset kNN-MT with the LaBSE sentence encoder matched conventional kNN-MT at 40.1 BLEU. The paper reports that it decoded 111.8 times as fast as conventional kNN-MT in the large-batch setting and 47.4 times as fast when translating one sentence at a time. The authors also tested German-to-English and English-to-Japanese domain adaptation with mixed stores and no supplied domain label. Across the experiments, the reported speedup over conventional kNN-MT reached 132.2 times, and the reported improvement over that baseline reached 1.6 BLEU points. Those are maxima across comparisons. The English-to-Japanese results illustrate a different tradeoff: subset search recovered much of the quality gain from retrieval while giving up some of the improvement achieved by conventional kNN-MT.
Which sentences enter the subset can matter as much as how quickly it is searched. In the German-to-English medical test, selecting the closest sentences with LaBSE produced better BLEU than drawing the same number from a wider band of neighbors. An example in the same domain traces the effect down to a hyphen: closely related translations gave the decoder repeated evidence for a conventional medical term. The speed advantage also has a boundary. Larger subsets increase the cost of each token lookup, and the method still needs substantial storage and preparation for the full collection.
Deep dive: Subset Retrieval Nearest Neighbor Machine Translation
Subset kNN-MT speeds up machine translation by finding relevant example sentences first, then searching their target tokens during decoding. · about 35 minutes to read
The problem and its context
Why a translator consults its examples
The paper starts with a translator that has already been trained on parallel sentences, pairs in which a source sentence is accompanied by a translation. The encoder reads the source. The decoder generates a target sentence in order, assigning probabilities to possible continuations based on the source and on the target tokens it has generated so far. The authors situate this setup in the line of work represented by Sequence to Sequence Learning with Neural Networks and Neural Machine Translation by Jointly Learning to Align and Translate.
The paper uses a Transformer as its translator, following the architecture introduced in Attention Is All You Need. The question is what this trained system should do when an unfamiliar input calls for wording that is well represented in a collection of examples. A translator trained on general text can lose quality in a specialized domain. Suitable parallel sentences give it another source of evidence. A previously observed translation can be relevant even when the subject of the new input and the identity of its closest precedents were unknown at training time.
Conventional nearest-neighbor machine translation, or kNN-MT, supplies that evidence at the point where the decoder chooses a token. It records internal decoder states from parallel sentences and associates each state with the actual next token in the corresponding example. At inference, the current decoder state serves as a query. An earlier state close to that query contributes evidence for the token that followed it. When multiple retrieved entries carry the same token, they can reinforce one another. The decoder uses this evidence as a probability distribution alongside the distribution produced by the translator itself.
This differs from handing the translator a complete sentence to imitate. Two occurrences of the same target token can be recorded as separate examples because the target prefixes and source sentences that give rise to them differ. A single target sentence can likewise supply different evidence at different decoding steps. The extra flexibility is central to the original kNN-MT approach. It is also the source of the computational problem, because each step needs a new query suited to the prefix available at that point.
Why the search becomes expensive
A datastore in this paper is a searchable collection of example representations and their associated outputs. The conventional token datastore has an entry for each included target position in the parallel data. It therefore grows with the total number of target tokens, even though its immediate job is to find a small set of useful continuations. An input may come from any of several domains, so keeping a broad collection is valuable. That same breadth gives conventional token search a large collection to organize and query throughout decoding.
Conventional kNN-MT uses an index that groups vectors into clusters and probes promising groups. The baseline already has a mechanism for avoiding a direct scan of all stored vectors. Even with that indexing, it starts each token search with the corpus-wide structure as its search space. No initial source-sentence decision restricts eligible examples to the translations of a few known sentence matches. In the setting that prompted the study, the paper reports that repeating the search made conventional kNN-MT about 100 to 1,000 times slower than standard neural translation.
The burden is especially relevant to what the authors call an open-domain setting. A system is presented with a source sentence without a label telling it which domain to consult. Giving each domain its own small store would change that problem, because the translator would then need either a supplied label or some way to choose the store. A mixed collection keeps domain evidence available without requiring that preliminary label. Subset kNN-MT tries to retain that advantage while restricting token search for the current sentence.
The proposal rests on an opportunity available before the first target token is generated. The source sentence is already present in full. Its representation can be compared with the source side of the parallel corpus, and the resulting matches can be used repeatedly while the target sentence takes shape. Sentence search and token search therefore answer different questions. One asks which prior inputs resemble this input. The other asks which observed continuations resemble the current decoding situation. The former can be done at the start, while the latter remains sensitive to the changing target prefix.
How earlier approaches use or restrict examples
The paper traces translation by example back to analogy-based translation. It describes later neural approaches that find example sentences by edit distance, a measure of how much textual editing is required to turn one string into another. Other work gives the translator similar examples as part of its input, including their translations. The paper cites Neural Fuzzy Repair and Boosting Neural Machine Translation with Similar Translations in that connection. Subset kNN-MT uses sentence matches to determine which existing token entries can cast a vote during generation.
Some earlier work directly addressed the cost of such votes. Fast kNN-MT builds extra datastores associated with source tokens and uses word alignment to reduce the search space. The alignment links positions in a source text with corresponding parts of its translation. Deguchi and colleagues make a sentence-level selection and dispense with that alignment requirement. They characterize their additional sentence datastore as smaller than the source-token datastores used by Fast kNN-MT. Another approach cited in the paper retrieves chunks of text to cut down the number of queries. Subset kNN-MT retains the recurring token query and reduces how much it has to search.
The authors also discuss Dai and colleagues, who use sentence retrieval to narrow token search, ranking sentence matches by BM25 through ElasticSearch. This is the closest comparison in terms of where to put the initial restriction. Deguchi and colleagues describe their own BM25 variant as an approximation of that approach. They distinguish it from Dai and colleagues’ adaptive interpolation weight, which depends on exact distances and is incompatible with the quantized lookup used here. The paper also distinguishes its objective from Adaptive Nearest Neighbor Machine Translation, which learns how to weight probabilities obtained with different numbers of token neighbors. The central design choice in Subset kNN-MT concerns which examples those neighbors can come from and how their distances can be scored efficiently.
The method, step by step
From the input sentence to the next token
Imagine that the translator has received a German sentence and is about to begin writing its English output. Subset kNN-MT first converts the whole German sentence into a vector and searches for source sentences with nearby vectors. Each result corresponds to a parallel sentence pair. The system gathers the previously prepared token entries associated with the target side of those pairs. This defines the working collection for the input sentence.
The target sentence is then generated in the ordinary order. For the next token, the translation decoder produces an internal state. Subset kNN-MT uses that state to rank the example token entries in the working collection. It gives more weight to closer examples, adds the weights of examples that point to the same token, and mixes the resulting probabilities with the translator’s own. The working collection is specific to the source sentence. The token query, its distances, and the evidence it produces can change as the translation grows.
How Subset kNN-MT uses earlier translations
The steps in order.
Preparing the token memory
The token memory is constructed from parallel data using teacher forcing. This means the decoder receives the reference target prefix at each position when the examples are prepared. The authors can then record the state immediately before the final feed-forward network and pair it with the reference token that actually comes next. At inference the corresponding state is generated from the source and the prefix of a candidate translation. The point of taking the state at the same place in the decoder is to compare queries with keys that describe the same kind of prediction situation.
ℳ = {(f(x, y₍<t₎), yₜ) | (x, y) ∈ 𝒟, 1 ≤ t ≤ |y|}
Here ℳ is the token datastore and 𝒟 is the collection of parallel sentence pairs. A pair consists of the source token sequence x and the reference target token sequence y. The index t identifies a position in the target sequence, |y| is the target length, y₍<t₎ is the reference prefix before that position, and yₜ is the reference token at the position. The function f returns the decoder representation, a vector of D real-valued components. The condition following the vertical bar includes every valid target position for each pair in 𝒟. Each resulting entry associates the vector key with the token value in the target vocabulary.
This construction preserves context even though it stores only a token as the value. The key comes from processing both the source and the prefix of the reference. Repeated tokens consequently contribute multiple entries, indexed by states that can be near or far from a later query. A token’s frequency in the whole corpus gives no direct account of its influence at a particular step. What matters for that step is which occurrences survive sentence selection, how close their keys are to the query, and whether they enter the final neighbor list.
The translation parameters are already trained when this memory is built. Teacher forcing here is a way to extract states from existing parallel sentences. It also provides a known next token to associate with each state. Fitting the compression codebooks and building the search structures are additional preparation, distinct from updating the translator to adapt it to a new domain.
Preparing and selecting whole-sentence examples
The authors build a sentence store alongside the token store. Its unit of retrieval is a source sentence in the parallel collection. The corresponding target sentence determines which target positions will be available if that example is selected.
𝒮 = {(h(x), y) | (x, y) ∈ 𝒟}
The symbol 𝒮 denotes the sentence datastore. The function h encodes the source sequence x as a real-valued vector of dimension D′. The prime distinguishes the sentence representation dimension from the decoder representation dimension D. The associated value y is the target reference for that source. The right-hand condition ranges over the same parallel collection 𝒟 used in the token memory. The vector h(x) describes the source as a whole, whereas f in the token memory also takes a target prefix and describes one position in generation.
When a new source arrives, it is encoded with the same h that was used to prepare the keys in 𝒮. Its nearest sentence matches form a subset denoted 𝒮̂. The number requested is n. The working token store then consists of entries associated with the sentence pairs that yielded those matches.
ℳ̂ = {(f(x, y₍<t₎), yₜ) | (h(x), y) ∈ 𝒮̂, 1 ≤ t ≤ |y|}
Here ℳ̂ is the reduced token datastore for the current input. The hatted 𝒮̂ is the selected part of the sentence datastore. In this expression x and y belong to a retrieved example, and f(x, y₍<t₎) and yₜ are its stored key and value at target position t. The condition on t includes all target positions of each selected example. The identity of the input determines 𝒮̂, while the set of example positions in ℳ̂ is reused during generation for that input.
The distinction between n and k matters throughout the paper. The sentence parameter n governs how many past sentence pairs are admitted. It does not impose a fixed count of candidate token entries, since the selected target sentences can have different lengths. The token parameter k governs how many entries from that working collection contribute to a particular next-token prediction. A full target sentence can supply any number of useful positions across the course of decoding. Even within an eligible sentence, a given position contributes to the current prediction only if its key places it among the selected token neighbors.
Choosing a representation for sentence search
The authors compare several ways of implementing h. LaBSE is a pretrained encoder derived by fine-tuning multilingual BERT. Its role here is to map the source sentence to a vector for retrieval. The paper motivates this option through work such as Sentence-BERT, which illustrates the use of training for sentence-level similarity. The authors expect this kind of representation to help when the most useful source examples share meaning with the input in spite of differences in their wording. Language-agnostic BERT Sentence Embedding
AvgEnc instead averages hidden representations from the translation encoder across the input. This makes a single vector out of the encoder’s sequence of representations. The same trained Transformer supplies them and also performs translation. The encoder was trained for translation, so the usefulness of the average as a measure of sentence similarity is an empirical question. It provides a way to test whether representations already learned for translation can also select examples effectively.
The other alternatives are TF-IDF and BM25. They build sentence representations from token counts and the distribution of tokens across sentences. The authors use raw counts for term frequency and add-one smoothing for inverse document frequency, treating each sentence as a document. In the BM25 setting, k₁ is 2.0 and b is 0.75. Both representations are normalized by their Euclidean length and reduced to 256 dimensions by singular value decomposition. That transformation produces smaller vectors for retrieval. These alternatives emphasize which tokens the source sentences contain, giving the experiments a comparison with the two encoders that derive representations from neural processing of the input.
Whichever encoding is chosen, this stage applies to the source side. Target-side evidence comes along through the parallel sentence pairs. The premise is that a source sentence that resembles the input can have a translation containing useful tokens, even when the example as a whole would be an unsuitable answer to the new input. The token search is what lets the decoder use a fragment of that evidence in context.
Compressing the keys
Even a system that searches a small subset needs to store enough information to assemble that subset for different inputs. The WMT’19 German-to-English collection illustrates the problem. The paper estimates that storing the original 1024-dimensional token vectors directly would take about 3.2 TiB. The authors use product quantization to represent a vector by a sequence of codes. The method divides the vector into blocks and learns a separate set of representative vectors, or centroids, for each block. This set is called a codebook.
Cₘ = {c₁⁽ᵐ⁾, …, cᴸ⁽ᵐ⁾}, cₗ⁽ᵐ⁾ ∈ ℝ^(D/M)
In this notation Cₘ is the codebook for the block indexed by m. The vector cₗ⁽ᵐ⁾ denotes centroid l in that block, with cᴸ⁽ᵐ⁾ denoting the last centroid. The number of centroids per codebook is L, set to 256. The number of blocks is M, and D is the dimension of the vector entering this quantization step. The notation ℝ^(D/M) indicates that each centroid is a real vector with the same number of components as its block. Here M counts blocks, whereas the script letter ℳ denotes the token datastore.
The codebooks are learned from key vectors through k-means. Within each block, each training example is assigned to its closest centroid, and the centroids are updated using their assigned examples. The procedure alternates assignments and updates. After codebook learning, a stored key is represented by the centroid indices for its blocks.
q̄ = [q̄₁, …, q̄ₘ, …, q̄ᴹ]ᵀ ∈ {1, …, L}ᴹ
The bar marks q̄ as the quantized code for a vector q. The components q̄₁, q̄ₘ, and q̄ᴹ denote the first, the m-th, and the last block codes. The superscript T writes this ordered list as a column. The set on the right says that there are M entries, each an index from 1 through L. The codes stand for centroids, so the stored entry need only identify a representative for each block.
q̄ₘ = argminₗ ‖q⁽ᵐ⁾ − cₗ⁽ᵐ⁾‖₂²
Here q⁽ᵐ⁾ is the block of q indexed by m, and cₗ⁽ᵐ⁾ is the candidate centroid with index l in its codebook. The squared Euclidean norm ‖·‖₂² measures the sum of squared component differences. The operator argmin returns the index l yielding the smallest distance. Thus q̄ₘ is an index, rather than a distance or a vector. The expression describes how to encode a vector for storage. In the asymmetric search below, the incoming query stays in vector form while stored keys are represented by their codes.
The different stores use different transformations and search structures. For the conventional token store and the subset system’s sentence store, the authors use an inverted file index and optimized product quantization. An inverted file index groups entries into lists and lets the search examine promising lists. Optimized product quantization rotates a vector before coding to reduce quantization error. The paper gives 131,072 list centroids for the conventional token index and 32,768 for the sentence index. The search probes 64 clusters in each. The configurations for the conventional token keys, sentence keys, and subset token keys all use 64 product-quantization blocks. The retrieval implementation uses FAISS for the conventional token search and for locating the sentence neighbors. Billion-scale Similarity Search with GPUs
The subset token store uses principal component analysis to transform the decoder keys from 1024 to 256 dimensions before quantization. The query goes through the corresponding transformation before it is compared with the keys. The token candidates for this stage already come from a sentence selection, so the authors implement a linear lookup through those candidates without probing an index of token clusters. The subset search and lookup use PyTorch, and the working token subset is small enough to load into GPU memory in their implementation.
Scoring compressed keys by lookup
Asymmetric distance computation, or ADC, reuses distance calculations within a query. For each block, the search calculates how far the query block is from each centroid in that block’s codebook. It stores those distances in a table. Several candidate keys may carry the same code in a block, so they can use the same table entry. The table is specific to the present query and can serve every candidate in the current subset.
Aₘ[l] = ‖q⁽ᵐ⁾ − cₗ⁽ᵐ⁾‖₂²
Here Aₘ is the lookup table for block m, and Aₘ[l] is its entry at centroid index l. The vector q⁽ᵐ⁾ is the query block after the relevant transformation, and cₗ⁽ᵐ⁾ is its corresponding candidate centroid. The squared Euclidean norm gives the distance stored in that entry. Each table contains L scalar distances, one for each code available in the block. The entries therefore depend on the query and the codebook, while the codes used to index them depend on individual keys.
d(q, k̄ᵢ) = Σₘ₌₁ᴹ dₘ(q⁽ᵐ⁾, k̄ᵢₘ) = Σₘ₌₁ᴹ Aₘ[k̄ᵢₘ]
In this expression q is the query vector, i identifies one of the N candidate keys, and k̄ᵢ is the stored code sequence for that key. The component k̄ᵢₘ is the code of its block m. The block distance dₘ is the distance from the query block to the centroid identified by that code. The function d adds the block distances for all M blocks. The second sum spells out the lookup implementation: each block code selects a value from Aₘ, and the selected values are added.
The distance is asymmetric because the query retains its vector values while the key stands for a collection of centroids. The calculation measures distance to the key as represented by those centroids, so relative to the original key it is approximate. The code sequence is sufficient to compute the score without reconstructing the entire key vector. Direct comparison would repeat coordinate arithmetic for each candidate. Lookup exchanges that repeated arithmetic for a fixed table-building step followed by indexed reads and additions for each key. The cost of the reads still grows with the number of keys scanned. The paper treats this as a good fit for a small subset and a poor fit for scanning the full datastore.
Turning neighbors into a prediction
The distance computation locates the k closest eligible entries, set to 16 token neighbors in the experiments. Being close gives an example more influence, but the vote goes to its token value. If several close entries have the same value, the probability of that token reflects their combined influence.
pₖₙₙ(yₜ | x, y₍<t₎) ∝ Σᵢ₌₁ᵏ 𝟙[yₜ = vᵢ] exp(−‖kᵢ − f(x, y₍<t₎)‖₂² / τ)
The symbol pₖₙₙ is the probability distribution based on neighbors. Here x is the actual input, y₍<t₎ is the candidate translation prefix being extended, and yₜ on the left is a possible next token. The index i runs through the k retrieved neighbors, whose keys and token values are kᵢ and vᵢ. The indicator 𝟙 is 1 when the proposed token equals vᵢ and 0 otherwise. The role of f is to produce the current decoder query. The squared Euclidean distance appears inside exp, the exponential function. Its negative sign makes more distant keys receive less weight. The temperature τ, set to 100, scales the distance before exponentiation. The proportionality sign indicates that the resulting token weights are normalized to give probabilities over the target vocabulary. In the experiments, approximate distances obtained from quantized keys are used in this calculation.
A candidate token that does not occur among the retrieved values has no neighbor weight. It can still receive probability from the underlying translator. Conversely, if all retrieved values agree, the neighbor distribution puts its mass on their shared token, even when the translator alone assigns another token a higher probability. Interpolation determines how strongly that evidence changes the output.
P(yₜ | x, y₍<t₎) = λ pₖₙₙ(yₜ | x, y₍<t₎) + (1 − λ) pₘₜ(yₜ | x, y₍<t₎)
Here P is the final distribution for the next token yₜ given the source x and the prefix y₍<t₎. The neighbor term is pₖₙₙ, and pₘₜ is the distribution produced by the translator itself. The interpolation parameter λ is the weight on the neighbor term, and its complement weights the translator term. Conventional kNN-MT and Subset kNN-MT use this same form. In the subset method, sentence selection and compressed distance computation change the examples that supply pₖₙₙ and the cost of obtaining them.
Experiments and results
What the comparisons measure
The evaluation combines a news translation task with domain adaptation. News tests whether the reduced search can preserve translation quality when the evaluation task matches the general domain of the underlying translator. The adaptation experiments evaluate specialized test sets whose parallel data are available for retrieval. In the open-domain configuration, that specialized data are mixed with general material. A domain label for the individual input does not determine where the system searches.
The speed measure is generated target tokens per second. It captures the throughput of decoding under a specified workload. The authors use a single NVIDIA V100 GPU and distinguish a 12,000-token batch setting, B∞, from a single-sentence setting, B₁. The former represents document translation in the setup. The latter represents online translation. They use beam search with a beam size of 5 and a length penalty of 1.0. Beam search keeps multiple candidate translations in play as decoding proceeds, so the token probabilities described above can affect which partial translations survive as well as which next words are proposed.
The primary quality measures are sacre-BLEU and COMET. BLEU scores overlap between generated translations and references at the level of token sequences. The authors report it using the conventions associated with A Call for Clarity in Reporting BLEU Scores. COMET supplies a separate learned quality measure. The appendix also reports chrF, which uses overlap of character sequences. The measures can rank close systems differently. A quality tie on BLEU therefore answers a more specific question than a tie across all the evaluations.
Base MT is the trained translator running without example retrieval. Conventional kNN-MT is the corpus-wide token index baseline. For WMT’19 news, the paper also compares Fast kNN-MT. The subset variants share the sentence-then-token method and differ in the sentence representation used to select the working set. That comparison is especially important in interpreting domain adaptation, because the amount of parallel data in the store can be held fixed while the system changes which examples it presents to the decoder.
German-to-English news translation
The in-domain evaluation uses newstest2019 from WMT’19 German-to-English, with 2,000 source sentences. The authors use an already trained Transformer big in fairseq. The parallel data used for the datastore come from the WMT’19 news task. A pair is admitted if the subword lengths are at most 250 and the source-to-target length comparison satisfies the paper’s ratio limit of 1.5. The resulting collection has 29.5M sentence pairs and 862.6M target tokens. Subset retrieval uses n = 512 sentence neighbors.
WMT’19 German-to-English news test throughput with 12,000-token batches
Subset retrieval sharply increases throughput over conventional and Fast kNN-MT, while base translation remains fastest.
The numbers
| System or setting | tok/s |
|---|---|
| Base MT | 6375.2 |
| Conventional kNN-MT | 19.6 |
| Fast kNN-MT | 286.9 |
| Subset kNN-MT with LaBSE (this paper) | 2191.4 |
| Subset kNN-MT with AvgEnc | 1816.8 |
| Subset kNN-MT with TF-IDF | 2199.1 |
| Subset kNN-MT with BM25 | 1903.9 |
In news translation, Base MT scores 39.2 BLEU, 84.56 COMET, and 63.7 chrF. Conventional kNN-MT reaches 40.1 BLEU, 84.73 COMET, and 64.2 chrF. Fast kNN-MT reaches the highest BLEU in this comparison at 40.3 and the highest chrF at 64.6, with a COMET score of 84.70. These results establish that retrieval has a measurable quality benefit over base translation on this test even before considering the speed of the various retrieval procedures.
Subset kNN-MT with LaBSE reaches 40.1 BLEU, 84.66 COMET, and 64.1 chrF on the same test. The BLEU match with the conventional baseline is the strongest quality result behind the paper’s in-domain speed claim. AvgEnc reaches 39.9 BLEU and 84.68 COMET. The lexical variants both reach 40.0 BLEU, with TF-IDF at 84.63 COMET and BM25 at 84.60. For news, the tested sentence representations give closely grouped quality scores. The results also show that a ranking based on BLEU alone would miss differences in how those representations fare under COMET.
At B₁, Base MT generates 129.14 tokens per second, conventional kNN-MT 2.5, and Fast kNN-MT 27.1. LaBSE subset retrieval reaches 118.4 tokens per second. The paper reports speedups for this configuration of 111.8 times at B∞ and 47.4 times at B₁ against conventional kNN-MT. AvgEnc reaches 97.3 tokens per second at B₁, with reported speedups of 92.7 times at B∞ and 38.9 times at B₁ over that same baseline. The single-sentence comparison is particularly informative for interpreting the workload: it shows what happens when the speed advantage cannot depend on having a large batch of different translations to process together.
The news experiment also shows why the choice of baseline changes the practical reading. Comparing LaBSE with conventional kNN-MT asks how much of the cost of an established retrieval approach can be removed while preserving its BLEU. Comparing it with Fast kNN-MT asks whether this way of restricting search delivers additional throughput against an alternative specifically designed for speed. Comparing it with Base MT puts a price on using retrieval at all. The chart and the B₁ measurements show that the size of that price depends on the batching regime.
German-to-English adaptation with a shared datastore
For open-domain German-to-English adaptation, the authors keep the news-trained translator. They pool parallel news data with adaptation data drawn from five domains: IT, Koran, Law, Medical and Subtitles. The combined datastore represents 30.8M sentence pairs and 895.9M target tokens. The selected subset contains n = 256 sentence neighbors. The authors evaluate throughput at B∞, the 12,000-token setting. Performance on each domain’s test data therefore reflects retrieval from the same mixed collection.
Conventional kNN-MT improves BLEU over Base MT in each domain. On the IT test it reaches 41.0 BLEU versus 38.7 for Base MT. The LaBSE and AvgEnc subset variants both reach 41.9, while the TF-IDF and BM25 variants both reach 40.0. The comparison separates two effects. Access to the mixed datastore can help the translator on IT text, and the representation used to find examples in that store can determine how much of the improvement a subset retains. COMET supplies a similar distinction in IT: conventional kNN-MT scores 83.93, LaBSE scores 84.17, and AvgEnc scores 84.23, whereas TF-IDF scores 81.70 and BM25 scores 81.16. Base MT scores 83.09.
On the Koran test, the BLEU results are 17.1 for Base MT, 22.3 for conventional kNN-MT, and 20.1 for the LaBSE subset. AvgEnc reaches 19.9. This domain shows that neural sentence selection can give up quality relative to a conventional token search across the mixed datastore. The same comparison looks different on the Law test, where conventional kNN-MT scores 52.6 and LaBSE reaches 53.6. AvgEnc reaches 53.2 there. On Subtitles, the BLEU scores occupy a tighter range: Base MT scores 29.4, conventional kNN-MT 29.6, LaBSE 29.9, and AvgEnc 30.0. BM25 scores 29.4, and TF-IDF scores 29.3. The practical room for improvement over base translation varies with the domain.
Open-domain German-to-English Medical test BLEU by retrieval setting
The neural sentence encoders improve on conventional kNN-MT, while the lexical variants fall below it.
The numbers
| System or setting | BLEU |
|---|---|
| Base MT | 42.1 |
| Conventional kNN-MT | 48.2 |
| Subset kNN-MT with LaBSE (this paper) | 49.8 |
| Subset kNN-MT with AvgEnc | 49.2 |
| Subset kNN-MT with TF-IDF | 47.5 |
| Subset kNN-MT with BM25 | 47.4 |
The Medical test supplies the reported improvement of 1.6 BLEU points over conventional kNN-MT. It also shows how the comparison depends on what the metric rewards. The LaBSE subset scores 84.60 COMET against 84.63 for conventional kNN-MT. AvgEnc scores 84.75 COMET. The Medical chrF results are 66.4 for LaBSE, 66.1 for AvgEnc, and 65.4 for the conventional baseline. The larger BLEU gain for the LaBSE subset consequently coexists with a different ordering under COMET. Its speed on this test is 2328.3 tokens per second versus 19.8 for conventional search, with Base MT at 4392.1.
The paper reports a maximum speedup of 132.2 times over conventional kNN-MT across its experiments. The German-to-English adaptation measurements give the scale of that claim. On the Koran test, for instance, the open-domain large-batch throughput is 2551.3 tokens per second for LaBSE subset retrieval and 19.3 for conventional kNN-MT. The matching test condition matters when reading those speed numbers. They describe the performance of both retrieval strategies with an unknown domain and a very large mixed datastore.
English-to-Japanese adaptation
The English-to-Japanese experiments use a Transformer big trained on JParaCrawl v3. They test ASPEC, which represents scientific writing, and the Kyoto Free Translation Task, or KFTT, whose material is drawn from Wikipedia articles about Kyoto. The adaptation datastore combines parallel data from these tasks with JParaCrawl v3. ASPEC contains 3M sentence pairs, and the authors use its first 2M pairs for datastore construction, following an earlier procedure intended to omit noisier data. The resulting datastore represents 24.4M sentence pairs and 735.9M target tokens. The subset contains n = 512 sentence neighbors, and the reported throughput uses B∞.
English-to-Japanese ASPEC test BLEU under open-domain retrieval
Neural sentence selection preserves more of the conventional retrieval gain than lexical selection.
The numbers
| System or setting | BLEU |
|---|---|
| Base MT | 26.7 |
| Conventional kNN-MT | 32.8 |
| Subset kNN-MT with LaBSE (this paper) | 32.5 |
| Subset kNN-MT with AvgEnc | 32.4 |
| Subset kNN-MT with TF-IDF | 29.5 |
| Subset kNN-MT with BM25 | 29.4 |
On ASPEC, Base MT scores 88.55 COMET and conventional kNN-MT scores 89.13. LaBSE scores 88.77 and AvgEnc 88.75. The conventional baseline also leads on chrF with 41.5, followed by LaBSE with 40.6 and AvgEnc with 40.5. The lexical variants improve BLEU over Base MT, while their COMET scores, 88.24 for TF-IDF and 88.04 for BM25, fall below it. The ASPEC throughput is 5541.6 tokens per second for Base MT, 23.5 for conventional kNN-MT, and 2031.8 for the LaBSE subset. These measurements give a clear example of a quality and speed tradeoff. The subset preserves a substantial part of the benefit of retrieval on BLEU and chrF, while the conventional method maintains the strongest reported quality.
On KFTT, Base MT scores 20.3 BLEU and conventional kNN-MT scores 27.8. AvgEnc scores 26.4 BLEU and LaBSE scores 25.8. TF-IDF and BM25 reach 22.3 and 21.8. COMET favors AvgEnc among the subset configurations at 84.45, compared with 84.11 for LaBSE, 85.32 for conventional kNN-MT, and 83.52 for Base MT. KFTT throughput is 3714.4 tokens per second for Base MT and 28.0 for conventional kNN-MT. The LaBSE and AvgEnc configurations generate 1436.6 and 1471.3 tokens per second respectively. The two English-to-Japanese tests therefore support the speed advantage with a different underlying translator and language direction, while giving a more qualified account of quality than the WMT’19 news BLEU tie.
What the ablations show
The effect of replacing distance calculations with lookups
The most direct speed ablation switches ADC on and off for the same subset configurations on WMT’19 German-to-English. In the large-batch setting, LaBSE yields 2191.4 tokens per second with ADC and 446.4 without it. AvgEnc yields 1816.8 with ADC and 365.1 without it. TF-IDF yields 2199.1 with ADC and 531.0 without it, while BM25 yields 1903.9 with ADC and 471.6 without it. The paper summarizes this as a speed advantage of approximately 4 to 5 times for lookup over the versions without it.
The comparison matters because the systems without ADC already restrict retrieval to a sentence subset. The large gains from restricting candidates and the gains from reducing work per candidate have different causes. Sentence retrieval makes a scan of all eligible keys feasible. Lookup makes that scan cheaper after the subset has been chosen. The ablation measures the latter contribution to throughput with the tested encoders and batching setup. It does not settle how the same variants would compare with another implementation of direct distance computation.
The authors also vary the batch size for LaBSE on the WMT’19 news test. Their batch-size curve shows that the subset system retains a large throughput advantage over conventional kNN-MT as the batch becomes larger. This is compatible with the method’s use of repeated arithmetic and table reads that can be handled in parallel. The comparison with Base MT remains important. Parallel work can process multiple retrievals efficiently, while plain translation avoids those retrievals altogether.
What changes when the subset grows
The subset-size analysis varies n for LaBSE in WMT’19 German-to-English. Increasing n gives the decoder access to tokens from more sentences. It also increases the number of keys examined at every token step. The speed curve shows a persistent advantage over conventional kNN-MT across the tested subset sizes, with the authors reporting that subset translation becomes slower than Base MT from n = 256. At n = 2048, the token search inside the subset accounts for 71.7% of the time. This measurement identifies where the cost goes when the sentence filter admits many examples. The recurring scan can again dominate, even when its distances are computed by lookup.
Quality follows a different curve. On the WMT’19 development set, newstest2018, BLEU rises as the subset grows up to n = 512 and falls with further increases. A very restricted set gives the decoder fewer potential precedents. A larger set lets in more examples that may be useful and more examples whose apparent similarity offers poor guidance for this input. The measured curve supports a balance between access to examples and selectivity on that development set. The authors choose n = 512 for the WMT’19 test configuration using both the quality and throughput analyses.
Domain adaptation has its own development-set comparison. With LaBSE as the sentence encoder, the authors try n = 256 and n = 512 and choose by average BLEU across each language direction’s development domains. In German-to-English, the reported average is 38.3 BLEU for n = 256 and 38.1 for n = 512. The larger subset does better in Law and Subtitles, while the smaller one does better in IT and Medical, and the Koran scores are equal at 19.7. Thus the average determines a shared configuration even though the domain-level preferences differ.
The English-to-Japanese development results favor the larger of the tested subsets. ASPEC scores 31.7 BLEU at n = 256 and 32.0 at n = 512. KFTT scores 24.5 and 25.5, respectively. Their reported average goes from 28.1 to 28.8. The authors consequently choose n = 512 for English-to-Japanese adaptation and n = 256 for German-to-English adaptation. Because the tuning uses LaBSE, these comparisons justify the reported choice for that representative encoder. They do not establish independently optimal subset sizes for AvgEnc or the lexical alternatives.
What the sentence choices contribute
The authors examine the vocabulary of retrieved sentences in the German-to-English Medical task. Their diagnostic is the share of token occurrences represented by distinct token types. They calculate it on the source and target sides separately.
r = U / T
Here r is the unique-token ratio, U counts distinct token types on the relevant side of the subset, and T counts all token occurrences on that same side. Repeating an existing token increases T while leaving U unchanged. The paper reports the resulting ratios as percentages. The diagnostic describes the concentration of the selected vocabulary, giving a way to examine the composition of candidate sets alongside translation quality.
Across the tested encoders, more concentrated subsets coincide with higher Medical BLEU. LaBSE has a source unique-token ratio of 19.6% and a target ratio of 18.5%. AvgEnc gives 20.4% on the source and 19.2% on the target. For TF-IDF, the corresponding ratios are 33.3% and 32.3%, and BM25 gives 34.2% and 32.9%. In the same comparison, LaBSE and AvgEnc score above the lexical variants on BLEU. The ratios suggest that the neural encoders retrieve sets with more repeated wording on both sides. Since this comparison changes the sentence representation, it leaves open which properties of the retrieved examples explain the quality difference.
A more controlled Medical experiment keeps LaBSE and the number of selected sentences fixed while changing where in the ranked results the sentences are drawn from. The first strategy takes the top n. The second takes the n farthest sentences within the top 2n. The third draws n sentences randomly from those top 2n. This makes each strategy dependent on the same underlying ranking while varying the concentration on its closest matches. It also preserves the number of sentence examples, although their target lengths can differ.
The closest selection yields 49.8 BLEU, with unique-token ratios of 19.6% on the source and 18.5% on the target. Selecting from the bottom of the top 2n yields 47.7 BLEU, with ratios of 21.7% and 20.3%. The random selection yields 44.9 BLEU, with ratios of 22.7% and 21.1%. These outcomes support the authors’ account that close sentence matches help keep distracting examples out of the candidate set. Selecting farther or randomly chosen examples changes which target tokens the decoder can see and coincides with poorer BLEU. The lexical diversity statistic tracks that change. The experiment varies retrieval choices, so it leaves open whether explicitly reducing diversity without improving example relevance would produce any gain.
Following a terminology decision through decoding
The Medical case study gives the sentence filter a concrete role. The source concerns the joint use of nifedipine and rifampicin. Base MT and conventional kNN-MT produce the wording A joint use, while Subset kNN-MT with LaBSE produces Co-administration, the term used in the reference. Among the top 3 sentence matches are descriptions of drug combinations with parallel wording about administration. The examples concern other combinations, while still supplying the expression needed for the new sentence.
Across the subset of 256 retrieved sentences, the authors count 30 occurrences of Co-administration and none of A joint use. They also report 101 occurrences of the hyphen token and none of joint. These counts describe the pool of possible evidence. The closer diagnostic comes from the actual neighbors during decoding: at the relevant second step of the beam extending Co, all the retrieved token values are hyphens. The retrieval distribution consequently gives the hyphen probability 1.0 at that step. The final probability also depends on the translator’s prediction and the interpolation weight.
The paper reports negative log-likelihood, or NLL, for the opening tokens of the generated sequences. Lower NLL corresponds to greater probability under the system being evaluated. In the subset output the first token, Co, has NLL 1.49. The hyphen has NLL 0.05, and administration has NLL 0.59. The reported average for those opening tokens is 0.71, versus 0.94 for Base MT and 0.93 for conventional kNN-MT on their respective sequences. The decision therefore involves the evolving score of a candidate prefix. A strong vote for a continuation can favor a beam even if its first token received a weaker score than the competing openings. The case demonstrates that short sub-word decisions can be consequential when the output needs a domain-specific term.
What a known domain changes
In an appendix experiment the authors give German-to-English adaptation a closed-domain setup. Each specialized domain gets its own datastore containing only its parallel data. The news corpus is excluded from those stores. The translator can thus draw examples from an already relevant domain without having to locate them in a mixture. The change helps show how much of the speed advantage and quality difference depends on searching a broad collection.
Conventional kNN-MT is faster with those smaller stores. In Medical, it generates 144.0 tokens per second with a closed store, compared with 19.8 in the open-domain setup. The closed-domain LaBSE subset yields 2287.3 tokens per second in Medical. The authors describe subset retrieval as still 10 times faster than conventional kNN-MT in the closed-domain experiments. The change in search scope narrows the throughput gap while leaving a substantial advantage for subset retrieval in the reported conditions.
The closed-domain BLEU results also clarify why scope is part of the quality comparison. In Law, LaBSE subset retrieval scores 54.5 BLEU against 54.1 for conventional kNN-MT, and in Medical it scores 50.2 against 49.7. In IT, the conventional search scores 43.2 while LaBSE scores 42.8. On Subtitles the scores are 30.9 and 30.5, respectively. A domain label removes the need to separate specialized evidence from general or unrelated domains. Relevance still varies within a domain. A sentence filter may improve the set of token candidates for some inputs and cut off useful candidates for others, even when the collection has already been restricted by domain.
Limitations
Limits identified by the authors
The paper addresses decoding speed. The underlying example collection still has to be represented and stored. In the WMT’19 German-to-English experiment, the authors report a quantized token store of 52GB for 862,648,422 entries, together with a sentence store of 2GB for 29,540,337 entries. A request accesses a small fraction of that collection at a time, but the system needs the full prepared stores to handle varying inputs. Building the token store still entails processing the parallel corpus through the translator, and preparing the sentence store adds work and storage. The speed measurements describe inference and give no measure of how many translation requests would be needed to offset the time spent constructing the stores.
The authors also emphasize that large-batch translation remains several times slower than Base MT. A lookup-based scan saves substantial time against conventional kNN-MT, yet increasing the number of sentence matches still increases the number of token-distance lookups. The authors identify table lookup as the bottleneck for large subsets and mention more efficient lookup using SIMD, which applies an operation across multiple data values in parallel, as a possible route to improvement. The reported throughput comes from the implementation they tested.
The timing results are from one run on a single computer, with a single NVIDIA V100 GPU. The authors explicitly note that a different architecture may yield a different speed improvement. A method that exchanges vector arithmetic for table operations and uses a GPU-resident candidate subset has several ways to interact with hardware and batch layout. The measurement supports the reported comparisons under the specified conditions. Repeat measurements on other systems would be needed to estimate variation in those comparisons.
The authors also identify a limit on transferring this particular selection strategy to the language modeling work they discuss. The subset method assumes that it can represent a complete source input before generation. The same information is unavailable to the language modeling setup described in their discussion. Nearest-neighbor retrieval in those systems shows that the wider idea of consulting examples can apply in other settings. The upfront sentence filter relies on a property of the translation task used here.
The paper flags a risk associated with the open parallel datasets: toxic content in the examples may enter generated translations through either retrieval approach. Its quality and speed experiments do not measure that behavior. Retrieval makes stored examples available as direct evidence for token choice, which is the mechanism both for obtaining useful domain terminology and for giving undesirable dataset content a route into the output.
Limits visible in the experimental setup
The evaluation demonstrates adaptation for German-to-English and English-to-Japanese with the chosen data and trained translators. Specialized parallel examples from the test domains are represented in the adaptation datastores. Open-domain here means that the domain of an individual input is unknown during inference. It does not establish that the approach can adapt equally well when the datastore lacks parallel material from the input’s domain. The sentence filter can only choose among examples that exist, and a nearby example under the chosen representation may still contain little applicable target evidence.
The evaluation of sentence encoders leaves several sources of variation connected. Switching from LaBSE to a lexical representation changes the ranking and content of retrieved sentences. It can also change the number of target tokens to scan, since n counts sentences. The resulting differences in quality and speed describe complete retrieval configurations. They cannot be attributed solely to the value of neural representations or to a fixed change in candidate count. The controlled Medical selection experiment goes further by holding the encoder and n fixed, but it covers one domain and changes which examples enter the subset instead of manipulating one specific linguistic property.
Corpus-level BLEU, COMET, and chrF capture different aspects of translation quality, as the reported rankings show. The Medical case gives an interpretable account of a particular term. It provides no estimate of how often the method improves terminology, introduces misleading terminology, or changes meaning outside that example. The quantitative results also come from a single run without reported uncertainty estimates. Small gaps, including those among the sentence encoders on news, are measured differences for those runs. Their stability under other runs or data is an open empirical question.
The comparison also combines several deliberate engineering choices. The conventional baseline uses a corpus-wide inverted index and optimized product quantization. The subset token search uses principal component analysis, compressed keys, and a linear ADC scan on the GPU. Its measured speed advantage belongs to that configuration as a whole. The ADC ablation isolates a contribution within the subset system, and the subset-size sweep shows how sensitive search cost is to the number of eligible examples. The experiments do not assign an independent share of the headline speedup to every difference between the two complete systems.
Finally, the throughput measurements characterize specified decoding workloads. The single-sentence setting shows that the advantage over conventional kNN-MT persists at low batching. It does not report a distribution of request latencies or performance under varying demand. The large-batch setup clarifies the cost of processing many tokens together. Both measurements concern the tested inference run, while building and retaining the datastore remains a separate resource commitment.
What came after
Retrieval-Augmented Generation for Natural Language Processing: A Survey cites Subset kNN-MT in its treatment of the broader research area. The connection is that the translator uses retrieved examples to modify generation, which places it within the scope of retrieval-augmented generation. In Deguchi and colleagues’ method, retrieval affects generation through a probability distribution over the next token. Sentence search determines where the decoder can look for evidence, while token search determines which parts of those earlier translations can influence a particular prediction.
The documented follow-up is a survey citation. Its title establishes the wider scope in which the method is cited, but the citation alone does not establish a replication, a new evaluation, or an extension of the subset algorithm. The specific contribution that enters that wider literature is the combination tested here: select examples using the complete source sentence, then consult their target tokens as the output develops.
Cite
Cite as Hiroyuki Deguchi, Taro Watanabe, Yusuke Matsui, Masao Utiyama, Hideki Tanaka and Eiichiro Sumita. 2023. Subset Retrieval Nearest Neighbor Machine Translation. Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers).
@inproceedings{deguchi2023subset,
title = {{Subset Retrieval Nearest Neighbor Machine Translation}},
author = {Hiroyuki Deguchi, Taro Watanabe, Yusuke Matsui, Masao Utiyama, Hideki Tanaka and Eiichiro Sumita},
booktitle = {Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
year = {2023},
doi = {10.18653/v1/2023.acl-long.10},
url = {https://doi.org/10.18653/v1/2023.acl-long.10}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/deguchi-2023-subset-retrieval-nearest-neighbor-machine/