AI Engineer World's Fair 2024
Going beyond RAG: Extended Mind Transformers
Read the talk
Going Beyond RAG: Extended Mind Transformers
Extended Mind Transformers retrieve cached token representations inside attention, separating memory from the prompt and enabling retrieval traces and uncertainty-driven regeneration.
From a talk by Phoebe Klett
Before you start: Familiarity with transformer attention, token generation, and retrieval-augmented generation will help; the memory mechanism is explained without requiring its mathematical derivation.
Why distinguish memory from the prompt?
How much of a codebase does a model need to answer one question? Pretraining supplies general knowledge, but an application also needs specific, current information. Long context makes room for that information by extending the sequences a transformer can accept. Phoebe Klett points to two costs: extending a model beyond its training context can require expensive fine-tuning, and filling the prompt can introduce irrelevant information. A question about a repository usually needs only a subset of its function definitions.
Conventional retrieval-augmented generation, or RAG, selects that subset before generation. In the setup discussed here, an external retriever decides what matters once, upfront, using representations that are coarser than the token representations the transformer uses internally. The selection cannot respond to what the model discovers it needs while writing its answer.
Separating memory from the inference prompt makes retrieval available during generation. That separation enables two further capabilities: tracing which memory tokens were retrieved for an answer, and retrieving more information when the model becomes uncertain.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Retrieve memory inside attention
Extended Mind Transformers, or EMTs, modify the transformer's existing attention mechanism. Within each decoder layer, tokens already have key-value representations: keys participate in selecting information, and values carry the information attention combines. These internal representations provide the basis for memory retrieval.
The process has two phases:
- Construct memory. Pass the memory tokens through the model and save their key-value representations.
- Retrieve during generation. Let each query token use cosine similarity to select a configured number of cached memory tokens, then attend to their representations.
Retrieval therefore uses representations formed inside the model, and its selections can change as generation proceeds. In the diagram, the red-highlighted entries are the retrieved tokens.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Making retrieved tokens fit the position scheme
The difficult integration question is how to assign position information to retrieved tokens. Attention needs a way to distinguish token order. Klett attributes part of earlier approaches' need for fine-tuning to their use of absolute position embeddings: the model had to learn how to use memory tokens introduced into that positional scheme. The relative-position approaches tested for EMT allow the modified models to use retrieved representations without additional fine-tuning.
| Tested model family | Position mechanism | How position enters attention |
|---|---|---|
| Llama | Rotary position embeddings, or RoPE | Rotates pairs of embedding coordinates to encode relative position |
| MPT | ALiBi | Applies linear attention biases that penalize greater distance |
ALiBi is not a position embedding: it changes attention scores directly. The distinction matters because accommodating memory requires working with the model's particular position mechanism, even when no weight updates are needed.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Testing retrieval rather than memorization
A model can answer a factual question correctly without reading the supplied document. To distinguish retrieval from memorization, the counterfactual WikiQA benchmark pairs questions with supporting contexts containing deliberately altered facts. Supporting contexts span approximately 2,000–16,000 tokens.
The songwriting example asks who wrote These Boots Are Made for Walkin'. The original answer is Lee Hazlewood. The benchmark replaces every occurrence of his name in the supplied context with Terry Allen, a plausible but deliberately incorrect alternative. The expected benchmark answer then becomes Terry Allen. This tests whether the model prioritizes inference-time evidence over facts memorized during pretraining or fine-tuning; it does not make the substituted answer historically true.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Query-only retrieval, then retrieval with RAG
The first comparison includes models fine-tuned for longer context and a base Llama model using interpolated position embeddings. Klett describes the base model as trained on 2,048-token sequences; that is the talk's characterization, rather than a general specification for the Llama family. In the reported counterfactual retrieval comparison, the base model remains reasonably effective around 8K tokens but declines sharply at 16K.
EMT performs better than the fine-tuned comparators on shorter inputs and remains competitive through 16K without additional fine-tuning. Klett interprets the shorter-input results as evidence that long-context fine-tuning can degrade attention on shorter sequences, not as a universal finding about every long-context model.
For EMT in this first experiment, the supporting document stays in memory: the prompt contains the question rather than the document. The paper specifies one-shot prompting, so “query only” describes where the supporting evidence goes, not the absence of all other prompt scaffolding. Answering the counterfactual songwriting question requires the internal retriever to find the substituted name.
The second experiment adds RAG context to the prompt while retaining the entire supporting document in memory. The paper describes retrieving five nonoverlapping 500-token chunks using Ada embeddings. In the June 2024 counterfactual fact-retrieval experiment, EMT combined with RAG outperforms the tested GPT-4 baseline. This is a result for that benchmark and setup, not a claim of general superiority; the inspected evaluation does not identify the exact GPT-4 snapshot. The combination also shows that prompt retrieval and memory attention can complement each other.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Connect an answer token to retrieved evidence
Citations help users assess an answer, but matching an output to a supplied passage leaves a gap. If a date appears in both the prompt and the completion, that agreement supports the answer without establishing which information the model used. EMT exposes the memory tokens retrieved and attended to during generation. Klett calls these causal citations; more precisely, the paper reports retrieval provenance, including tokens most frequently retrieved across layers, rather than an intervention-based proof of causality.
The demonstration stores a Wikipedia passage about Alexander Grothendieck and asks when he received French citizenship. Its supplied answer is 1971. When the model generates that date, the display highlights retrieved tokens containing 1971 and parts of Grothendieck's name. The trace connects the generated date to specific memory content, giving the reader a more granular account of retrieval than a document-level citation alone.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Retrieve more when generation becomes uncertain
Memory access can also respond to uncertainty. The simplest signal discussed is token-level entropy over the output distribution. Other uncertainty measures can serve the same purpose. Klett mentions Bayesian fine-tuning work at Normal Computing as another way to estimate uncertainty, but it is not a requirement for this loop. When uncertainty is detected, the model can regenerate the affected step with more information from memory.
The citizenship example makes the sequence concrete:
- Start with a default retrieval budget. Each query token can retrieve a baseline number of memory entries.
- Observe an incorrect answer. Under that budget, the demonstration produces 1993 instead of its target, 1971.
- Expand retrieval and regenerate. For uncertain tokens, retrieve more cached information and regenerate a subset of the output. The revised example produces 1971.
This is an active-learning-inspired demonstration of hallucination reduction; the paper defers full-scale experiments. Efficiency gains are also conditional: avoiding a large retrieval budget everywhere must save more computation than the extra retrieval and regeneration consume.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Tune memory construction and retrieval separately
Stride length controls how memory representations are constructed. The source text must pass through a model with a fixed context length, so processing advances through it in windows. Overlapping windows give tokens preceding context when the model forms their cached key-value representations. Smaller strides improve representation quality in the described setup, but require more computation because the model processes more overlapping text.
top-k controls generation-time access: it is the number of memory key-value pairs each query token may retrieve and attend to. Klett identifies it as the most important retrieval parameter and recommends adapting it to memory length. Longer memories generally benefit from retrieving more entries. Stride determines the quality and construction cost of the stored representations; top-k determines how much of that memory a generation step can consult.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Keep irrelevant matches out of attention
Increasing retrieval indiscriminately can recreate the problem of an overloaded prompt. The implementation therefore includes similarity masking: retrieve candidate entries, then mask those whose query-key similarity falls below a threshold. Klett gives 0.25 as an illustrative threshold, not a universal setting. This permits a broad initial selection while withholding weak matches from attention. The paper did not use similarity masking in its reported retrieval experiments.
A second filter removes unknown-token entries, particularly for models using RoPE. Messy Wikipedia-derived text can contain unknown tokens whose representations match many queries without carrying useful information. Those entries are removed from the constructed memory before retrieval begins. The paper's pruning also includes beginning- and end-of-sequence special tokens. Unlike similarity masking, this changes the pool of available entries rather than filtering the results of an individual query.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Use memory as a model input
The released implementation, dataset, paper, and Hugging Face models provide the starting points for using EMT. One released model is Extended Mind Llama-2-7B Chat. These are the research implementation and interfaces presented in 2024, rather than a verified current serving recipe.
The usage pattern is to tokenize the memory, supply those tokens when instantiating the model, and set the model configuration for memory retrieval. Memories can also be changed dynamically after instantiation. This makes the memory a separately managed input rather than information that must always accompany the question in the prompt.
That separation carries through the practical benefits demonstrated here: retrieval can supply facts without additional fine-tuning, its traces can expose the memory tokens associated with an answer, and uncertainty can trigger another retrieval attempt during generation. The open-source models and code make those capabilities available together as changes to attention and memory handling.
Suggest correction
This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.
Resources
From the talk
Original research paper covering memory attention, positional handling, experiments and implementation parameters.
Official code, Llama and MPT demonstration notebooks, and memory configuration examples.
Question-answer examples with deliberately substituted facts for testing reliance on supplied documents.
Model card for a released chat model with external memory attention.
Further reading
Companion slides with benchmark comparisons, citation examples and tuning guidance.
Predecessor research on retrieving cached representations inside transformers.
Read the complete timestamped transcript
- 0:00
[upbeat music] I'm Phoebe. I'm a machine learning engineer at Normal Computing, and I'm really excited to tell you guys about some of our recent research, uh, and in particular, Extended Mind Transformers.
- 0:23
All right, so just to briefly cover what we're gonna go over in today's talk, uh, we'll introduce the problem, which I think will be quite familiar given the amazing talks which came before mine, uh, and then dive right into the method.
- 0:33
So, uh, what is the retrieval mechanism that Extended Mind Transformers implement? Uh, and then we'll dive into some experiments which give us confidence that these methods are actually performant.
- 0:42
After that, we'll get into two of my favorite and I think most compelling features that Extended Mind Transformers enable. This is a new kind of citation, uh, as well as a new kind of generation paradigm, which is active learning inspired.
- 0:54
Uh, and then we'll go over the most important parameters to tune when implementing, uh, EMTs in your applications, and generally, how to use them.
- 1:04
All right. So we pre-train language models, uh, so that they have general knowledge. But as we've been discussing all this conference, that's not enough. We need a lot of application-specific information and a topical, uh, description of the world in order to make these things useful.
- 1:20
Um, I am not going to belabor the two most popular methods, um, which try to load this description into the language model, those being long context and RAG, as I think, yeah, we've heard a lot about those, um, great methods already.
- 1:34
But I'd like to point out that they solve the problem in different ways and they suffer from different downsides. So long context seeks to extend the context window of the transformer model.
- 1:44
So we train language models, we train them on sequences of a fixed length, and then we're trying to say, "Well, can we, can we extend that so we can include more in the context, more in the prompt during inference time?"
- 1:56
Uh, fine-tuning is usually how this is done, and that's awfully expensive. Uh, and more so than that, including all of that context in your prompt can confuse the model with a lot of irrelevant information.
- 2:08
Um, and kind of beyond that, just conceptually speaking, it seems a little, like, wasteful, right? Like, if we're trying to do question answering over a big code base, uh, our query is most usually, does not need to reference, like, all of those different function definitions, but just needs some subset of them to answer the query correctly.
- 2:25
Um, okay, so this is what RAG tries to do, right? Let's try to subset that information down and just include the most relevant context in our prompt. Um, so what are the issues here?
- 2:36
Well, these, these mechanisms which are external to the transformer are kind of, like, necessarily limited by being external to the model. So we make this choice of what's relevant once and up front before the generation starts, and we're also making this choice about what's relevant using kind of the least granular representation of that data, and often ones
- 2:57
that are disjoint from the way that the model will reason about that data. Um, kind of also just conceptually, neither of these methods make a difference, uh, or make a distinction between things that should go in memory and things that should be included along with your inference query.
- 3:13
And this is more than just aesthetics. It's actually gonna enable us to... Oh.
- 3:19
It's gonna enable us to have these, like, more granular causal citations, uh, and allow the model to retrieve more information when we can tell it's uncertain, kind of actively within the generation.
- 3:32
All right, so how do we do this? Extended Mind Attention is a very simple edit to the attention mechanism of the transformer. I'm not gonna get too much into the math because we don't have a ton of time today, but would love for anyone to check out the paper and let me know what you think.
- 3:45
Um, so, but I'll just go over kind of, yeah, from a qualitative perspective how this works. So the model represents data within each decoder layer. Most of the transformers that we're using today are decoder-only transformers.
- 3:59
And within each of those decoder layers, the model will represent that data as a key-value pair. So it actually already has this retrieval mechanism built into the transformer. All we have to do is kind of hack around it.
- 4:11
Um, so we pass all of the memory tokens through the model and save off those key-value representations. And then during generation time, we allow each query token, just like RAG, using cosine similarity, to go retrieve a particular number of those memory tokens and attend to them.
- 4:29
So this, in this picture, these kind of red tokens, red highlighted tokens, are meant to, uh, represent those retrieved tokens.
- 4:37
Uh, again, this actually ends up being a very simple change to the transformer model. What's difficult, uh, was figuring out how to assign position information to those tokens. So this, uh, work is based on research from a couple years ago, but they needed to fine-tune their model in order to kind of teach the model how to leverage
- 4:56
these retrieved tokens, and that's, uh, in large part due to the absolute position embeddings that were popular during that time. So because transformer models are position agnostic, we have to figure out how to kind of tell them, like, "Okay, this token is position zero, this one is to position one," et cetera, et cetera.
- 5:13
Um, but due to today's more kind of like their softer position embeddings, this allows us to really leverage this method without any further fine-tuning. So in particular, these relative position embeddings that have become popular, and I'll talk about two different methods that we've tested and implemented this on, um, really enable the model to kind of generalize, um,
- 5:36
to these retrieved tokens. The first one, uh, that we tested on is present in all of the Llama models. These are the rotary position embeddings, and this generalizes the principle of using kind of, like, an angle between two vectors as a distance metric.
- 5:50
So we kind of take the whole embedding and we rotate kind of two positions at a time. The other one that we implemented, um, this method into is the ALiBi, uh, linear biases.
- 6:01
These actually aren't positioning embeddings at all. It just kind of linearly damps down, uh, information which is further away. And these are, uh, the way that all of the Mosaic's MPT models are trained.
- 6:16
Okay, so let's talk about some evaluations. Um, we also just open sourced a new counterfactual retrieval benchmark, and I'm just gonna briefly describe what that benchmark looks like. So this is a long context benchmark, so our input context is our query answer pairs.
- 6:32
Uh, and the context to answer those questions range from about two thousand tokens to all the way up to sixteen thousand tokens. And the... Again, these are like queries, so, like, the question might be, "Who wrote the song, 'These Shoes Are Made for Walking?'" And then the corresponding Wikipedia snippet.
- 6:47
Um, we wanted to control for facts memorized during pre-training, though, and actually any fine-tuning also. So what we did was we looked up, for instance, in this case, the answer is Lee Hazlewood.
- 6:58
We did a little bit of research. We figured out, okay, well, Terry Allen is a similar songwriter. This is a plausible answer, but it's wrong. We went in, and we replaced all the instances of Lee Hazlewood with Terry Allen, and now we ask the model to retrieve this new, you know, not factually correct, but in the sense
- 7:15
that we're trying to test whether it's prioritizing what's being provided at inference time. Um, so now we're asking it to retrieve this Terry Allen answer.
- 7:27
All right. So how do Extended Mind Transformers stack up? Here we're comparing it with fine-tuned models as well as the base Llama model with, uh, ex- interpolated position embeddings.
- 7:38
So we can see here in the green that the base model does a pretty good job extrapolating even, like, many times more. So this was a model trained up to, like, twenty forty-eight tokens, uh, during pre-training.
- 7:51
And you can see even up to eight K, it's, like, doing okay. Sixteen K, it really falls off. The position embeddings can't extrapolate that far. The fine-tune models, you can see, actually perform worse than the Extended Mind model on these shorter inputs.
- 8:05
And this is another data point that suggests that fine-tuning on super long context actually degrades the quality of attention that you get on shorter inputs. And Extended Mind Transformers continue to be competitive with those fine-tuned models all the way up to sixteen K.
- 8:18
Again, our models are not fine-tuned at all.
- 8:22
And in this particular experiment, so what the Extended Mind model sees in context is the query only. So it only sees the, like, "Who wrote the song, 'These Shoes Are Made for Walking?'" And relies heavily on that internal retrieval mechanism to go look up that new information.
- 8:39
In this second experiment, we seed it with a little bit more information in context, uh, using RAG. But again, mostly relying on that, uh, internal mechanism still. Uh, and you can see we're outperforming GPT-4 here now when we combine it with that more information in context as well.
- 8:58
Okay, now we're gonna talk about citations. So I think, uh, this will be a topic that lots of you here can empathize with. Uh, as AI engineers, I think this is one of the most important things to provide in an application, such that people can learn to trust the model outputs.
- 9:13
In fact, you might actually use RAG just to get citations. Um, so with RAG, though, the citations that you get are a little bit kind of like post-hoc rationalization.
- 9:23
So maybe if, like, the date appears in the output, and we knew it was also in the input to the language model, we feel pretty confident that that date is not hallucinated.
- 9:31
Um, but again, this is not really, like, a causally related to what information the model used during the generation. Now, with Extended Mind Transformers, we can look up exactly which tokens were retrieved from tho- from those memories and used during generation.
- 9:46
So in this example, on the top left here, we have the memories. This is a snippet from Wikipedia about one of my favorite mathematicians, Alexander Grothendieck. And the query is, "When did he get his French citizenship?"
- 9:58
And then, in the bottom, you can see the completion with the correct date. I think he got it in nineteen seventy-one. So the blue highlighted tokens here, uh, importantly the nineteen seventy-one, as well as some of the Alexander Grothendieck tokens, uh, those are the ones that the model retrieved and attended to when generating that nineteen seventy-one correct
- 10:17
token. And so being able to report that, uh, gives a lot of confidence and also just insight into how the model is using those retrieved tokens.
- 10:27
Okay. We can also use Extended Mind Transformers to reduce hallucinations. So how do we do this? So right now we have access to, in the, like, simplest case, just kind of token level entropy over that output distribution.
- 10:41
And if you wanted to get fancier, we're also doing some Bayesian fine-tuning of language models at Normal. But you can use any uncertainty metric to determine kind of how certain the model is about a generated token.
- 10:52
And if we kind of can detect that the model is uncertain about that token, we can regenerate that step using more information from these memories. Uh, so okay, so in the top right here, we can see, uh, this is...
- 11:04
We just set, like, a baseline default number of memories that each query token is allowed to retrieve and attend to. And you can see it wasn't quite enough information, uh, to get this query right.
- 11:14
So if you remember from the previous slide, the correct answer here is nineteen seventy-one. And you can see we've got nineteen ninety-three here. So wasn't enough. [laughs] We didn't attend to that memory quite enough to get this question right.
- 11:26
And in the bottom example, we allow it to regenerate some subset of those tokens using more information from the cache when we can tell the model is uncertain.
- 11:37
And again, got this right. So it's kind of like kind of a nice intuition for, uh, when the model's uncertain, and then, okay, if it's really uncertain, let's go use more information and also can be more efficient, kind of depending on how the math works out.
- 11:53
All right, so now I'm gonna tell you guys about the most important, uh, parameters to set when using Extended Mind Transformers. So you may have heard of something called stride length before
- 12:02
Uh, and this is, um, a parameter that comes up a lot, even just kind of in regular perplexity computations. So when we compute the memories that we're going to attend to, we pass them through the model and then again save off these key value representations that the model saves internally.
- 12:18
Um, but again, the models that we're using are trained on this fixed context length. So we need to kind of pass over them with some stride such that each of those tokens has an appropriate amount of context, um, to generate the representation.
- 12:34
So if the stride is smaller, uh, you're gonna get more, uh, high-quality representations, but also it will require more computations. Um, so you can kind of tune this, and there are some graphs in the paper as well that kind of d- represent this trade-off.
- 12:48
Um, but this is an important parameter to set when, yeah, generating the memories themselves. Top K is, uh, probably the most important parameter to think about. So this is the number of key value pairs or memories that each query token is allowed to retrieve and attend to.
- 13:04
Um, when your memory is quite long, kind of the more the better. Um, but again, uh, yeah, this is kind of, should be dynamically set based on how long your memory is.
- 13:15
Um, okay, yeah. So lastly, uh, we wanna retrieve as much information as we can from the memory without confusing the model. So making analogy back to kind of putting everything into context, we don't wanna just throw everything in there 'cause that will be confusing to the model.
- 13:31
Um, so we have two different regularization techniques that we implement that we have found to be especially effective. Um, the first one is called similarity masking. So again, we, we retrieve these tokens, uh, based on similarity with our query token and the key that we are retrieving from.
- 13:49
And so we might say like, "Well, if we don't hit some similarity threshold, like we'll retrieve a lot of them, but then if they, you know, if they're not at least like .25 similar, then we'll just throw them out."
- 13:58
So we can retrieve and then just mask the ones that end up being less important. Uh, another, [laughs]
- 14:04
another important regularization technique, in particular for models that are trained using RoPE, uh, is to eliminate tokens from the memory that correspond to unknown tokens. So especially if your data is super messy, a lot of the Wikipedia-based benchmarks are like really way more messy than I even knew before I started working on this stuff.
- 14:22
Uh, they have a lot of like, just unknown tokens, and so they're kind of like poorly represented by the models often because they're unknown. They end up having a lot of matches with your query tokens, but then they're n- not actually containing a lot of useful information.
- 14:35
Um, so we just eliminate those from the memory before we allow it to start retrieving.
- 14:42
All right, so we have a whole collection of these models on Hugging Face. All of the, uh, code is on GitHub as well as that dataset. Um, and encourage you all to read the paper if you're curious about more of the technical details.
- 14:53
Uh, as I hope you can see here, it's actually pretty easy to use these things. So it's as simple as passing those memories in as inputs, uh, as tokens into the model during instantiation.
- 15:04
Um, you can dynamically change them after that as well, but it's the easiest way to do it. Uh, and then making sure your config is set up correctly.
- 15:13
All right, so just to conclude here, uh, I hope you all will take away that these new kinds of models, um, impre- in- achieve impressive performance on retrieval tasks.
- 15:22
They enable these great new kind of citations. Um, they also enable this new kind of hallucination reduction technique, which is inspired by active learning. They do not require fine-tuning unlike kind of long context methods, uh, and they can be easily run using our open source models and code.
- 15:41
Thanks so much and, uh, find me after for questions. [audience applauding] [upbeat music]