K NOWLEDGE I NFUSED D ECODING
A BSTRACT
Pre-trained language models (LMs) have been shown to memorize a substantial amount of knowledge from the pre-training corpora; however, they are still limited in recalling factually correct knowledge given a certain context.
Hence, they tend to suffer from counterfactual or hallucinatory generation when used in knowledge-intensive natural language generation (NLG) tasks.
Recent remedies to this problem focus on modifying either the pre-training or task fine-tuning objectives to incorporate knowledge, which normally require additional costly training or architecture modification of LMs for practical applications.
We present K nowledge I nfused D ecoding (KID)—a novel decoding algorithm for generative LMs, which dynamically infuses external knowledge into each step of the LM decoding.
Specifically, we maintain a local knowledge memory based on the current context, interacting with a dynamically created external knowledge trie, and continuously update the local memory as a knowledge-aware constraint to guide decoding via reinforcement learning.
On six diverse knowledgeintensive NLG tasks, task-agnostic LMs (e.g., GPT-2 and BART) armed with KID outperform many task-optimized state-of-the-art models, and show particularly strong performance in few-shot scenarios over seven related knowledge-infusion techniques.
Human evaluation confirms KID’s ability to generate more relevant and factual language for the input context when compared with multiple baselines.
Finally, KID also alleviates exposure bias and provides stable generation quality when generating longer sequences.
Code for KID is available at https:// github.com/microsoft/KID .
I NTRODUCTION
Pre-trained language models (LMs) have been shown to capture rich semantic and syntactic features, as demonstrated by the state-of-the-art performance on many generation tasks such as abstractive summarization (Zhang et al., 2020b; Chu & Liu, 2019) and dialogue generation (Roller et al., 2021; Zhang et al., 2020c).
Their generations, however, can be quite limited in scenarios requiring knowledge —they frequently struggle with issues such as being easily misguided by phrase cooccurrence (e.g., “Talk?
Birds can talk.” ), failing to handle negation (e.g., “The theory of relativity was not developed by Einstein.” )
(Kassner & Schütze, 2020), and being unable to compare commonsense concepts, such as time (Qin et al., 2021) and digits (Talmor et al., 2020).
To enhance the performance of LMs on knowledge-intensive NLG tasks 1 , prior studies have proposed to re-train LMs with knowledge-aware objectives (Zhou et al., 2020;
Xiong et al., 2020; Zhang et al., 2019; Khandelwal et al., 2020) or add special architectures to encode knowledge (Bosselut et al., 2019; Logan et al., 2019; Peters et al., 2019b) from external resources (e.g., knowledge graphs such as
C ONCEPT N ET (Speer et al., 2017) and A TOMIC (Sap et al., 2019)).
These methods, though yielding impressive results on many downstream tasks, can be computationally expensive.
More importantly, knowledge implicitly parameterized in LM architectures is difficult to revise and expand (Lewis et al., 2020b), and wrong generations are hard to diagnose due to lack of interpretation (Talmor et al., 2020), which heavily limits their real-world applications.
More recent retrieval-based models try to tackle these problems by augmenting inputs with retrieved knowledge evidence (Lee et al., 2019; Guu et al., 2020).
For example, RAG (Lewis et al., 2020b) leverages non-parametric memory to access extensive knowledge (in the form of unstructured documents), and jointly fine-tunes a parametric LM (i.e., BART (Lewis et al., 2020a)) to enable knowledge-aware generation.
A key limitation of such methods is that they retrieve documents only once while grounding them in the input static context, and thus cannot support the dynamic nature of the context as new tokens are generated.
The static knowledge becomes a major problem for tasks where longer and abstractive generation is expected, such as open-ended story generation (Mostafazadeh et al., 2016), multi-turn dialogues (Zhao et al., 2020), and conversation summarization (Gliwa et al., 2019).
Moreover, in a recent study, Krishna et al.
(2021) replaced the knowledge retriever in RAG with a random retriever and found little difference in the resulting performance on a long-form QA task named ELI5 (Fan et al., 2019b), indicating the model may not be actually grounding its text generation to the retrieved documents.
To address these limitations, in this work, we present a novel decoding algorithm KID, aiming to better infuse knowledge into generation in a dynamic manner.
Instead of solely relying on the static knowledge retrieved at beginning, during each step of LM decoding, KID dynamically searches promising continuation from retrieved knowledge, to guide the current step generation.
Specifically,
KID maintains a local knowledge memory, interacts it with a knowledge trie dynamically created from retrieved supporting documents, and updates the local memory as a knowledge-aware constraint to guide the generation.
The key intuition behind KID is that existing LM pre-training objectives are usually defined at the token level yet do not explicitly model concept-centric knowledge (Xiong et al., 2020) — thus motivating us to reshape the probability mass at each step decoding towards the distribution of entities in knowledge.
The contribution of this work is three-fold: First , we introduce KID as a model and task agnostic decoding method that integrates knowledge on the fly and can be applied to various knowledgeintensive tasks with different generative LMs.
Second , from a docoding perspective, on six knowledgeintensive NLG tasks, GPT2 (Radford et al., 2019) and BART (Lewis et al., 2020a) equipped with KID significantly outperform conventional beam search or sampling decoding by a large margin.
Third , from a knowledge infusion perspective, unlike seven strong knowledge-infusion baselines which require either additional retraining or special architecture modifications, KID leverages knowledge more effectively as a light-weight knowledge infusion solution.
Additionally, in few-shot scenarios
KID significantly improves over them, demonstrating its generalization ability in low-resource and domain shifting regimes.
R ELATED W ORK
We briefly review existing work enhancing LMs with external knowledge and representative decoding algorithms for generation.
Enhancing Language Model with Knowledge.
Large language models implicitly encode knowledge in their parameters but with limits (Petroni et al., 2019; Kassner & Schütze, 2020; Lin et al., 2020a).
Several architectures and objective functions have been proposed to explicitly encode external knowledge (Sun et al., 2020;
Logan et al., 2019; Roberts et al., 2020; Levine et al., 2020), or to augment LM pre-training data with retrieved knowledge (Lewis et al., 2020b; Guu et al., 2020; Lee et al., 2019).
However, Talmor et al.
(2020) notes that the reasoning ability of such LMs is strongly tied to the context seen during pre-training and is thus hard to generalize to new domains.
Built on
LMs, KID incorporates extra knowledge from external resources (Wikipedia) and thus shows strong performance in knowledge-intensive NLG tasks.
Better Decoding Algorithm.
Two common strategies dominate the decoding algorithms used by most generative models: beam search which maximizes likelihood in a local horizon (due to finite beam size), and sampling decoding (e.g., top- k sampling (Fan et al., 2018; Holtzman et al., 2018)) which relies on randomness.
Holtzman et al.
(2020) find beam search often produces generic and repetitive generation, while top- k sampling tends to pick unlikely tokens which creates incoherent and unrelated sequences.
Existing attempts to mitigate these problems include reranking (Adiwardana et al., 2020;
Shao et al., 2017), adding control signals (Zhang et al., 2018;
Xing et al., 2017), and self-adaptive truncation (Welleck et al., 2020; Peters et al., 2019a).
None of these decoding algorithms consider integrating knowledge in the generation process.
Reflective decoding (West et al., 2021) and DeLorean (Qin et al., 2020) are two recent decoding algorithms that focus on abductive commonsense reasoning.
Reflective decoding in particular has the potential to be extended to other knowledge-intensive tasks.
We compare it with KID in our experiments.
K NOWLEDGE I NFUSED D ECODING
We detail the implementation of KID in this section.
As shown in Figure 1, KID comprises of three steps: retrieving relevant knowledge (§3.1), constructing external and local knowledge memory (§3.2), and guiding current step decoding under the constraint of the knowledge trie (§3.3).
3. R ETRIEVING E XTENSIVE K NOWLEDGE FROM W IKIPEDIA
The first step of KID is to retrieve several context-relevant documents to ground the following generation.
We use DPR (Karpukhin et al., 2020) as our general-purpose knowledge retriever, which projects contexts and relevant documents to a 768-dim shared embedding space using a bi-encoder network (i.e., two independent BERTs (Devlin et al., 2019)).
Here, the documents refer to the 100word chunks of Wikipedia passages released by RAG (Lewis et al., 2020b), a total of 21M documents as our knowledge source Z .
We pre-load the weights from the latest checkpoint of DPR (March 2021), as it improves retrieval performance by using mined negative samples and contrastive learning, which is also suggested by Jernite (2020).
During retrieval, we perform a maximum inner-product search (MIPS) with faiss 2 accelerated by GPU (Johnson et al., 2019).
Formally, we retrieve k most relevant document z [ 1 ,...,k
] ∈ Z for context x context as:
[Equation]
where BERT ( ⋅ ) means the vectors encoded by BERT.
The number of retrieved documents k is a task-specific hyper-parameter—we discuss its impact on performance in §4.3.
C ONSTRUCTING E XTERNAL AND L OCAL K NOWLEDGE M EMORIES
We convert multi-document input retrieved from previous step into compressed knowledge memories, in order to 1) allow relevant knowledge to be easily identified, 2) reduce the memory footprint of the knowledge, whose size grows linearly with the number of retrieved documents.
Following design choice of previous successful methods (Bosselut et al., 2021; Huang et al., 2020; Fan et al., 2019a), we adopt co-reference resolution and open information extraction (OpenIE) (Stanovsky et al., 2018) to convert plain text into triplet form 3 .
For example, knowledge statement like “Iceland is a Nordic island country in the North Atlantic Ocean and it is the most sparsely populated country in Europe.” will be converted to subject-relation-object triplets such as ⟨ subj :Iceland , rel :is , obj :Nordic island country ⟩ , ⟨ subj :Iceland , rel :is , obj :most sparsely populated country in Europe ⟩ , etc.
To account for overlapping elements from these triplets, we use a prefix tree (namely Knowledge
Trie G ext ) to store and organize the extracted triplets, by setting the subject in each triplet as the key in the G ext .
Note that unlike common character-level dictionary tries (Chen et al., 2020; Germann et al., 2009), in G ext each triplet is stored in token unit as our goal is to efficiently query and traverse the knowledge triplets stored in it.
A tree structure encoding knowledge is appealing to knowledge intensive NLG tasks, since 1) the non-cyclic structure helps reduce repetitions in generations, and 2) querying a prefix tree can be efficiently completed in constant time ( O (∣ x context ∣) ) which does not involve any costly traversal on the graph (Ji et al., 2020; Zhang et al., 2020a), regardless of the scale of grounding knowledge (normally ∣ x context ∣ ≪ ∣ k Wiki docs ∣ ).
We also maintain a local memory G loc (a first-in-first-out list) [Figure] that records all the mentioned entities in current context, to focus on concept-centric knowledge (Zhou et al., 2020; Lin et al., 2020b).
More details about how we construct and query these knowledge memories can be found in §A.2 of Appendix.
3. K NOWLEDGE T RIE C ONSTRAINED D ECODING VIA P OLICY G RADIENT
Background.
Current generative LMs are trained to maximize the probability of generating groundtruth tokens at each decoding step.
Assuming y ∗ 1 ∶ T = { y ∗ 1 , y ∗ 2 , ..., y ∗ T } is the ground-truth output sequence for a given context x context , the MLE objective minimizes the following loss:
[Equation]
In knowledge-intensive NLG tasks, however, it is reported that the MLE training goal does not explicitly model knowledge, and thus the LM often produces counterfactual generation by surfacelevel misguidance (Zhou et al., 2020; Petroni et al., 2019).
Furthermore, the teacher-forcing algorithm used by MLE training leads to the exposure bias problem (Ranzato et al., 2016), as the LM has access to ground truth sequence up to the next token during training, but does not have such signal during testing, which causes accumulated errors when generating longer sequence (Paulus et al., 2018).
Both problems heavily limit the performance of popular LMs on diverse knowledge-intensive NLG tasks.
One remedy is to learn a generation policy that not only maximizes knowledge correctness but also alleviates exposure bias in longer generation, which can be made possible with policy gradient in reinforcement learning (RL).
Knowledge Trie Constrained Decoding.
To formulate NLG as a RL problem, we define the state as the generated tokens before t (i.e., s t
= y < t ), and the action as the current step output token (i.e., a t =
y t ).
The softmax output of the language modeling head, i.e., a categorical distribution p t over the entire vocabulary, is considered as the policy π t for picking token y t (action a t ) given the state s t =
y < t (Guo et al., 2021;
Liu et al., 2020).
Note that p t (i.e., π t ) could be from either a pre-trained
LM or a LM fine-tuned with task data.
While conventional sampling decoding and beam search pick next token directly from p t , here we look to inject knowledge to adjust p t to guide decoding.
For current input context x context at step t , we first take its concept mentions in local memory { c 1 , c 2 , ..., c m } ⊂ G loc , and then query the knowledge trie G ext with these concepts by max hops of h max .
The union of queried results of all hops V i
= { v i 1 , v i 2 , ..., v in } for i = 1 , .., h max then serve as knowledge demonstrations for current step generation.
To put probability mass on tokens aligning with these demonstrations, we compute the t -th step knowledge gain r t as the total log probability of all retrieved tokens from G ext under decoding policy π t as r t = ∑ h max i = 1 ∑ v ∈ V i I
[ v ] ⊤ ⋅ log π t , where I [ ⋅ ] is the indicator function that will output an one-hot vector with a 1 in the coordinate of token v in the vocabulary and 0’s elsewhere.
With r t , we define the t -th step reward J RL ,t on trajectories τ induced by π t as:
[Equation]
where π ∗ t is the desired policy (a vector initialized from π t ) to produce tokens approaching knowledge demonstrations, and the KL penalty term KL ( π t ∣∣ π ∗ t ) is to avoid the updated policy drifts too much away from the original one, also known as trust region constraint (Schulman et al., 2017; 2015).
Note that we use off-policy sampling to collect trajectories, with an importance weight π ∗ t / π t to calibrate the knowledge gain r t , which can stabilize the optimization (Munos et al., 2016). Algorithm 1: Trie-Constrained Policy Gradient for t = 1 , 2 , . . . do Collect samples ( a t ∣ s t ) by vanilla policy π t ;
Compute reward J RL ,t by Eq.
Compute updated policy π ∗ t ← arg max of
SGD via ); if KL ( π t ∣∣ π ∗ t ) ≥ 2 σ then β t + 1 = 2 β t ; else if KL ( π t ∣∣ π ∗ t ) ≤ σ / 2 then β t + 1 = β t / 2 ; end Generate token y t with updated policy π ∗ t ; end Algorithm 1 shows how we obtain the updated policy through policy gradient.
We set β dynamically to control the KL penalty within the reward function.
The target divergence σ tunes the strength of knowledge infusion—smaller σ means less infusion while larger σ provides more space for policy gradient (We set σ to 0.02 across all tasks).
To generate the actual token for step t , we pick from the updated policy π ∗ t with sampling decoding.
The token should conform to the knowledge demonstrations, since its corresponding hidden states have shifted towards V due to policy gradient.
We empirically choose K = 3 for good performance in most cases.
Prior approaches have also explored to set sequence-level metrics such as BLEU (Papineni et al., 2002) as the reward to directly optimize the generation quality (Li et al., 2016; Paulus et al., 2018).
However, many studies report such sparse reward will cause low efficiency optimization (i.e., J t = 0 , ∀ t < T ) (Guo et al., 2021).
Our trie-constrained policy gradient method seemingly mitigates this problem by using an immediate reward ( J θ ∗ RL ) at each step with reasonable approximation.
Recent off-line RL for NLG work show promising results when using data itself (rather than metrics) to estimate rewards (Pang & He, 2020;
Jaques et al., 2020)—our design of knowledge trie echoes their findings.
The gold data distribution memorized in trie is treated as guidance to reshape each step probability distribution, and thus brings benefits on alleviating exposure bias during long generation.
E XPERIMENTS 4. E XPERIMENTS S ETTINGS
We consider three diverse types of knowledge-intensive tasks for evaluation (statistics see §A.1):
Abstractive Question Answering.
We study Abstractive QA, which requires the model to generate free-form answers to the questions.
We choose long-form QA task ELI5 (Fan et al., 2019b) and
MSMARCO NLG task v2.1 (Nguyen et al., 2016)
as two commonsense QA tasks whose questions can be mostly answered by referring to Wikipedia passages.
We also use two extra QA tasks
PIQA (Bisk et al., 2020) and PubMedQA (Jin et al., 2019) whose questions require domainspecific knowledge to answer (i.e., physical interaction knowledge for PIQA, and medical knowledge for PubMedQA).
We calculate BLEU-1 and ROUGE-L scores to be able to compare directly with related work (Lewis et al., 2020b; Krishna et al., 2021).
Logic-centric Writing.
We also investigate whether KID can benefit NLG tasks that do not have an explicit query form for certain knowledge (i.e., with specific questions, like QA tasks).
We study ROC story ending generation (Mostafazadeh et al., 2016), which requires generating a legitimate ending given a four-sentence context, and α NLG (Bhagavatula et al., 2020) which [Table] Published
[Table]
requires generating reasonable hypothesis given two observations.
We follow related work (Zhou et al., 2020; Guan et al., 2020) in using BLEU-1 and ROUGE-L as evaluation metrics.
Dialogue Generation.
Chitchat dialogues are normally multi-turn discussions over a variety of topics or concepts, which often involve topical and factual knowledge (Petroni et al., 2021).
We study two dialogue datasets that require knowledge grounding: Wizard of Wikipedia (WoW) (Dinan et al., 2019), where the speaker in the conversation must ground their utterances in Wikipedia passages, and
MuTual (Cui et al., 2020), where utterances have to be a logically-coherent continuation of the given multi-turn context.
We follow existing work and the leaderboard of WoW in using F-1/ROUGE-L for
WoW and MRR/ROUGE-L for MuTual evaluations.
We take two representative language models to demonstrate the effectiveness of KID: 1) GPT2medium
(Radford et al., 2019) which is an auto-regressive LM, and 2) BART-large (Lewis et al., 2020a) which is a text-to-text LM.
We tune the hyperparameters based on the models’ performance on an in-house split dev set, and report the results that were best on the official dev set 4 .
4. M AIN R ESULTS ON D ECODING P ERFORMANCE
Comparison with off-the-shelf decoding methods.
Table 1 compares the results of GPT2-medium and BART-large on six diverse NLG tasks with beam search (Beam), sampling (Sampling), and our proposed KID decoding algorithm.
Compared with the other two commonly used decoding algorithms, knowledge-guided KID achieves better results for all the cases, with significant improvements (with p-value p < 0 .
over the next-best decoding strategy (e.g., 4.1 absolute increase for BLEUin ELI5 (GPT2)).
We also notice that KID brings greater improvements to auto-regressive language models – above 5% improvement in 9 out of 12 metrics for GPT2-medium, in contrast to 5 out of 12 for text2text language model (BART-large).
The reason could be that the reinforcement learning objective of KID is more similar to the MLE objective of GPT2 than the denoising objective of
BART (Pang & He, 2020; Guo et al., 2021).
Compared with task-specific state-of-the-art models 5 , task-agnostic LMs armed with KID can beat SOTA results on three different tasks (ELI5, ROC, WoW), which is not possible when beam search and sampling decoding is used.
This interesting observation demonstrates a huge potential in inference-time optimization, which we believe is worth exploring further.
[Table]
Comparison with existing knowledge-infusion methods.
Besides evaluating KID from a pure decoding perspective [Table] we also compare KID with existing methods of integrating knowledge for knowledge-intensive NLG tasks.
In addition to ELI5 and MSMARCO, we also evaluate on two extra QA tasks: PIQA and PubMedQA (discussed in §4.1), where answers are considered to be not fully covered by Wiki knowledge.
Besides RAG (Lewis et al., 2020b), we consider several competitive prior methods incorporating knowledge including a) GPT2 + Knowledge (Guan et al., 2020), which post-trains GPT2 on triplets-converted augmentation data (e.g., ⟨ helium , is , gas ⟩ → “helium is gas.” ); b) GPT2 + COMeT Embeddings , which fuses knowledge-aware embeddings (e.g., from CoMET (Bosselut et al., 2019); c) FiD-T5 (Izacard & Grave, 2021; 2020), which concatenates retrieved grounding documents with context as new input; d) QA-GNN (Yasunaga et al., 2021), which traverses a graph neural network; e) Reflective decoding (West et al., 2021), which relies on forward and backward LMs to encode bi-directional context for generation.
As shown in Table 2 (columns with 100% training data), KID outperforms all other methods in
ELI5 (with 5.2 ROUGE-L points improvements over the second-best method (RAG)), and achieves competitive results requiring neither specific model architecture nor additional training to infuse knowledge.
We also evaluate on a few-shot setting, where only 10% of task training data is available to mimic domains for which ample training data is unavailable or difficult to acquire in practice.
This setting also tests a method’s ability to transfer to new domain and to generalize to unseen entities, concepts or events.
Also shown in Table 2, KID with a LM similar in size to the baselines (GPT2medium) achieves best few-shot performance in all four tasks, including PIQA and PubMedQA.
Our experiments find baseline methods tend to generate off-topic and hallucinatory answers when the expected answer length is long (e.g., ELI5 and PIQA).
RAG shows limited performance in few-shot scenarios, due to its static knowledge retrieved by initial context cannot be generalized to newly generated tokens.
KID, instead, dynamically searches references for grounding, thus showing more agility in unfamiliar context.
Comparison with more baselines can be found in §A.3 of Appendix.
4. A BLATION S TUDIES FOR THE B EST P ERFORMING KID
How to choose retriever?
We experiment with replacing the default DPR document retriever of
KID, with popular retrievers including the TF-IDF retriever from DrQA (Chen et al., 2017), and the Wiki retriever used in BLINK (Wu et al., 2020).
We also experiment with a random retriever baseline that retrieves documents randomly given the context.
We choose two tasks ELI5 and WoW that provide ground-truth knowledge provenance, which are also the only two KILT tasks requiring long and abstractive generation (Petroni et al., 2021).
Following KILT benchmarking metrics, we use precision@1 (Prec@1) to measure the top-1 retrieval accuracy, and ROUGE-L (R-L) to evaluate generation quality.
We also consider directly measuring how much knowledge in the ground-truth evidence (provenance) appear in the actual generation.
We compute knowledge Coverage (Cov) (used in Guan et al.
(2020)) which is the 1-gram overlap between the triplets of provenance and the generation, to measure the extent to which our generation is actually using the retrieved knowledge.
[Figure]
Table 3 shows the corresponding results.
For reference, RAG obtains nearly equivalent performance (R-L and Cov) with random retriever and the DPR FT6 , which indicates its generation mainly relies on the fine-tuned BART and ignores retrieved knowledge (also observed in Krishna et al.
In contrast, KID with the default DPR retriever outperforms all other retrievers and RAG variants in retrieval accuracy (Prec@1), knowledge coverage (Cov) and final generation quality (R-L).
We observe high correlation 1, indicating that a good knowledge retrieval is essential for knowledge-intensive
[Table]
[Table]
How much knowledge do we need?
We also study the impact of number of documents ( k ) we retrieve and number of hops ( h max ) we use to query the knowledge trie, two factors that determine how much knowledge we use to ground the generation.
As shown in Figure 2 (a) and (b), for the example task ELI5, we find the generation performance measured by ROUGE-L does not benefit from simply more retrieved documents—an optimum k is 5 through empirical observation, and similarly, h max = 4 brings best performance.
A larger k might risk retrieving less relevant Wiki documents and a larger hop h max with deeper traverse through the knowledge trie tends to bring in off-topic knowledge.
We also plot the average time consumed for generating each sentence as reference (the second y -axis in Figure 2 (a) and (b)), which demonstrate the best performing k = 5 and h max =achieve a reasonable trade-off between generation quality and decoding speed.
In Figure 2 (c), we quantify the exposure bias problem through human judgements.
We first sample 200 ELI5 test set questions and generate answers of various lengths { 80 , 100 , ..., 260 } (260 is the average sequence length in training set) with beam search, sampling, reflective (West et al., 2021), and KID.
We then ask humans to rate these generations with 7-point Likert scoring (Joshi et al., 2015) how likely the generated text is a natural sentence.
Each generation receives at least 15 ratings.
We observe that both beam search and sampling methods suffer from the exposure bias problem 7 , since
[Table]
their ratings deteriorate as the length grows.
Reflective decoding exhibits similar trend since it stills relies on MLE training.
KID, instead, dynamically infuses global knowledge with LM predictions at each step and thus can mitigate exposure bias by imitating non-local demonstrations.
Does the size of LM matter?
We run experiments with different sizes of LMs that have the similar architecture (GPT2-medium, and GPT3 with 1.3B, and 2.7B parameters 8 ).
Table 4 shows that overall larger LMs benefits all decoding methods with KID consistently outperforming Beam search and sampling decoding.
In addition, KID brings more gain for non-finetuned LMs than fine-tuned ones, potentially because the fine-tuning LM is already fit onto the new domain thus less knowledge infusion is needed.
Interestingly with KID, vanilla GPT3-2.7B outperforms its 1.3B fine-tuned counterpart, which is especially meaningful since ever-large foundation models (Bommasani et al., 2021) are expensive to fine-tune effectively on common hardware settings (Liu et al., 2021).
4. H UMAN E VALUATION
We recruited 300 MTurk participants to manually examine generated outputs of several decoding algorithm in terms of relevance, factuality, and fluency.
Each participant was asked to review five sample generations without revealing their source.
We used paired samples t -tests to examine the difference between human references and other decoding methods generation.
As Table 5 shows,
KID generates similar quality sequences as human references without significant differences across all three tasks, while in ELI5, beam search and reflective decoding generation are rated significantly low in both relevance and factuality, partially due to exposure bias in longer generation.
There is no significant difference in grammaticality between KID and vanilla decoding methods.
The exact questions we asked participants can be found in §A.5 of Appendix.
C ONCLUSIONS AND F UTURE W ORK
In this work, we proposed KID, a novel decoding algorithm which in each step of decoding dynamically fetches knowledge and guides token decoding via interaction between a local knowledge memory and a constructed external knowledge trie.
Given its decoding nature, KID doesn’t require architecture changes to existing LMs and is applicable to various generative LMs.
Evaluations on eight knowledge-intensive NLG tasks demonstrated the effectiveness of KID and that its generations are aligned with human references well.
In addition, KID is also found to alleviate exposure bias and maintain quality for long generations.
Future work of KID could study more efficient data structures to accelerate knowledge fetching and integration.
One could also investigate combining KID with prompt based generations to further boost the performance, especially in the few-shot settings.
Another direction is to further study the integration of KID with full size foundation models, like GPT-3 175B to understand KID’s potential.
E THICS AND R EPRODUCIBILITY S TATEMENT
The goal of KID is to provide a general-purpose knowledge infusing decoding algorithm by leveraging retrieved Wikipedia documents.
Still, the generation of KID can be affected by certain biases from the
LM it is based on though those biases may be partially mitigated by the knowledge demonstrations.
Another major ethical consideration is that KID can mimic undesirable attributes of the target knowledge source documents that could be non-contemporary and do not represent current norms and practices—and KID has no scheme to diagnose these problems.
Furthermore, our experiments and analysis are done in English and therefore we do not claim that our findings will generalize across all languages, although our framework has potential to be extended to other languages with necessary modifications.
For reproducibility, evaluations of KID and baseline methods are all conducted on public NLG data sets.
We compare results from published papers and public leaderboards.
Code and scripts for reproducing KID is available on GitHub at https://github.com/microsoft/KID .
A A PPENDIX A. D ATASETS S TATISTICS
We chose eight knowledge intensive NLG tasks to evaluate KID.
Here we present the dataset statistics of these tasks in Table A1.
The links to these datasets can be found in §4.1.
[Table]
A. D ETAILS ON K NOWLEDGE T RIE C ONSTRUCTION AND Q UERY A.2. K NOWLEDGE T RIE C ONSTRUCTION
In this section, we detail the process of constructing the knowledge trie and how we query for the knowledge in a dynamic fashion.
In Figure A1 (a), for a given question (say from the ELI5 dataset), the DPR retriever (Karpukhin et al., 2020) would retrieve k documents (the effect of choosing different k on performance has been discussed in §4.3; we use k = 3 here for simplicity) from 21M 100-token Wiki documents as the grounding passages for the question.
We then use co-reference resolution to replace the pronouns with their referents (colored in red), normalize the text (e.g., removing links, lower-casing, etc.), and pass them through the OpenIE (Stanovsky et al., 2018) to obtain knowledge triplets (the use of OpenIE can be also seen in related prior work (Trisedya et al., 2019;
Wu et al., 2019; Fan et al., 2019a)).
The end nodes of the extracted triplets (i.e., the subj and obj ) serve as the key-value pairs when they are stored in the external knowledge trie ( G ext ), and the relations between nodes are translated to the edges.
We use the stems of the tokens as the keys in
G ext (e.g., “ driving ” → “ drive ”), in order to compress duplicated nodes in a concept-centric manner.
During knowledge trie construction, besides the one-step key-value pairs from the triplets, we also consider multiple-step relations by looking for key mentions in the values of previous keys (e.g., value: “ influence of drugs ” → next-hop key: “ drug ”).
Such iterative procedure will end when there are no more keys appearing in the values.
Specifically, we use depth-first search (DFS) to record the maximum depth of the child branch for each key node, and also memorize the corresponding values (and its next-hop key) on the branch to facilitate further query.
A.2. D YNAMIC Q UERYING FOR K NOWLEDGE
Since retrieving knowledge from millions of documents is slow (even with GPU acceleration), the knowledge trie described above is constructed off-line.
We pre-compute and store this knowledge trie on the disk, and build the local knowledge memory on the fly.
The local knowledge memory is simply a First-in-First-out (FIFO) list which continuously stores newly generated entities ( G loc ; initialized with entities in the input question), whose length will be limited by w max (we set w max =
h max empirically, where h max is the max query hops).
In Figure A1 (b) we show a query example with the query word “ driving ” in the local memory.
The query word is firstly converted to its stem (i.e., “ drive ”), and then its demonstrations are retrieved with the key “ drive ”.
We show the whole generation loop of KID in Algorithm 2.
At each step of the decoding, we first collect knowledge demonstrations by querying G ext with each entity in G loc as key.
The collected demonstrations (a list of tokens) will then serve as target word space to guide current step generation (has been detailed in §3.3).
The local knowledge memory is updated only when a new entity is generated.
This is because the non-entity words (such as stop words, digits, etc.) a) are rarely the keys in the G ext (which are subj in OpenIE triplets), and b) rarely lead to meaningful next-step constraints (it’s hard to answer what’s a proper continuation of “ the ”).
Since the external knowledge trie is constructed off-line, the query time mainly depends on the number of query words in the local knowledge memory (with max length w max ), and the maximum number of in some studies to have a negative effect on driving ability.
The British Medical Journal indicated that "drivers who consume cannabis within three hours of driving are nearly twice as likely to cause a vehicle collision as those (who) drivers are not under the influence of drugs or alcohol".
In "Cannabis and driving: a review of the literature and commentary", the United Kingdom's
Department for Transport reviewed data on cannabis and driving, finding "Cannabis impairs driving behaviour.
However, this impairment is mediated in that subjects under cannabis treatment appear to perceive that they are indeed impaired.
Where they can compensate, they alcohol concentration is performed using three methods – blood, breath, or urine.
For law enforcement purposes, breath is the preferred method, since results are available almost instantaneously.
Drug testing screens are typically performed in scientific laboratories so that the results will be admissible in evidence at trial.
Due to the overwhelming number of impairing substances that are not alcohol, drugs are classified into different categories for detection purposes.
Drug impaired drivers still show impairment during the battery of standardized field sobriety tests, but there are additional tests to help detect drug impaired driving.
The Drug Evaluation and Classification program is for life.
Driving under the influence of drugs “to an extent as to be incapable of having proper control” is illegal.
The Police may require suspects to undergo an objective (at the police station)
Impairment Test.
Suspects who fail the test shall surrender (their) suspects who fail the test driving licence for 24 hours.
Regarding common drugs, the Road Safety Council reminds drivers to check the side effects before driving.
The law prohibits driving with any concentration of illicit drugs: heroin, cocaine, ketamine, methamphetamine, cannabis and MDMA .
Drug–impaired driving
Drug–impaired driving, in the context of its legal definition, is the act of driving a
[Table] drug [Table] impaired drivers impair driving behaviour subjects under cannabis (a) (b)
Paragraph
ID:
Paragraph
ID:
Paragraph
ID:
ELI5 Question: Does marijuana impair driving ability?
marijuana, driving, ability marijuana, driving , ability, ... cannabis, vehicle, collision, influence, drugs, impaired, drivers, testing, screens, driving,
[Figure]
hops query the external knowledge trie ( h max ) with, which is approximately w max ∗ h max
We claim this is actually constant time complexity because h max and w max are fixed hyper-parameters (normally 1-5, as discussed §4.3) and it will not scale up with sequence length or the number of grounding documents retrieved.
A. M ORE C OMPARISON WITH I MPROVED D ECODING A LGORITHMS
Besides the baselines we compare in the paper, there are other inference-time decoding methods that focus on improving generation quality in different perspectives, such as diversity (Baheti et al., 2018), and attributes controlling (Dathathri et al., 2020), and entity appearance (Mao et al., 2020) 9 .
if then
We also notice some methods that are training-time optimization, such as CTRL (Keskar et al., 2019), which requires re-training language models conditioned on a set of static control words, and fusion-in-decoder (FiD) (Izacard & Grave, 2021; 2020), which concatenates additional retrieved grounding sentences with input text, and fine-tunes text2text language models (e.g., T5 (Roberts et al., 2020)).
KID differs from all these methods, since 1) KID aims to improve knowledge awareness during decoding, though we also find KID could mitigate exposure bias, and 2) KID can function as a standalone module requiring neither specific model architecture nor re-training or fine-tuning the language model (as shown in §4.3, the experiments with vanilla GPT3-2.7B).
In the following part, we compare KID with all above methods except CTRL since it requires costly language model retraining on each new domain and how to pick control words for dynamic knowledge seems ambiguous.
We also prepare a naive version of KID (Little KID) which uses plain list instead of graph structure (the knowledge trie) to store knowledge, where we directly use all the end nodes of extracted triplets from the documents as constraints without any dynamic query.
We run experiments on QA tasks as FiD was trained on, and discuss their differences on performance, deployment, and efficiency (time/space).
A.3. P ERFORMANCE ON K NOWLEDGE A WARENESS
In Table A2 we present the comparison results about performance on knowledge awareness.
Not surprisingly, FiD is the strongest baseline among others, as it also explicitly leverages retrieved documents to ground its generation.
Compared with KID, we find the performance of FiD is relatively limited when the NLG tasks requires longer and creative generation.
For example, ELI5, whose average reference length is around 220 tokens, and FiD tends to generate generic and repeated sequence after about 80 tokens from our observation, potentially because though FiD fuses knowledge during training, there is no scheme to guarantee the knowledge parameterized in the model can be expressed during inference.
Diverse Decoding, and PPLM show mediocre performance in these tasks because no knowledge-aware object was considered, but relatively well on longer generation tasks (e.g., ELI5), which seems to demonstrate the advantage of inference-time optimization methods (as
KID).
Little KID is not able to dynamically query knowledge when new context is generated, and thus performs not as good as KID, especially in longer generation (e.g., ELI5).
A.3. C OMPARISON OF T IME AND S PACE C ONSUMPTION
The time and space cost of running KID could be a matter of concern especially when we consider real-world applications.
In Table A3, we compare the time complexity of KID with other baselines, including vanilla beam search and sampling decoding.
We provide a breakdown for different stages: retrieving knowledge ( retrieving ), training the generative model ( training ), and the actual generation ( inference ).
Beam search and sampling decoding only have noticeable cost when there is sorting process filtering the candidate tokens (common in beam search and top- p or top- k sampling), which will often bring O ( k log k ) cost ( O ( 1 ) when pure random sampling without any sorting).
Diverse is explicitly optimized for
[Table]
Decoding, PPLM, and KID are similar as all are inference-time optimization (not necessarily need model fine-tuning, denoted as “LM FT / –”), but KID requires additional off-line knowledge trie construction (nearly the same time cost as RAG and FiD).
During inference, KID takes constant time for query (as discussed in §A.2.2), and several iterations policy gradient (by constant number of steps) to guide the generation.
We also analyze the space cost of KID and other baselines (Table A4).
The difference between KID and RAG / FiD is the external and local knowledge memory, which is relatively small (normally < 10Mb) from our observation.
Other decoding methods do not have the ability to infuse knowledge, and thus do not bring additional space cost.
[Table]
function on tuning
[Table]
[Table]
[Table]
FT / –
[Table]
O ( # docs )
+ DFS, # docs ≈ 5 LM FT / –
O ( h 2 max )
≈ O ( 1 )
A. S AMPLE G ENERATIONS
We list several generation samples of KID and RAG.
In general, the generated texts of both methods are highly readable; however, we find RAG’s generation tends to off-topic and not coherent with current on-going concepts flow when the generation is long (e [Table] g., ELI5, “ smoking inside the vehicle ”), or the context is multi-fold and complicated (e.g., multi-turn dialogue WoW, “ do some exercise ”)— these are legit continuation if we only consider immediate context.
KID is superior especially in longer generation, which seems to echo our findings that KID can mitigate exposure bias.
We show some generation samples of KID and RAG in Table A5.
A. A CTUAL Q UESTIONS WE A SK H UMAN A NNOTATORS
We asked participants about: 1) Relevance (i.e., “What’s the relevance level between the generated text and the given context?”
Answer is from 1- totally not relevant to 7- totally relevant ), 2) Factuality
[Table]
[Table]
Does marijuana impair driving ability?
[Table]
Marijuana does impair your ability to drive, but you can avoid this by not being asleep together in class together and using a napkin for balance..
One way to avoid discomfort would be smoking inside the vehicle.
That being said, smoking in public can do the same thing as smoking outside.
[Table]
Marijuana does impair your ability to drive because cannabis is a depressant drug, which means it slows reaction times and information processing.
A person who has been using cannabis is more likely to cause a vehicle collision, but may still think that they can drive safely. ROC
[Table]
Keith lived in an area that had occasional earthquakes.
But he thought keeping an first aid kit was unnecessary.
The next day, he cut his hand while cutting food.
And
[Table]