M ASS -E DITING M EMORY IN A T RANSFORMER
Anonymous authors
Paper under double-blind review
A BSTRACT
Recent work has shown exciting promise in updating large language models with new memories, so as to replace obsolete information or add specialized knowledge.
However, this line of work is predominantly limited to updating single associations.
We develop MEMIT, a method for directly updating a language model with many memories, demonstrating experimentally that it can scale up to thousands of associations for GPT-J (6B) and GPT-NeoX (20B), exceeding prior work by orders of magnitude.
Our code and data will be open-sourced upon publication.
I NTRODUCTION
How many memories can we add to a deep network by directly editing its weights?
Although large autoregressive language models (Radford et al., 2019; Brown et al., 2020; Wang &
Komatsuzaki, 2021; Black et al., 2022) are capable of recalling an impressive array of common facts such as “Tim Cook is the CEO of Apple” or “Polaris is in the constellation Ursa Minor” (Petroni et al., 2020; Brown et al., 2020), even very large models are known to lack more specialized knowledge, and they may recall obsolete information if not updated periodically (Lazaridou et al., 2021; Agarwal & Nenkova, 2022; Liska et al., 2022).
The ability to maintain fresh and customizable information is desirable in many application domains, such as question answering, knowledge search, and content generation.
For example, we might want to keep search models updated with major breaking news and recently-generated user feedback.
In other situations, authors or companies may wish to customize models with specific knowledge about their creative work or commercial products.
Because retraining a large model can be prohibitive (e.g., training GPT-3 used an estimated 1200MWh of electricity (Patterson et al., 2021)), we seek methods that can update knowledge directly.
To that end, several knowledge-editing methods have been proposed to insert new memories directly into specific model parameters.
The approaches include constrained fine-tuning (Zhu et al., 2020), hypernetwork knowledge editing (De Cao et al., 2021;
Hase et al., 2021; Mitchell et al., 2021; 2022), and rank-one model editing (Meng et al., 2022).
However, this body of work is typically limited to updating at most a few dozen facts; a recent study evaluates on a maximum of 75 (Mitchell et al., 2022) whereas others primarily focus on single-edit cases.
In practical settings, we may wish to
[Figure] [Figure]
update a model with hundreds or thousands of facts simultaneously, but a naive sequential application of current state-of-the-art knowledge-editing methods fails to scale up (Section 5.2).
We propose MEMIT, a scalable multi-layer update algorithm that uses explicitly calculated parameter updates to insert new memories.
Inspired by the ROME direct editing method (Meng et al., 2022),
MEMIT targets the weights of transformer modules that we determine to be causal mediators of factual knowledge recall.
Experiments on GPT-J (6B parameters; Wang & Komatsuzaki 2021) and GPT-NeoX (20B; Black et al.
2022) demonstrate that MEMIT can scale and successfully store thousands of memories in bulk .
We analyze model behavior when inserting true facts, counterfactuals, 27 specific relations, and different mixed sets of memories.
In each setting, we measure robustness in terms of generalization, specificity, and fluency while comparing the scaling of
MEMIT to rank-one, hypernetwork, and fine-tuning baselines.
R ELATED W ORK
Scalable knowledge bases.
The representation of world knowledge is a core problem in artificial intelligence (Richens, 1956; Minsky, 1974), classically tackled by constructing knowledge bases of real-world concepts.
Pioneering hand-curated efforts (Lenat, 1995; Miller, 1995) have been followed by web-powered knowledge graphs (Auer et al., 2007;
Bollacker et al., 2007;
Suchanek et al., 2007;
Havasi et al., 2007; Carlson et al., 2010; Dong et al., 2014; Vrandeˇci´c & Krötzsch, 2014; Bosselut et al., 2019) that extract knowledge from large-scale sources.
Structured knowledge bases can be precisely queried, measured, and updated (Davis et al., 1993), but they are limited by sparse coverage of uncatalogued knowledge, such as commonsense facts (Weikum, 2021).
Language models as knowledge bases.
Since LLMs can answer natural-language queries about real-world facts, it has been proposed that they could be used directly as knowledge bases (Petroni et al., 2019; Roberts et al., 2020; Jiang et al., 2020; Shin et al., 2020).
However, LLM knowledge is only implicit; responses are sensitive to specific phrasings of the prompt (Elazar et al., 2021;
Petroni et al., 2020), and it remains difficult to catalog, add, or update knowledge (AlKhamissi et al., 2022).
Nevertheless, LLMs are promising because they scale well and are unconstrained by a fixed schema (Safavi & Koutra, 2021).
In this paper, we take on the update problem, asking how the implicit knowledge encoded within model parameters can be mass-edited.
Hypernetwork knowledge editors.
Several meta-learning methods have been proposed to edit knowledge in a model.
Sinitsin et al. (2019) proposes a training objective to produce models amenable to editing by gradient descent. De Cao et al. (2021) proposes a Knowledge Editor (KE) hypernetwork that edits a standard model by predicting updates conditioned on new factual statements.
In a study of KE, Hase et al.
(2021) find that it fails to scale beyond a few edits, and they scale an improved objective to 10 beliefs.
MEND (Mitchell et al., 2021) also adopts meta-learning, inferring weight updates from the gradient of the inserted fact.
To scale their method, Mitchell et al.
(2022) proposes
SERAC, a system that routes rewritten facts through a different set of parameters while keeping the original weights unmodified; they demonstrate scaling up to 75 edits.
Rather than meta-learning, our method employs direct parameter updates based on an explicitly computed mapping.
Direct model editing.
Our work most directly builds upon efforts to localize and understand the internal mechanisms within LLMs (Elhage et al., 2021; Dar et al., 2022).
Based on observations from
Geva et al.
(2021; 2022) that transformer MLP layers serve as key–value memories, we narrow our focus to them.
We then employ causal mediation analysis (Pearl, 2001; Vig et al., 2020;
Meng et al., 2022), which implicates a specific range of layers in recalling factual knowledge.
Previously, Dai et al.
and Yao et al.
(2022) have proposed editing methods that alter sparse sets of neurons, but we adopt the classical view of a linear layer as an associative memory (Anderson, 1972; Kohonen, 1972).
Our method is closely related to Meng et al.
(2022), which also updates GPT as an explicit associative memory.
Unlike the single-edit approach taken in that work, we modify a sequence of layers and develop a way for thousands of modifications to be performed simultaneously.
P RELIMINARIES : L ANGUAGE M ODELING AND M EMORY E DITING
The goal of MEMIT is to modify factual associations stored in the parameters of an autoregressive
LLM.
Such models generate text by iteratively sampling from a conditional token distribution
P [
[Equation]
t |
[Equation] [Equation]
. , x E ] parameterized by a D -layer deep transformer decoder, G (Vaswani et al., 2017):
[Equation]
where h DE is the transformer’s hidden state representation at the final layer D and ending token E .
This state is computed using the following recursive relation:
[Equation]
a l =
[Equation]
h 0 t ( x ) is the embedding of token x t , and γ is layernorm.
Note that we have written attention and
MLPs in parallel as done in Black et al.
and Wang & Komatsuzaki (2021).
Large language models have been observed to contain many memorized facts (Petroni et al., 2020;
Brown et al., 2020; Jiang et al., 2020; Chowdhery et al., 2022).
In this paper, we study facts of the form (subject s , relation r , object o ), e.g., ( s = Michael Jordan, r = plays sport, o = basketball).
A generator G can recall a memory for ( s i , r i , ∗ ) if we form a natural language prompt p i
= p ( s i , r i ) such as “Michael Jordan plays the sport of” and predict the next token(s) representing o i .
Our goal is to edit many memories at once.
We formally define a list of edit requests as:
[Equation]
∄ i, j. ( s i = s j ) ∧
( r i = r j ) ∧
( o i ̸
= o j ) .
The logical constraint ensures that there are no conflicting requests.
For example, we can edit Michael
Jordan to play o i = “baseball”, but then we exclude associating him with professional soccer.
What does it mean to edit a memory well?
At a superficial level, a memory can be considered edited after the model assigns a higher probability to the statement “Michael Jordan plays the sport of baseball” than to the original prediction (basketball); we say that such an update is effective .
Yet it is important to also view the question in terms of generalization , specificity , and fluency :
• To test for generalization , we can rephrase the question: “What is Michael Jordan’s sport?
What sport does he play professionally?”
If the modification of G is superficial and overfitted to the specific memorized prompt, such predictions will fail to recall the edited memory, “baseball.”
• Conversely, to test for specificity , we can ask about similar subjects for which memories should not change: “What sport does Kobe Bryant play?
What does Magic Johnson play?”
These tests will fail if the updated G indiscriminately regurgitates “baseball” for subjects that were not edited.
• When making changes to a model, we must also monitor fluency .
If the updated model generates disfluent text such as “baseball baseball baseball baseball,” we should count that as a failure.
Achieving these goals is challenging, even for a few edits (Hase et al., 2021; Mitchell et al., 2022;
Meng et al., 2022).
We investigate whether they can be attained at the scale of thousands of edits.
M ETHOD
MEMIT inserts memories by updating transformer mechanisms that have recently been elucidated using causal mediation analysis (Meng et al., 2022).
In GPT-2 XL, it was found that there exists a sequence of critical MLP layers R that mediate factual association recall at the last subject token S (Figure 2).
MEMIT operates by (i) calculating the vector associations we want the critical layers to remember, then (ii) storing a portion of the desired memories in each layer l ∈ R by applying an update to the parameters.
Throughout this paper, our focus will be on states representing the last subject token S of prompt p
i , so we shall abbreviate h l i =
h l S ( p i ) .
Similarly, m l i and a l i abbreviate m l S ( p i ) and a l S ( p i ) .
4. I DENTIFYING THE CRITICAL PATH OF MLP LAYERS
Figure 3 shows the results of applying causal tracing to the larger GPT-J (6B) model; for implementation details, see Appendix A. We measure the average indirect causal effect of each h li on a sample of memory prompts p i , with either the Attention or MLP modules for token S disabled.
The results
[Figure]
# 𝑊
[Figure] [Figure]
[Figure] [Figure]
[Figure]
confirm that GPT-J has a concentration of mediating states h li ; moreover, they highlight a mediating causal role for a range of MLP modules, which can be seen as a large gap between the effect of single states (purple bars in Figure 3) and the effects with MLP severed (green bars); this gap diminishes after layer 8.
Unlike Meng et al.
(2022) who use this test to identify a single edit layer, we select the whole range of critical MLP layers l ∈ R .
For GPT-J, we have R = { 3 , 4 , 5 , 6 , 7 , 8 } .
[Figure]
Given that a range of MLPs play a joint mediating role in recalling facts, we ask: what is the role of one MLP in storing a memory?
Each token state in a transformer is part of the residual stream that all attention and MLP modules read from and write to (Elhage et al., 2021).
Unrolling Eqn. 2:
[Equation]
Eqn.
6 highlights that each individual
MLP contributes by adding to the memory at h Li (Figure 2b), which is later read by last-token attention modules (Figure 2c).
Therefore, when writing new memories into G , we can spread the desired changes across all the critical layers m li for l ∈ R .
4. B ATCH UPDATE FOR A SINGLE LINEAR ASSOCIATIVE MEMORY
In each individual layer l , we wish to store a large batch of u ≫ 1 memories.
This section derives an optimal single-layer update that minimizes the squared error of memorized associations, assuming that the layer contains previously-stored memories that should be preserved.
We denote W 0 ≜ W lout (Eqn. 4, Figure 2) and analyze it as a linear associative memory (Kohonen, 1972; Anderson, 1972) that associates a set of input keys k i ≜ k li (encoding subjects) to corresponding memory values m i ≜ m li (encoding memorized properties) with minimal squared error:
[Equation] [Equation]
If we stack keys and memories as matrices K 0 =
[ k 1 | k 2 | · · · | k n ] and M 0 =
[ m 1 | m 2 | · · · | m n ] , then Eqn.
7 can be optimized by solving the normal equation (Strang, 1993, Chapter 4):
[Equation]
Suppose that pre-training sets a transformer MLP’s weights to the optimal solution W 0 as defined in
Eqn. 8.
Our goal is to update W 0 with some small change ∆ that produces a new matrix W 1 with
[Figure]
a set of additional associations.
Unlike Meng et al.
(2022), we cannot solve our problem with a constraint that adds only a single new association, so we define an expanded objective:
[Equation]
We can solve Eqn. 9 by again applying the normal equation, now written in block form:
[Equation]
which expands to: ( W
[Equation]
∆
[Equation]
subtracting Eqn. 8 from Eqn.
12 : ∆
[Equation]
A succinct solution can be written by defining two additional quantities: C 0 ≜ K 0 K T 0 , a constant proportional to the uncentered covariance of the pre-existing keys, and R ≜ M 1 − W 0 K 1 , the residual error of the new associations when evaluated on old weights W 0 .
Then Eqn.
13 can be simplified as:
[Equation]
Since pretraining is opaque, we do not have access to K 0 or M 0 .
Fortunately, computing Eqn.only requires an aggregate statistic C 0 over the previously stored keys.
We assume that the set of previously memorized keys can be modeled as a random sample of inputs, so that we can compute
[Equation] [Equation]
by estimating E k (cid:2) kk T (cid:3) , an uncentered covariance statistic collected using an empirical sample of vector inputs to the layer.
We must also select λ , a hyperparameter that balances the weighting of new v.s. old associations; a typical value is λ = 1 . 5 × 10 4 .
4. U PDATING MULTIPLE LAYERS
We now define the overall update algorithm (Figure 4).
Inspired by the observation that robustness is improved when parameter change magnitudes are minimized (Zhu et al., 2020), we spread updates evenly over the range of mediating layers R .
We define a target layer L ≜ max( R ) at the end of the mediating layers, at which the new memories should be fully represented.
Then, for each edit ( s i , r i , o i )
∈
E , we (i) compute a hidden vector z
i to replace h Li such that adding δ i ≜
z i − h Li to the hidden state at layer L and token T will completely convey the new memory.
Finally, one layer at a time, we (ii) modify the MLP at layer l , so that it contributes an approximately-equal portion of the change δ i for each memory i .
(i)
Computing z i .
For the i th memory, we first compute a vector z i that would encode the association ( s i , r i , o i ) if it were to replace h Li at layer L at token S .
We find z i
= h
Li
+ δ i by optimizing the residual vector
δ i using gradient descent:
[Equation]
In words, we optimize δ i to maximize the model’s prediction of the desired object o i , given a set of factual prompts { x j ⊕ p ( s i , r i ) } that concatenate random prefixes x j to a templated prompt to aid generalization across contexts.
G ( h Li += δ i ) indicates that we modify the transformer execution by substituting the modified hidden state
z i for h Li ; this is called “hooking” in popular ML libraries.
(ii) Spreading z i − h Li over layers .
We seek delta matrices ∆ l such that:
[Equation] [Equation]
where ˆ h Li
=
h
i +
L (cid:88) l = a li +
L (cid:88)
[Equation]
Because edits to any layer will influence all following layers’ activations, we calculate ∆ l iteratively in ascending layer order (Figure 4ii-a,b,c).
To compute each individual ∆ l , we need the corresponding keys K l =
[ k l 1 | · · · | k ln ]
and memories M l = [ m l 1 | · · · | m ln ] to insert using Eqn. 14.
Each key k li is computed as the input to W lout at each layer l
(Figure 2d):
[Equation] [Equation]
m li is then computed as the sum of its current value and a fraction of the remaining top-level residual: m li
=
W out k li + r li where r li is the residual given by z i − h
Li L − l + 1 , (20) where the denominator of r i spreads the residual out evenly.
Algorithm 1 summarizes MEMIT, and additional implementation details are offered in Appendix B.
Algorithm 1: The MEMIT Algorithm
Data: Requested edits E =
( s i ,r i ,o i ) } , generator G , layers to edit S , covariances C l Result:
Modified generator containing edits from E 1 for s i ,r i ,o i ∈ E do //
Compute target z i vectors for every memory i hook G ( h Li += δ i ) optimize argmin δ i 1 P (cid:80)
Pj =1 − log P G ( h Li += δ i )
[ o i | x j ⊕ p ( s i ,r i )]
(Eqn. 16)
z i ← h Li
+ δ i 5 end 6 for l ∈ R do //
Perform update: spread changes over layers h li ← h l − 1 i + a li + m li
(Eqn. 2) //
Run layer l with updated weights for s i ,r i ,o i ∈
E do k li ← k li = 1 P (cid:80)
Pj =1 k ( x j + s i ) (Eqn. 19)
r li ← z
i − h Li L − l +
(Eqn. 20) //
Distribute residual over remaining layers end
K l ← [ k l 1 i ,...,k L i ]
R l ← [ r l 1 i ,...,r Li ] ∆ l ← R l K lT ( C l + K l K lT ) − 1 (Eqn. 14)
W l ← W l + ∆ l // Update layer l MLP weights in model
16 end
E XPERIMENTS 5. M ODELS AND BASELINES
We run experiments on two autoregressive LLMs: GPT-J (6B) and GPT-NeoX (20B).
For baselines, we first compare with a naive fine-tuning approach that uses weight decay to prevent forgetfulness ( FT-W ).
Next, we experiment with MEND , a hypernetwork-based model editing approach that edits multiple facts at the same time (Mitchell et al., 2021).
Finally, we run a sequential version of ROME (Meng et al., 2022): a direct model editing method that iteratively updates one fact at a time.
The recent SERAC model editor (Mitchell et al., 2022) does not yet have public code, so we cannot compare with it at this time.
See Appendix B for implementation details.
[Table] [Table]
We first test MEMIT on zsRE (Levy et al., 2017), a question-answering task from which we extract 10, real-world facts; zsRE tests MEMIT’s ability to add correct information.
Because zsRE does not contain generation tasks, we evaluate solely on prediction-based metrics.
Efficacy measures the proportion of cases where o is the argmax generation given p ( s, r ) , Paraphrase is the same metric but applied on paraphrases, Specificity is the model’s argmax accuracy on a randomly-sampled unrelated fact that should not have changed, and Score is the harmonic mean of the three aforementioned scores; Appendix C contains formal definitions.
As Table 1 shows, MEMIT performs best at 10,000 edits; most memories are recalled with generalization and minimal bleedover.
Interestingly, simple fine-tuning FT-W performs better than the baseline knowledge editing methods
MEND and ROME at this scale, likely because its objective is applied only once.
5.2. C OUNTER F ACT SCALING CURVES
Next
[Table]
we test MEMIT’s ability to add counterfactual information using C OUNTER F ACT , a collection of 21,919 factual statements (Meng et al.
(2022), Appendix C).
We first filter conflicts by removing facts that violate the logical condition in Eqn.
5 (i.e., multiple edits modify the same ( s, r ) prefix to different objects).
For each problem size n ∈ { 1 , 2 , 3 , 6 , 10 , 18 , 32 , 56 , 100 , 178 , 316 , 562 , 1000 , 1778 , 3162 , 5623 , 10000 } 1 , n counterfactuals are inserted.
Following Meng et al.
, we report several metrics designed to test editing desiderata.
Efficacy Success ( ES ) evaluates editing success and is the proportion of cases for which the new object o i ’s
probability is greater than the probability of the true real-world object o ci : 2 E i [ P G [ o i | p ( s i , r i )]
> P G [ o ci | p
( s i , r i )]] .
Paraphrase Success ( PS ) is a generalization measure defined similarly, except G is prompted with rephrasings of the original statement.
For testing specificity, Neighborhood Success ( NS ) is defined similarly, but we check the probability G assigns to the correct answer o ci (instead of o i ), given prompts about distinct but semantically-related subjects (instead of s i ).
Editing Score ( S ) aggregates metrics by taking the harmonic mean of ES, PS, NS.
We are also interested in measuring generation quality of the updated model.
First, we check that G
’s
generations are semantically consistent with the new object using a Reference Score ( RS ), which is collected by generating text about s and checking its TF-IDF similarity with a reference Wikipedia text about o .
To test for fluency degradation due to excessive repetition, we measure Generation
Entropy ( GE ), computed as the weighted sum of the entropy of bi- and tri-gram n -gram distributions of the generated text.
See Appendix C for further details on metrics.
Figure 5 plots performance v.s. number of edits on log scale, up to 10,000 facts.
ROME performs well up to n = 10 but degrades starting at n = 32 .
Similarly, MEND performs well at n = 1 but rapidly declines at n = 6 , losing all efficacy before n = 1 , 000 and, curiously, having negligible effect on the model at n = 10 , 000 (the high specificity score is achieved by leaving the model nearly unchanged).
MEMIT performs best at large n .
At small n , ROME achieves better generalization at the cost of slightly lower specificity, which means that ROME’s edits are more robust under rephrasings, likely due to that method’s hard equality constraint for weight updates, compared to MEMIT’s soft error minimization.
Table 2 provides a direct numerical comparison at 10,000 edits on both GPT-J and
GPT-NeoX. FT-W 3 does well on probability-based metrics but suffers from complete generation failure, indicating significant model damage.
Appendix B provides a runtime analysis of all four methods on 10 , 000 edits.
We find that MEND is fastest, taking 98 sec .
FT is second at around 29 min , while MEMIT and ROME are the slowest at
[Table]
29 hr , respectively.
While MEMIT’s execution time is high relative to MEND and FT, we note that its current implementation is naive and does not batch the independent z i optimizations, instead computing each one in series.
These computations are actually “embarrassingly parallel” and thus could be batched.
5. E DITING DIFFERENT CATEGORIES OF FACTS
For insight into MEMIT’s performance on different types of facts, we pick the 27 categories from
C OUNTER F ACT that have at least 300 cases each, and assess each algorithm’s performance on those cases.
Figure 6a shows that MEMIT achieves better overall scores compared to FT and MEND in all categories.
It also reveals that some relations are harder to edit compared to others; for example, each of the editing algorithms faced difficulties in changing the sport an athlete plays.
Even on harder cases, MEMIT outperforms other methods by a clear margin.
Model editing methods are known to occasionally suffer from a trade-off between attaining high generalization and good specificity.
This trade-off is clearly visible for MEND in Figure 6b.
FT consistently fails to achieve good specificity.
Overall, MEMIT achieves a higher score in both dimensions, although it also exhibits a trade-off in editing some relations such as P127 (“product owned by company”) and P641 (“
athlete plays sport”).
[Figure] [Figure]
5. E DITING DIFFERENT CATEGORIES OF FACTS TOGETHER
To investigate whether the scaling of MEMIT is sensitive to differences in the diversity of the memories being edited together, we sample sets of cases E mix that mix two different relations from the C OUNTER F ACT dataset.
We consider four scenarios depicted in Figure 7, where the relations have similar or different classes of subjects or objects.
In all of the four cases, MEMIT’s performance on E mix is close to the average of the performance of each relation without mixing.
This provides support to the hypothesis that the scaling of MEMIT is neither positively nor negatively affected by the diversity of the memories being edited.
Appendix D contains implementation details.
D ISCUSSION AND C ONCLUSION
We have developed MEMIT, a method for editing factual memories in large language models by directly manipulating specific layer parameters.
Our method scales to much larger sets of edits (100x) than other approaches while maintaining excellent specificity, generalization, and fluency.
Our investigation also reveals some challenges: certain relations are more difficult to edit with robust specificity, yet even on challenging cases we find that MEMIT outperforms other methods by a clear margin.
The knowledge representation we study is also limited in scope to working with directional ( s, r, o ) relations: it does not cover spatial or temporal reasoning, mathematical knowledge, linguistic knowledge, procedural knowledge, or even symmetric relations.
For example, the association that “Tim Cook is CEO of Apple” must be processed separately from the opposite association that “
The
CEO of Apple is Tim Cook.”
Despite these limitations, it is noteworthy that large-scale model updates can be constructed using an explicit analysis of internal computations.
Our results raise a question: might interpretability-based methods become a commonplace alternative to traditional opaque fine-tuning approaches?
Our positive experience brings us optimism that further improvements to our understanding of network internals will lead to more transparent and practical ways to edit, control, and audit models.
E THICAL CONSIDERATIONS
Although we test a language model’s ability to serve as a knowledge base, we do not find these models to be a reliable source of knowledge, and we caution readers that a LLM should not be used as an authoritative source of facts.
Our memory-editing methods shed light on the internal mechanisms of models and potentially reduce the cost and energy needed to fix errors in a model, but the same methods might also enable a malicious actor to insert false or damaging information into a model that was not originally present in the training data.
R EPRODUCIBILITY
The code and data for our methods and experiments are available in supplemental materials.
All experiments are run on workstations with NVIDIA A6000 GPUs.
The language models are loaded using HuggingFace Transformers (Wolf et al., 2019), and PyTorch (Paszke et al., 2019) is used for executing the model editing algorithms on GPUs.
GPT-J experiments fit into one 48GB A6000, but GPT-NeoX runs require at least two: one 48GB
GPU for running the model in float16 , and another slightly smaller GPU for executing the editing method.
Due to the size of these language models, our experiments will not run on GPUs with less memory.
B I MPLEMENTATION D ETAILS B. F INE -T UNING WITH W EIGHT D ECAY
Our fine-tuning baseline updates layer 21 of GPT-J, which Meng et al.
(2022) found to provide the best performance in the single-edit case.
Rather than using a hard L ∞ -norm constraint, we use a soft weight decay regularizer.
However, the optimal amount of regularization depends strongly on the number of edits (more edits require higher-norm edits), so we tune this hyperparameter for the n = 10 , 000 case.
Figure 9 shows that 5 × 10 − 4 selects for the optimal tradeoff between generalization and specificity.
FT-W optimization proceeds for a maximum of 25 steps with a learning rate of 5 ×
10 − 4 .
To prevent overfitting, early stopping is performed when the loss reaches 10 − 2 .
Regarding runtime, FT takes 1 , 716 .
21 sec ≈ 0 .
48 hr to execute 10 , 000 edits on GPT-J.
Note that we choose not to complicate the analysis by tuning FT-W on more than one layer.
Table 2 demonstrates that FT-W, with just one layer, already gets near-perfect efficacy at the cost of low specificity, which indicates sufficient edit capacity.
B. M ODEL E DITING N ETWORKS WITH G RADIENT D ECOMPOSITION (MEND)
MEND makes concurrent edits by accumulating gradients from all edit examples, then passing them through the hypernetwork together.
We use the GPT-J MEND hypernetwork trained by Meng et al.
During inference, learning rate scale is set to the default value of 1.0.
MEND is by far the fastest method, taking 98 .
25 seconds to execute 10 , 000 updates on GPT-J.
B. R ANK -O NE M ODEL E DITING (ROME)
The default ROME hyperparameters are available in their open source code: GPT-J updates are executed at layer 5, where optimization proceeds for 20 steps with a weight decay of 0.5, KL factor of 0.0625, and learning rate of 5 × 10 − 1 .
ROME uses prefix sampling, resulting in 10 prefixes of length 5 and 10 prefixes of length 10.
Covariance statistics are collected in fp32 on Wikitext using a sample size of 100,000.
See Meng et al.
for more details.
ROME takes 44 , 248 .
26 sec ≈ 12 .
29 hr for 10 , 000 edits on GPT-J, which works out to approximately 4 seconds per edit.
B. M ASS -E DITING M EMORY IN A T RANSFORMER (MEMIT)
On GPT-J, we choose R = { 3 , 4 , 5 , 6 , 7 , 8 } and set λ , the covariance adjustment factor, to 15 , 000 .
Similar to ROME, covariance statistics are collected using 100,000 samples of Wikitext in fp32 .
δ
i optimization
proceeds for 25 steps with a learning rate of 5 × 10 − 1 .
In practice, we clamp the
L 2 norm of δ i such that it is less than 3 4 of the original hidden state norm, ∥ h L i ∥ .
On GPT-NeoX, we select R = { 6 , 7 , 8 , 9 , 10 } and set λ = 20 , 000 .
Covariance statistics are collected over 50, samples of Wikitext in fp16 but stored in fp32 .
Optimization for δ i proceeds for 20 steps using a learning rate of 5 × 10 − 1 while clamping ∥ h Li ∥ to 310 ∥ h Li ∥ .
In MEMIT, we have the luxury of being able to pre-compute and cache z i values, since they are inserted in parallel.
If all such vectors are already computed, MEMIT takes 3 , 226 .
35 sec ≈ 0 .
90 hr for 10 , 000 updates on GPT-J, where the most computationally expensive step is inverting a large square matrix (Eqn. 14).
Computing each z i vector is slightly less expensive than computing a ROME update; to get all 10,000 z i vectors, we need 23 , 546 .
65 sec ≈ 6 .
54 hr .
This optimization is currently done in series, but it is actually “embarrassingly parallel,” as we can greatly reduce computation time by batching the gradient descent steps.
Note that this speed-up does not apply to ROME, since each update must be done iteratively.
C E VALUATION M ETRICS C. F OR ZS RE
For consistency with previous works that use the zsRE task (Mitchell et al., 2021; Meng et al., 2022), we report the same three probability tests:
• Efficacy is the proportion of edits that G recalls with top-1 accuracy.
Note that the prompt matches exactly what the edit method sees at runtime:
[Equation]
• Paraphrase is the accuracy on rephrasings of the original statement:
[Equation]
• Specificity is the proportion of neighborhood prompts that the model gets correct.
In C OUNTERF ACT , all such prompts have the same correct answer o ci :
[Equation]
We also report an aggregated Score : the harmonic mean of Efficacy, Paraphrase, and Specificity.
C. F OR C OUNTER F ACT
C OUNTER F ACT contains an assortment of prompts and texts for evaluating model rewrites (Figure 14).
This section provides formal definitions for each C OUNTER F ACT metric.
First, the probability tests:
• Efficacy Success ( ES ) is the proportion of cases where o i exceeds o ci in probability.
Note that the prompt matches exactly what the edit method sees at runtime
[Equation]
• Paraphrase Success ( PS ) is the proportion of cases where o i exceeds o ci in probability on rephrasings of the original statement:
[Equation]
• Neighborhood Success ( NS ) is the proportion of neighborhood prompts where the models assigns higher probability to the correct fact:
[Equation]
• Editing Score ( S ), is the harmonic mean of ES, PS, and NS.
Now, the generation tests:
• Reference Score ( RS ) measures the consistency of G ’s free-form generations.
To compute it, we first prompt G with the subject s , then compute TF-IDF vectors for both G ( s ) and a reference Wikipedia text about o ; RS is defined as their cosine similarity.
Intuitively, G ( s ) will match better with o ’s reference text if it has more consistent phrasing and vocabulary.
• We also check for excessive repetition (a common failure case with model editing) using Generation Entropy ( GE ), which relies on the entropy of n -gram distributions:
[Equation]
Here
f n ( ·
) is the
n -
gram
frequency
distribution.
D E DITING D IFFERENT C ATEGORIES OF F ACTS T OGETHER
For an edit ( s, r, o ) , r associates a subject s and object o .
Both s and o have their associated types τ ( s ) and τ ( o ) .
For example, r = “is a citizen of” is an association between a Person and Country .
We say that τ ( s 1 ) and s 2 are diverse if τ ( s 1 ) ̸
= ( τ ( s 2 )) , and similar otherwise.
The definition follows similarly for objects.
For any relation pair ( r 1 , r 2 ) , we sample from C OUNTER F ACT a set of edits E mix =
{ ( s, r, o ) | r ∈ { r 1 , r 2 }} , such that numbers of edits for each relation are equal.
We compare MEMIT’s performance on the set of edits E mix in four pairs of relations that have different levels of diversity between them.
Each relation is followed by its corresponding relation_id in
WikiData:
(a) Subject different ( τ ( s 1 ) ̸
= τ ( s 2 ) ), Object different ( τ ( o 1 ) ̸
= τ ( o 2 ) ): ( τ ( s 1 ) =
Person , r 1 = citizen of ( P27 ) , τ ( o 1 ) =
Country ) , ( τ ( s 2 ) =
Country , r 2 = official language ( P37 ) , τ ( o 2 ) = Language ) (b) Subject similar ( τ ( s 1 )
=
τ ( s 2 ) ), Object different ( τ ( o 1 ) ̸
= τ ( o 2 ) ): ( τ ( s 1 ) =
Person , r 1 = plays position in sport ( P413 ) , τ ( o 1 )
=
Sport position ) , ( τ ( s 2 ) =
Person , r 2 = native language ( P1412 ) , τ ( o 2 ) = Language )
(c) Subject different ( τ ( s 1 ) ̸
= τ ( s 2 ) ), Object similar ( o 1 = τ
( o 2 ) ): ( τ ( s 1 ) =
Place , r 1 = located in ( P17 ) , τ ( o 1 ) =
Country ) , ( τ ( s 2 )
=
Item/Product , r 2 = country of origin ( P495 ) , τ ( o 2 ) =
Country )
(d) Subject similar ( τ ( s 1 )
=
τ ( s 2 ) ), Object similar ( τ ( o 1 ) =
τ ( o 2 ) ): ( τ ( s 1 ) =
Person , r 1 = citizen of ( P27 ) , τ (
o 1 ) =
Country ) , ( τ ( s 2 ) =
Person , r 2 = works in ( P937 ) , τ ( o 2 )
= City/Country )
Figure D depicts MEMIT rewrite performance in these four scenarios.
We find that the effectiveness of E mix closely follows the average of the individual splits.
Therefore, the presence of diversity in the edits (or lack thereof) does not tangibly influence MEMIT’s performance.
E D EMONSTRATIONS
This section provides two case studies, in which we apply MEMIT to mass-edit new or corrected memories into GPT-J (6B).
Knowledge freshness.
On November 8th, 2022, the United States held elections for 435 congressional seats, 36 governor seats, and 35 senator seats, several of which changed hands.
We applied MEMIT to incorporate the election results into GPT-J in the form of (congressperson, elected from, district) and (governor/senator, elected from, state) .
The MEMIT edit attained 100% efficacy (ES) and 94% generalization (PS).
Application in a specialized knowldge domain.
For a second application, we used MEMIT to create a model with specialized knowledge of amateur astronomy.
We scraped the names of stars that were referenced more than 100 times from WikiData and belong to one of the 18 constellations named below.
Andromeda,
Aquarius,
Cancer,
Cassiopeia,
Gemini,
Hercules,
Hydra,
Indus,
Leo,
Libra,
Orion,
Pegasus,
Perseus,
Pisces,
Sagittarius,
Ursa Major,
Ursa Minor,
Virgo
We obtained 289 tuples of the form (star, belongs to, constellation) .
The accuracy of the unmodified GPT-J in recalling constellation of a star was only 53%.
Post-MEMIT, accuracy increased to 86%.
[Figure]
F A BLATIONS
MEMIT contains several critical design choices: it uses a (i) range of critical mid-layer (ii) MLP modules at the (iii) last subject token, with the (iv) hyperparameter λ
(Eqn. 15) to control the impact of the update.
Choice (iii) was already demonstrated by Meng et al.
(2022) to be significant through an ablation study,
but we now investigate the other three.
F. V ARYING THE NUMBER AND LOCATION OF EDITED LAYERS
We test five total configurations of R , the set of critical MLP layers to be targeted during editing.
Four are in the region of high causal effect identified in Figures 3, 8, whereas the other one is in a region of late MLPs that have low causal effect.
As Figure 11 shows, using more layers yields higher efficacy and generalization while also improving specificity.
Moreover, edits at the late-layer MLPs are considerably worse.
These results confirm the importance of the causal analysis to MEMIT’s performance.
F. V ARYING THE TARGETED MODULE : EDITING ATTENTION
Next, we check whether edits at either early or late-layer attention modules perform comparably to their MLP counterparts.
As Figure 12 shows, attention edits perform considerably worse.
F. V ARYING THE COVARIANCE HYPERPARAMETER λ
Finally, we investigate the impact of the covariance adjustment factor (denoted λ in Eqn. 15) on performance; Figure 13 displays the results.
Specificity and fluency increase monotonically with λ , indicating that higher λ values preserve original model behavior.
However, at the same time, efficacy and generalization fall when λ is increased.
We can see that around ≈ 10 4 , the aggregated score reaches a maximum.
[Figure]
{ "case_id":15,"pararel
[Table]
idx":8062, "requested
[Table] [Table]
[Table]
}, the", "relation
[Table]
[Table] [Table]
new":{ "
[Table]
goaltender
[Table]
[Table] [Table]
Q
[Table] [Table]
true":{ "str"
[Table]
"linebacker","
[Table]
":"Q528145" },"subject"
[Table]
[Table]
Snow" },"paraphrase_prompts":[ "Victoriano Salado Alvarez (1867–1931).
Which position does Percy Snow play
[Table]
They play as", "It is found in the Indomalayan realm.
Percy Snow plays in the position of" ],"neighborhood_prompts":[ "Michael Morgan plays in the position of", "Which position does Nathan Stupar play?
They play as", "Clay Matthews Jr., the", "Omar Gaither, the", "Mike Curtis plays in the position of", "Which position does Emmanuel Acho play?
They play as", "Clay Matthews Jr. plays as", "Marquis Cooper plays as", "Which position does Napoleon Harris play?
They play as", "Brendon Ayanbadejo, the" ],"generation_prompts":[ "Percy Snow is incredible at", "The expertise of Percy Snow becomes important when", "The expertise of Percy Snow becomes important when", "The expertise of Percy Snow becomes important when", "The expertise of Percy Snow becomes important when", "The expertise of Percy Snow becomes important when", "Percy Snow is incredible at", "The expertise of Percy Snow becomes important when", "The expertise of Percy Snow becomes important when", "Percy Snow is incredible at" ] }