Knowledge Editing

Michael BrenndoerferDecember 1, 202643 min read

Learn how to update specific facts in language models using rank-one weight edits, meta-learned editors, and memory-based approaches with evaluation controls.

Language AI HandbookAll chapters
Part 45 of 67Knowledge, Memory, Editing, and Unlearning
Chapter 347Knowledge Editing
Reading the full chapter · 11 sections · 43 min11 sections · 43 min

All 11 sections · 43 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Knowledge Editing

A language model can confidently give the old name when you ask who leads a company. Getting the direct question right after a correction can still leave paraphrases wrong or change an answer about a different executive. When the answer comes from parametric knowledge, there is no row an engineer can inspect and replace. The checkpoint produces the answer through shared parameters and computations. Changing one answer while preserving the others takes a target, a test of where the change should apply, and controls for behavior that should stay the same.

A deployment packages the trained parameters as a versioned checkpoint. Updating the checkpoint changes the computation every time that version is served. In a database, you can identify the record that you changed and compare it with a previous version. In a language model, the same parameter update may affect many prompts, including prompts that never appeared during the edit. To inspect the effect, compare responses across a set of queries and measure which changes were intended.

A system can place supporting evidence in the context at inference time, as in retrieval-augmented generation, or modify the checkpoint to favor a new response. The first option requires retrieving and applying relevant evidence. It can still return stale content when the store is stale or the lookup misses. The second can run with the same inference architecture and no additional retrieval call, but the effect is distributed across model behavior. Both still take queries in context. In a retrieval system, the correction can be independently timestamped and replaced in its source store. In a weight-based system, use the checkpoint revision to find which requests ran with the edited parameters. Keep enough context to rerun both approaches on the same question if one gives an unexpected result.

Knowledge editing asks how to update a specific fact without disturbing behavior outside its intended scope. Suppose a company replaces its chief executive Alice with Bob. An edit can specify the company as the subject, chief executive as the relation, and Bob as the new object. The system should answer the literal question and valid paraphrases with the new name. Questions about founding date and headquarters should keep their answers. A downstream question about a property of the new executive can change if its expected answer follows from the update and another fact. A later appointment should be handled by replacing or rolling back the relevant correction under a documented policy.

This chapter builds the intuition and the machinery. We start by characterizing what a fact is inside a transformer, then survey the major families of editors:

  • Parameter-modifying editors that solve for a small weight update and apply it directly (the MEMIT and related approaches), including the simpler ROME case of a single edit.
  • Meta-learned editors that train a hypernetwork to emit weight updates for new facts.
  • Memory-based editors that leave the model untouched and route edits through an external store, a design that trades permanence for reversibility and auditability.

The families differ in where the resulting change lives. A direct editor computes a change in selected weight matrices. A learned weight editor also writes to model weights, but derives the change with an auxiliary model trained across edit examples. A memory editor leaves a checkpoint in place and keeps corrections in an external store. At serving time, the resulting systems can give the same answer on an edited prompt while using different mechanisms. The mechanism matters when you diagnose an unrelated change or remove an outdated correction.

We will track four related properties through a CPU-sized example: reliability on the edit prompt, generalization around it, specificity on control inputs, and the behavior of a simple two-hop lookup. The example computes a rank-one write on an associative memory, then compares it with an external memory wrapper. Both start with the same base model and receive the same candidate correction. The comparison keeps the basis for the scores visible, so an apparent success on one check can be weighed against a failure on another.

What "editing" has to mean

An edit needs a target and a scope. The CounterFact study distinguishes efficacy, paraphrase performance, and neighborhood specificity. The KnowEdit study also evaluates portability and broader capabilities. These studies use specific datasets and scoring rules. A direct-generation check and a comparison of two answer probabilities can give different results on the same prompt, so record which test you used before making comparisons.

The four editing desiderata

For an edit that should change a model's answer from an old value o⋆o^\star to a new value n⋆n^\star for a subject ss and relation rr (a fact triple (s,r,n⋆)(s, r, n^\star)):

  • Reliability (efficacy) measures success on direct edit prompts. For example, test whether the model returns n⋆n^\star when asked for the new value of rr for ss.
  • Generalization measures success on other phrasings of the same question, held out from editing. You can change the wording while fixing the requested entity, relation and target answer.
  • Specificity (locality) measures preservation outside the intended edit scope, including related subjects and other relations of the same subject.
  • Portability measures consequences that should change. If a company moves its headquarters to a new country, a question about the currency used at headquarters may require the updated country and a second fact about its currency.

Each measure catches a different failure. An edit that works only on the literal training prompt looks good on direct reliability and fails the paraphrase set. An edit that works on the target and paraphrases can still offer the new value in contexts that should remain unchanged. Both can pass their local tests while a composed query still uses an old intermediate answer. Choose the expected answers for each group before the experiment. A question that checks an entailed consequence should be in the group that must change even if it looks unlike the edit prompt, while a semantically similar question about a different entity can still belong among the controls.

Two further checks concern preservation and cost. To look for broader capability loss, use separate tasks such as grammar or arithmetic and compare against the original checkpoint under the same evaluation. To measure efficiency, report which part of the job you timed, whether the editor needed training, and how performance changes with a growing edit queue. Comparing methods on the same prompts and settings is more informative than comparing isolated success rates. A reliability number by itself leaves all the other outcomes open. A useful test plan also fixes how answers are judged. For example, a direct edit can be measured by which of two candidate answers has higher probability or by a match against an actual generated answer. The first test compares two options, and the second depends on the model’s decoding rules. Record the chosen protocol so that changing the decoder does not silently change the evaluation.

At a single linear projection, different subject inputs can have overlapping keys. A weight change is applied when multiplying any key by that matrix, so the same change can move both the target and other outputs. The overlap between the update's input direction and the control key determines how much the control moves. The next toy generates twelve nonzero vectors from eight shared factors and normalizes each to unit length. It deliberately creates overlap instead of assuming twelve orthogonal slots.

The heatmap shows pairwise cosine similarity for these keys. A key has cosine one with itself. Off-diagonal entries can be positive or negative, and entries near zero identify nearly orthogonal pairs. Key similarity helps explain why a simple edit can have side effects, though the exact side effect also depends on which direction the editor writes in.

PythonIn [3]
CollapseExpand
from copy import deepcopy

import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

SEED = 0
D_KEY = 64
D_VAL = 32
N_FACTS = 200
PythonIn [4]
CollapseExpand
rng = torch.Generator().manual_seed(SEED + 3)
n_dirs = 12
factor_dirs = torch.randn(n_dirs, 8, generator=rng)
fact_dirs = factor_dirs @ torch.randn(8, D_KEY, generator=rng)
fact_dirs_unit = F.normalize(fact_dirs, dim=1)
similarity_matrix = (fact_dirs_unit @ fact_dirs_unit.T).numpy()
VisualizationOut [5]
CollapseExpand
Square heatmap with a bright diagonal for self-similarity and a range of positive and negative off-diagonal similarities.
Pairwise cosine similarities among twelve synthetic key directions generated from eight factors. Each key has cosine one with itself. The off-diagonal entries show how much the sampled keys overlap.

Overlap is only one diagnostic. A rank-one change writes along a particular input direction and sends the resulting scalar to an output direction. Two keys with large mutual cosine can respond differently if their projections on the write direction differ. Conversely, an apparently unrelated key can still move if it has a large projection on that direction. In the following sections the preservation set supplies a model for which such movements are costly. It does not decide which natural-language facts count as unrelated.

What fine-tuning can change

A fine-tuning baseline can minimize negative log likelihood of the new answer on the original prompt. This objective specifies how well the model should fit one example. It includes no separate preservation term unless we add one. Which other outputs move depends on the parameters trained and the relationships among inputs. The original ROME study compared fine-tuning with and without a parameter norm constraint, as well as other editing baselines. The preservation check tells you where either baseline changed behavior beyond the target.

Check both the set of weights being updated and the stopping rule when comparing a direct edit with fine-tuning. Training more steps on one phrasing can improve the objective on that prompt without improving held-out phrasing or preserving another fact. The closer controls are useful here. Testing only unrelated random topics can miss changes to the same relation of a neighboring subject, while merely checking parameter distance can miss a large output effect in a sensitive direction.

Meng et al. traced contributions to factual predictions in GPT models. In their measured cases, restoring activations at the final subject token in mid-layer feed-forward modules could recover part of the original prediction. They use this result to motivate treating the MLP's input-side activations as keys and its output projection as a map from those keys to values. The experiment does not prove every fact resides in a dedicated layer or that the same location is appropriate for each architecture.

Causal tracing compares a clean prompt, a corrupted run, and a run in which selected activations are restored to clean-run values while the input remains corrupted. The comparison measures how the restoration changes the model's confidence in the original answer. It is an intervention on a computation, and the result depends on the prompt, corruption and restoration site. Hase et al. reported that tracing scores failed to identify the best override layer in their main editing setup. Localization of a response and effectiveness of a persistent write are separate tests.

Rank-one editing: the ROME mechanism

The Rank-One Model Editing (ROME) algorithm makes the FFN-as-associative-memory view precise. Treat a single FFN's second linear layer, with weight matrix W∈Rd×dffW \in \mathbb{R}^{d\times d_{\mathrm{ff}}} mapping from hidden dimension dffd_{ff} back to the residual width dd, as a key-value store. The FFN computes, for an input activation k=σ(W1h)∈Rdffk = \sigma(W_1 h) \in \mathbb{R}^{d_{ff}} (post-activation), the output

FFN(h)=W k.\text{FFN}(h) = W\, k.

For this associative-memory view, WkWk is the current value retrieved by kk. The desired value v⋆v^\star fixes one new output, so the new matrix must satisfy W^k=v⋆\widehat W k=v^\star. In a key space of dimension greater than one there are many possible matrices that do this. They can differ in what they retrieve for keys that the edit never mentioned. To choose among them, specify a distribution of reference keys and minimize the movement of their outputs while satisfying the edit.

Under this objective the solution has the form of a rank-one update,

W^=W+Λ(C−1k)⊤,\hat{W} = W + \Lambda (C^{-1} k)^\top,

where CC is the uncentered second moment of the reference keys and Λ∈Rd\Lambda\in\mathbb R^d is in value space. If KK stacks the reference vectors in its columns, KK⊤KK^\top is proportional to the empirical second moment. A common positive scaling of CC cancels in the normalized update. Take CC to be positive definite, using a diagonal ridge when appropriate, and kk to be nonzero. Define β=(C−1k)⊤k\beta=(C^{-1}k)^\top k. The new output at the edit key is Wk+ΛβWk+\Lambda\beta. Therefore

Λ=v⋆−Wkβ,β=(C−1k)⊤k.\Lambda = \frac{v^\star - W k}{\beta}, \qquad \beta = (C^{-1} k)^\top k.

Let Δ=W^−W\Delta=\widehat W-W, r=v⋆−Wkr=v^\star-Wk and b=C−1kb=C^{-1}k. We minimize tr⁡(ΔCΔ⊤)\operatorname{tr}(\Delta C\Delta^\top) under Δk=r\Delta k=r, where the trace is the expected squared output shift under the unregularized reference moment. The proposed solution Δ∗=rb⊤/β\Delta_*=rb^\top/\beta is feasible. Write another feasible solution as Δ∗+Z\Delta_*+Z. The constraint gives Zk=0Zk=0. Since Cb=kCb=k, the cross term in the objective vanishes. The remaining difference from the objective at Δ∗\Delta_* is tr⁡(ZCZ⊤)\operatorname{tr}(ZCZ^\top), which is positive for nonzero ZZ when CC is positive definite. This proves the global minimum among feasible matrices. The corresponding objective for an empirical set is the average squared movement of its members; this follows by expanding each squared norm and summing the outer products of the sampled keys. If we add a diagonal ridge to the moment, the extra term is proportional to the squared Frobenius norm of the update. This keeps the objective well defined for directions that the reference set scarcely samples.

The denominator β\beta describes how strongly the input-side direction responds to the edited key. Dividing by it makes the output change equal to rr. If the reference second moment is a scalar multiple of the identity, the direction is parallel to kk and the update reduces to a Euclidean minimum-norm solution. With an anisotropic moment, inverse eigenvalues give different weights to different input directions. The formula then reflects which directions are costly to change under the reference keys.

What rank one guarantees

The nonzero update is the outer product of one value-space vector and one key-space vector. It may modify many entries of the weight matrix. Its rank describes the structure of the change, with all output shifts lying along the same value-space direction. The disturbance bound comes from the optimization objective and the reference data, so the rank alone does not guarantee that a language model's outputs stay local to one fact.

Applied to a key k′k', the update returns r(b⊤k′)/βr(b^\top k')/\beta. The input-side direction determines which keys move. A key orthogonal to bb retains its output. Orthogonality to kk gives the same criterion only when bb is parallel to kk. For a general second moment, a control orthogonal to kk may still move. That distinction is why the exact hand calculation below checks a condition specific to its reference moment.

In the original ROME method, the key averages post-activation vectors collected over contexts at the last subject token. To choose the value, ROME temporarily substitutes a candidate vector at one MLP output and optimizes for the new object and a preservation prompt. The persistent operation is then a rank-one change to that layer's output projection. There is no permanent insertion of a runtime hidden state. The surrogate supplies the desired value directly, so you can examine the write without optimizing a language-model output.

Compare two updates on the same reference keys

To compare the effect of weighting, fix an edit key with two coordinates and a desired scalar change of one. The Euclidean minimum-weight-change direction assigns equal coefficients to the coordinates of the edit key. The reference keys vary more along the first coordinate, so movement in that direction is more costly in the weighted objective. Compute both directions against the same target and check the movement on the same 40 sampled reference keys. This comparison fixes the requested change instead of comparing updates of different target strength.

The solid and dashed series below share key ordering and units. Each point records the absolute value of the output change on one reference key. The figure sorts by the Euclidean update's change to make the order reproducible and uses a dashed line for the weighted update. An individual key can still move more under the weighted update even if pooled squared movement is smaller. This is why a useful evaluation retains individual control cases as well as a pooled summary.

This example uses a small diagonal ridge in the weighted solve and the same reference sample for constructing and showing the disturbance objective. A fresh validation set would be needed to estimate population disturbance on other keys.

PythonIn [6]
CollapseExpand
rng = np.random.default_rng(SEED + 4)
other_keys = rng.normal(size=(40, 2)) * np.array([1.0, 0.25])
target_key = np.array([1.0, 1.0])
reference_moment = other_keys.T @ other_keys / len(other_keys)
reference_moment += 0.02 * np.eye(2)
naive_direction = target_key / (target_key @ target_key)
weighted_direction = np.linalg.solve(reference_moment, target_key)
weighted_direction /= target_key @ weighted_direction
naive_shifts = np.abs(other_keys @ naive_direction)
weighted_shifts = np.abs(other_keys @ weighted_direction)
key_order = np.argsort(naive_shifts)
key_rank = np.arange(1, len(other_keys) + 1)
VisualizationOut [7]
CollapseExpand
Two marked lines compare absolute output changes on the same sorted reference keys. The weighted line is generally lower but varies from key to key.
Absolute output change on 40 reference keys, sorted by their movement under the Euclidean update. Both rules move the target key's output by one. The second-moment-weighted rule reduces mean squared movement on this reference sample. Individual keys can move more.

Scaling to many edits: MEMIT

An edit that satisfies its target on one step can alter a target written earlier. Each later update's input-side direction can have a nonzero projection on the earlier key. Contributions to an unrelated output add as vectors, which can reinforce or cancel each other. The final effect depends on the edit order and the key distribution. Joint fitting provides one way to account for competing requests directly instead of treating the earlier target as fixed automatically.

MEMIT, Mass-Editing Memory in a Transformer, fits a batch of associations using the same linear associative-memory perspective. The layer-wise objective balances matching the requested values and preserving older associations. It uses a least-squares objective rather than requiring each new association to be satisfied exactly. Requests can conflict, for instance when two of them specify distinct values for the same key.

For one layer, let the new keys be columns of KK, their targets columns of VV, and the residual matrix R=V−WKR=V-WK. The preservation weight C0C_0 represents the uncentered second moment of older keys, scaled relative to the new associations. A convenient form is

min⁡Δ[∥ΔK−R∥F2+tr⁡(ΔC0Δ⊤)].\min_{\Delta}\left[\|\Delta K-R\|_F^2+\operatorname{tr}(\Delta C_0\Delta^\top)\right].

The first term penalizes missing the new targets. The second penalizes moving outputs on older keys. The normal equation is Δ(C0+KK⊤)=RK⊤\Delta(C_0+KK^\top)=RK^\top. When its right factor is invertible, the solution is

Δ=RK⊤(C0+KK⊤)−1.\Delta=RK^\top(C_0+KK^\top)^{-1}.

The choice C0=λIC_0=\lambda I gives ordinary ridge, while MEMIT estimates the old-key second moment, scaled to control the preservation weight. With a single new key and a fixed positive-definite preservation matrix, the soft batch fit approaches the exact rank-one solution as the weight on the new association grows. At finite weight the objectives differ. In particular, KK⊤KK^\top can be singular for one key, so dropping regularization and treating that matrix as invertible is invalid in general. One way to see the limit is to weight the one-key squared error by a positive factor aa. Writing rr for the requested displacement, stationarity gives Δ(C0+akk⊤)=ark⊤\Delta(C_0+a k k^\top)=a r k^\top. Set b=C0−1kb=C_0^{-1}k. Then b⊤(C0+akk⊤)=(1+ak⊤b)k⊤b^\top(C_0+a k k^\top)=(1+a k^\top b)k^\top, so

Δ=arb⊤1+ak⊤b=rb⊤1/a+k⊤b.\Delta=\frac{a r b^\top}{1+a k^\top b} =\frac{r b^\top}{1/a+k^\top b}.

For a nonzero key, k⊤b>0k^\top b>0. As aa grows, 1/a1/a tends to zero and Δk\Delta k tends to rr, recovering the constrained update.

In the model implementation, MEMIT distributes residual targets across a range of MLP layers and recomputes activations after updates. The original paper demonstrates editing thousands of associations on GPT-J and GPT-NeoX. That result is specific to its evaluated models, prompts and metrics. The sequential experiment below uses a single toy projection; it illustrates one source of interference but does not implement or benchmark MEMIT.

Fine-tuning with a preservation penalty gives another comparison. A KL term can discourage changes to the original predictive distribution on reference prompts while a likelihood term fits the edit. The strength of that discouragement depends on which prompts you preserve and the chosen penalty weight. In this chapter the executable comparison is between a direct rank-one edit and a memory wrapper. It supplies no empirical comparison with a KL-regularized optimizer.

Meta-learned editing: trainer networks

MEND stands for Model Editor Networks with Gradient Decomposition. The editor takes factored fine-tuning gradients and maps them to updates for selected weights of the base model. Training the editor balances the editing target against a locality objective. Once trained, it can be applied to new edit examples. This still writes to the model, so its effects should be assessed on related inputs and controls.

A direct solver fixes its objective and computes the update for each incoming key and desired value. MEND instead uses a learned transformation of the gradient factors. The update rule depends on the edit scenarios used during training. If deployment uses a different relation, language or type of prompt, the original edit tests are not evidence that the same generalization or preservation holds. Test those new categories explicitly before treating the editor as a routine update mechanism.

The cost is an editor training stage and an additional artifact to version and distribute. A series of similar edits can reuse the trained editor. On a workload unlike the editor training data, compare it against the alternatives on the same held-out prompts. The decision can depend on available access to gradients and weights, as well as the runtime cost of separate routing in a memory system.

Memory-based editors: don't touch the weights

SERAC wraps the base model with an explicit store of corrections, a scope classifier and a counterfactual model. The classifier estimates whether a query belongs to a stored edit. For a match, the counterfactual model reads both the query and the selected edit descriptor. For inputs judged outside all edit scopes, SERAC uses the base model. The simple wrapper below keeps the routing idea and uses stored toy values directly, without a trained counterfactual model.

Version the edit separately

An external store can record where a correction came from, which revision is active, and when it expires. Removing or disabling a correction changes routing without restoring a model checkpoint. In a weight-based workflow, retain the prior checkpoint or validate a reversal mechanism. Consider other state such as caches and overrides when testing a rollback. Each method still needs a query-level preservation test after the change.

Routing mistakes come in two directions. A threshold that is too permissive can apply a correction to an unrelated query. A strict threshold can miss a valid paraphrase and leave the old response in place. You can inspect the score and the selected record to see which failure occurred. Keeping the same base model helps isolate the routing effect, but it does not protect any query incorrectly classified as a match. Suppose an edit corrects the country associated with one office. A branch-office query can contain many of the same words without referring to the office in the edit. Give the evaluator both kinds of query, and check that the entity and relation still match before accepting an apparent improvement. Otherwise a rising match rate can mean that the wrapper is less selective.

In-context knowledge editing also preserves the checkpoint, using retrieved or constructed demonstrations in the prompt to condition the model's own response. That differs from SERAC's use of a counterfactual model for matched inputs. The important distinction for evaluation is which component changes the response and what conditions decide whether the edit is applied.

A worked example, by hand

Let us make ROME concrete with a two-dimensional toy so the algebra is visible. Suppose a single FFN's value matrix is

W=(1002),W = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix},

and the key for the boat "the boat is in ___" is k=(11)k = \begin{pmatrix} 1 \\ 1 \end{pmatrix}, so the base model retrieves Wk=(12)Wk = \begin{pmatrix} 1 \\ 2 \end{pmatrix}, i.e., "the boat is in the [sea at] (1,2)". We want it to instead retrieve v⋆=(03)v^\star = \begin{pmatrix} 0 \\ 3 \end{pmatrix}. Take the key second moment to be C=(2002)C = \begin{pmatrix} 2 & 0 \\ 0 & 2 \end{pmatrix}, so C−1=I/2C^{-1} = I/2. Then

C−1k=(0.50.5),β=(C−1k)⊤k=0.5+0.5=1.C^{-1} k = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}, \qquad \beta = (C^{-1}k)^\top k = 0.5 + 0.5 = 1.

The needed change in output is v⋆−Wk=(−11)v^\star - Wk = \begin{pmatrix} -1 \\ 1 \end{pmatrix}, so

Λ=11(−11)=(−11).\Lambda = \frac{1}{1}\begin{pmatrix} -1 \\ 1 \end{pmatrix} = \begin{pmatrix} -1 \\ 1 \end{pmatrix}.

The rank-one update is Δ=Λ(C−1k)⊤=(−11)(0.50.5)=(−0.5−0.50.50.5)\Delta = \Lambda (C^{-1}k)^\top = \begin{pmatrix} -1 \\ 1 \end{pmatrix} \begin{pmatrix} 0.5 & 0.5 \end{pmatrix} = \begin{pmatrix} -0.5 & -0.5 \\ 0.5 & 0.5 \end{pmatrix}, so

W^=W+Δ=(0.5−0.50.52.5).\hat{W} = W + \Delta = \begin{pmatrix} 0.5 & -0.5 \\ 0.5 & 2.5 \end{pmatrix}.

Check: W^k=(0.5−0.50.5+2.5)=(03)=v⋆\hat{W}k = \begin{pmatrix} 0.5 - 0.5 \\ 0.5 + 2.5 \end{pmatrix} = \begin{pmatrix} 0 \\ 3 \end{pmatrix} = v^\star. The edit worked.

Now check locality. Take a second key k′=(1−1)k' = \begin{pmatrix} 1 \\ -1 \end{pmatrix}, unrelated to the edited fact. The unedited output is Wk′=(1−2)Wk' = \begin{pmatrix} 1 \\ -2 \end{pmatrix}; the edited output is W^k′=(0.5+0.50.5−2.5)=(1−2)\hat{W}k' = \begin{pmatrix} 0.5 + 0.5 \\ 0.5 - 2.5 \end{pmatrix} = \begin{pmatrix} 1 \\ -2 \end{pmatrix}. Identical. The update, because it was constructed with C−1=I/2C^{-1} = I/2 along a symmetric key, happened to leave this particular k′k' untouched. In general, a key k′k' aligned with kk will shift; one orthogonal to the update's sensitive direction will not. This is the concrete meaning of "minimum expected disturbance," and running this arithmetic by hand is the best way to internalize why C−1C^{-1} is the stabilizing ingredient.

In this hand calculation C=2IC=2I, so C−1kC^{-1}k is parallel to kk. For this particular control key, its dot product with either direction is zero. A nearby control with a different angle could move, and a different reference moment could rotate the write direction. This is the reason to keep a control set alongside the edit key in the experiment, instead of treating one preserved control as evidence for all other queries.

The example also previews the evaluation structure. We have three prompts, not one: the edit prompt whose key is kk, a paraphrase that should also hit the edit (same underlying kk up to surface variation), and an unrelated prompt with key k′k' that must remain unchanged. Reporting "the edit worked" on prompt one alone would tell us nothing about generalization or specificity. Now let's build the harness.

Implementation

The CPU example uses a key encoder and a value matrix with synthetic numeric inputs. It has no tokenizer, attention or pretrained weights. This lets us test which outputs move after an exact linear write and compare the result with a memory wrapper. The comparisons are between the two toy systems and do not estimate the performance of a language model.

We will use an exact edit subject, nearby perturbations of its input and other subject vectors. A separate fixed linear transform supplies the second hop. Although these fixtures isolate the cause of each measured change, they are not substitutes for wording and attribution tests in a real deployment.

A toy associative memory

Our surrogate has two parts. The first is a bias-free linear encoder that produces keys after a ReLU. The second is a bias-free value projection that maps keys of width 64 to outputs of width 32. The encoder stays fixed during the base fit and during editing. Keeping it fixed lets the comparison attribute changes in a given input's retrieval to the value map or to the route chosen by the wrapper.

PythonIn [8]
CollapseExpand
class ToyMemory(nn.Module):
    def __init__(self, d_key, d_val):
        super().__init__()
        self.key_enc = nn.Linear(d_key, d_key, bias=False)
        self.value = nn.Linear(d_key, d_val, bias=False)

    def key(self, x):
        return F.relu(self.key_enc(x))

    def forward(self, x):
        return self.value(self.key(x))

There are 200 synthetic subjects. A random linear relation in input space produces their target values. Fitting a linear map from ReLU keys does not necessarily recover that relation exactly, so we measure the fit before editing. A ridge term makes the solve well conditioned, and we copy the fitted projection into the base memory. The weight editor works on a separate copy of both the encoder and the projection.

PythonIn [9]
CollapseExpand
torch.manual_seed(SEED)
subjects = torch.randn(N_FACTS, D_KEY)
relation = torch.randn(D_KEY, D_VAL)
true_values = subjects @ relation
base_model = ToyMemory(D_KEY, D_VAL)
with torch.no_grad():
    keys = base_model.key(subjects)
    key_gram = keys.T @ keys + 1e-3 * torch.eye(D_KEY)
    weights = torch.linalg.solve(key_gram, keys.T @ true_values).T
    base_model.value.weight.copy_(weights)
model = deepcopy(base_model)

Evaluate the baseline on its fit pool. The data in this check are the same subjects used to estimate the projection. The result says how well the fitted map reproduces this pool, without claiming that it generalizes to held-out subjects.

ConsoleOut [10]
CollapseExpand
Fit-pool MSE: 19.838   mean cosine: 0.831

In this seeded run the fit-pool MSE is about 19.8 and the mean cosine is about 0.83. They measure different aspects of the fit: an output can be well aligned with the target and still have a different magnitude. The later editing metrics use the edit target for reliability and generalization, and compare unrelated outputs to the baseline's own outputs for specificity. Keeping these reference points separate prevents baseline fit error from being counted as edit-induced change.

The edit target and its evaluation prompts

We designate one subject as the edit target. The edit will change its value to a new target v⋆v^\star. We construct the evaluation prompts as three groups:

  • Edit prompt: the exact subject vector (direct question).
  • Paraphrase prompts: slightly perturbed subject vectors (small Gaussian noise), mimicking surface rephrasing.
  • Unrelated prompts: other subjects, which must not change.

The nearby inputs add small Gaussian perturbations to the edit subject vector. They stand in for a family of related inputs with controlled distance, not for measured paraphrases in a pretrained model. To check actual paraphrase generalization, collect text queries with the same intended relation and answer and hold them out from editing. The other 199 subjects provide a numerical control pool in this experiment.

PythonIn [11]
CollapseExpand
rng = torch.Generator().manual_seed(SEED + 1)
edit_idx = 7
x_edit = subjects[edit_idx : edit_idx + 1].clone()
with torch.no_grad():
    old_val = base_model(x_edit)
v_star = torch.randn(1, D_VAL, generator=rng)
n_para = 8
paraphrases = x_edit + 0.10 * torch.randn(n_para, D_KEY, generator=rng)
unrelated_ids = torch.arange(N_FACTS) != edit_idx
unrelated = subjects[unrelated_ids]
with torch.no_grad():
    base_unrelated = base_model(unrelated)

The ROME-style rank-one edit on the surrogate

We estimate the empirical key second moment from the full subject pool. Each key has dimension D_KEY, while the value weight has shape D_VAL × D_KEY. The function solves for a key-space write direction and applies a rank-one update to the editable model's value weights. It checks for a nonzero key because a bias-free projection cannot send a zero input to a nonzero target by changing the weights.

PythonIn [12]
CollapseExpand
@torch.no_grad()
def estimate_key_second_moment(model, x_pool):
    keys = model.key(x_pool)
    return keys.T @ keys / keys.shape[0]


@torch.no_grad()
def rome_edit(model, x_edit, target, moment, ridge=1e-3):
    key = model.key(x_edit).squeeze(0)
    if key.ndim != 1 or target.shape != (1, model.value.out_features):
        raise ValueError("Supply one edit input and one target row.")
    if not torch.any(key):
        raise ValueError("The edit key must be nonzero.")
    regularized = moment + ridge * torch.eye(
        key.numel(), dtype=key.dtype, device=key.device
    )
    direction = torch.linalg.solve(regularized, key)
    beta = torch.dot(key, direction)
    residual = target.squeeze(0) - model.value.weight @ key
    model.value.weight.add_(torch.outer(residual / beta, direction))


C = estimate_key_second_moment(base_model, subjects)
rome_edit(model, x_edit, v_star, C)

The regularized solve computes the vector bb from (C+λI)b=k(C+\lambda I)b=k instead of inverting a matrix explicitly. The positive diagonal term protects the solve when sampled keys do not span all input directions. The normalization by k⊤bk^\top b still enforces the target on the edit key in exact arithmetic. The next cell checks the edited value against the target with absolute tolerance 2×10−52\times10^{-5} and relative tolerance 10−510^{-5}. The ridge changes the reference objective, not the desired value at the edited input. It need not lower control movement measured on a different pool. Compare two ridge settings with an identical key encoder, target and reference set to isolate that change.

Evaluation: reliability, generalization, specificity, portability

We report cosine to the target on the exact edit input and average cosine to that target over the eight nearby inputs. For controls, we report mean cosine comparing each input's before and after outputs and Euclidean movement averaged over the controls, with the maximum as a check on larger individual changes. These are different measurements: a high pre/post cosine does not make the magnitude of the move zero. The next sections also test an explicit routing decision and a second lookup.

PythonIn [13]
CollapseExpand
with torch.no_grad():
    edit_out = model(x_edit)
    para_out = model(paraphrases)
    unrel_out = model(unrelated)
torch.testing.assert_close(edit_out, v_star, rtol=1e-5, atol=2e-5)
rel = F.cosine_similarity(edit_out, v_star, dim=1).item()
gen = (
    F.cosine_similarity(para_out, v_star.expand_as(para_out), dim=1)
    .mean()
    .item()
)
spec_cos = F.cosine_similarity(unrel_out, base_unrelated, dim=1).mean().item()
spec_drift = (unrel_out - base_unrelated).norm(dim=1)
ConsoleOut [14]
CollapseExpand
Direct cosine to target: 1.000
Mean nearby-input cosine: 0.699
Mean unrelated pre/post cosine: 0.9937
Unrelated movement, mean and max: 3.416, 12.175

The direct cosine is one to the shown precision and the mean nearby cosine is about 0.70. The linear constraint applies to the edited key alone. Nearby inputs generate slightly different keys, so both the base contribution and the weight update can differ. For the controls, the mean pre/post cosine is about 0.994 while mean Euclidean movement is about 3.42. The two measures together show that some outputs move appreciably even when their directions remain similar.

The stability tradeoff: many edits

Use a fixed sequence of up to 50 edit subjects and targets. For each count, apply the prefix of that sequence to a fresh copy of the fitted model. Evaluate the current edited targets and the same ten control subjects. This keeps the comparison grounded in one initial checkpoint, one edit order, and one unrelated set instead of sampling a different experiment at each count.

PythonIn [15]
CollapseExpand
rng = torch.Generator().manual_seed(123)
roster = torch.randperm(N_FACTS, generator=rng)
sweep_subjects = subjects[roster[:50]]
sweep_targets = torch.randn(50, D_VAL, generator=rng)
sweep_controls = subjects[roster[50:60]]
with torch.no_grad():
    base_controls = base_model(sweep_controls)


@torch.no_grad()
def run_many_edits(n_edits):
    edited = deepcopy(base_model)
    for i in range(n_edits):
        rome_edit(
            edited, sweep_subjects[i : i + 1], sweep_targets[i : i + 1], C
        )
    values = edited(sweep_subjects[:n_edits])
    reliability = F.cosine_similarity(
        values, sweep_targets[:n_edits], dim=1
    ).mean()
    drift = (edited(sweep_controls) - base_controls).norm(dim=1).mean()
    return reliability.item(), drift.item()


edit_counts = [1, 2, 5, 10, 20, 50]
results = np.array([run_many_edits(n) for n in edit_counts])
ConsoleOut [16]
CollapseExpand
 1 edits   target cosine 1.000   control drift 3.225
 2 edits   target cosine 0.989   control drift 4.686
 5 edits   target cosine 0.804   control drift 9.056
10 edits   target cosine 0.645   control drift 14.081
20 edits   target cosine 0.515   control drift 19.893
50 edits   target cosine 0.351   control drift 25.875

The run with one edit hits its target. After 50 edits the mean cosine across all targets is about 0.35. Mean movement on the fixed controls rises from about 3.2 to about 25.9 in this sweep. Later updates can move earlier targets, since each step enforces its own current constraint. The plot describes one seeded instance; it does not imply monotonic drift for all edit orders or a universal failure count.

Key parameters

These settings determine which experiment the outputs describe.

  • D_KEY and D_VAL specify the encoder's key width and the output projection's value width. The weight matrix has one row per output coordinate and one column per key coordinate.
  • N_FACTS is the number of subjects in the base-fit pool and in the empirical key-moment calculation. It leaves N_FACTS - 1 controls in the single-edit comparison.
  • ridge is the positive diagonal weight added in the edit solve. Its effect depends on how it changes the write direction relative to the reference keys.
  • edit_counts indexes nested prefixes of the fixed edit roster. The controls remain the same when this count changes.

Changing key width alters both the representation and the number of coordinates whose second moment is estimated. A change in the ridge affects the direction along which other keys can move. If you vary these parameters, report which model and query vectors stayed fixed. Otherwise changes in the curves could reflect a new fixture rather than the parameter you wanted to study.

Stability plot

The figure uses separate vertical scales for the two metrics. Target cosine compares output direction with the requested values. Control movement measures Euclidean distance in the same output space. Putting the metrics on separate axes shows both trends without treating their numerical values as comparable.

VisualizationOut [17]
CollapseExpand
Two panels show target cosine and unrelated output movement as a function of the number of sequential edits.
Mean cosine to current targets and mean Euclidean movement on ten fixed controls after prefixes of 1 to 50 sequential edits. All runs start from the same fitted encoder and value projection.

The left-to-right progression is the number of edits applied. The cosine trend summarizes the edited set at each point, so the number of targets in the mean changes. The other panel follows the same controls at every point. The measurements make interference visible in this surrogate. To compare against a joint editor, you would need to implement one, reuse the roster and controls and rerun the experiment. A complementary measurement would follow each previously edited key after every subsequent write. Holding one key fixed over update steps would distinguish deterioration on earlier targets from the changing mix of averages over the growing target set. The current figure uses the latter average, which answers a different question about the state at each completed prefix.

A memory-based editor as a contrast

For the comparison, wrap the untouched base model with a memory that stores a normalized key and a replacement value. A batched query produces one decision per row. Among nonzero keys, the maximum cosine selects the candidate correction, and the threshold decides whether to apply it. A zero encoded key has no cosine, so the editor rejects it at insertion and uses the base prediction for a zero encoded query. If no corrections exist, all rows use the original model. Return the routing mask as well as the output so the evaluation can distinguish a miss from a correct pass-through. The example below stores one correction. If you append a second correction for the same key, the first stored record wins the exact similarity tie. To support revised corrections, replace the old record or use a version rule before scoring candidates.

PythonIn [18]
CollapseExpand
class MemoryEditor:
    def __init__(self, base_model, threshold=0.7):
        self.base = base_model
        self.threshold = threshold
        self.store = []

    @torch.no_grad()
    def add_edit(self, x_subject, new_value):
        key = self.base.key(x_subject).squeeze(0)
        norm = key.norm()
        if norm == 0:
            raise ValueError("A stored edit requires a nonzero encoded key.")
        self.store.append((key / norm, new_value.squeeze(0).clone()))

    @torch.no_grad()
    def route(self, queries):
        base_output = self.base(queries)
        if not self.store:
            empty_mask = torch.zeros(
                queries.shape[0], dtype=torch.bool, device=queries.device
            )
            return base_output, empty_mask
        keys, values = map(torch.stack, zip(*self.store, strict=True))
        query_keys = self.base.key(queries)
        norms = query_keys.norm(dim=1, keepdim=True)
        nonzero = norms > 0
        query_keys = query_keys / norms.masked_fill(~nonzero, 1)
        similarity, selection = (query_keys @ keys.T).max(dim=1)
        applies = nonzero[:, 0] & (similarity >= self.threshold)
        output = torch.where(applies[:, None], values[selection], base_output)
        return output, applies
PythonIn [19]
CollapseExpand
mem_ed = MemoryEditor(base_model)
mem_ed.add_edit(x_edit, v_star)
mem_edit_out, edit_matched = mem_ed.route(x_edit)
mem_para_out, para_matched = mem_ed.route(paraphrases)
mem_unrel_out, unrelated_matched = mem_ed.route(unrelated)
mem_rel = F.cosine_similarity(mem_edit_out, v_star, dim=1).item()
mem_gen = (
    F.cosine_similarity(mem_para_out, v_star.expand_as(mem_para_out), dim=1)
    .mean()
    .item()
)
mem_drift = (mem_unrel_out - base_unrelated).norm(dim=1).mean().item()
editor_cosines = np.array([[rel, gen], [mem_rel, mem_gen]])
ConsoleOut [20]
CollapseExpand
Memory target cosine: direct 1.000, nearby 1.000
Matched nearby inputs: 8/8
Matched unrelated inputs: 0/199
Mean unrelated movement: weight 3.416, memory 0.000

In this run the wrapper matches all eight nearby inputs and none of the 199 controls. Its measured control drift is zero. The exact and nearby cosines happen to be equal to the displayed precision, since each matched row uses the same stored target value. This result depends on the query pool and the cosine threshold. A more similar control could pass the threshold and receive the replacement value even when the query should remain outside the edit.

Any query that takes the pass-through branch receives the base prediction for that row. This property holds even if the editor has unrelated records because the choice is made separately per row. It does not tell us whether the classifier chose the right branch. Check both expected matches and expected passes when tuning the threshold. Processing a mixed batch is also a useful test: it should keep the output shape and identity of each query while applying the correction only to matched rows.

The contrast plot

Compare the direct and nearby-input cosine scores on the same scale. The unrelated movement and routing counts remain in the printed output because they answer a different question and use different denominators or units.

VisualizationOut [21]
CollapseExpand
Two bar pairs compare direct and nearby-input cosine for the weight edit and the memory wrapper.
Cosine similarity to the requested value for the exact edit input and the eight nearby inputs. The left, solid bar shows the weight edit. The right, hatched bar shows the memory wrapper. Both start from the same base memory. Locality is measured separately as Euclidean movement.

Both editors reach the exact target on the direct input to the displayed precision. The weight edit's nearby mean is lower in this fixture; it has no separate rule that swaps their response for the target. The memory editor does perform that replacement when the scores exceed the threshold. This plot compares their behavior on these input vectors. It does not show that one route generalizes to arbitrary paraphrases or provides better scope in a different model.

A portability check (two-hop)

The portability check adds a fixed second transform from the retrieved value to a derived value. It implements an explicit composition of two lookups. We compare the original response, the weight edit and the memory wrapper on the direct subject and nearby inputs. Measure Euclidean error against the derived value obtained by applying that same transform to the requested first-hop target.

PythonIn [22]
CollapseExpand
rng = torch.Generator().manual_seed(SEED + 2)
downstream = torch.randn(D_VAL, D_VAL, generator=rng)
derived_target = v_star @ downstream
with torch.no_grad():
    pre_para = base_model(paraphrases)
    direct_hop = [old_val, edit_out, mem_edit_out]
    nearby_hop = [pre_para, para_out, mem_para_out]


def second_hop_error(first_hop_values):
    return (
        (first_hop_values @ downstream - derived_target)
        .norm(dim=1)
        .mean()
        .item()
    )


hop_results = [
    (second_hop_error(a), second_hop_error(b))
    for a, b in zip(direct_hop, nearby_hop, strict=True)
]
ConsoleOut [23]
CollapseExpand
          Base   direct 264   nearby mean 263
   Weight edit   direct 3.39e-05   nearby mean 30.1
Memory wrapper   direct 0   nearby mean 3.38e-06

The weight edit makes the direct first hop almost equal to the target. The downstream transform produces a direct error of roughly 3×10−53\times 10^{-5} in the run, while the memory wrapper returns exactly the provided first-hop value. The base direct error is about 264. The weight edit has larger error on nearby queries because their first-hop vectors differ from the target, and the downstream map operates on those different vectors. The exact direct constraint should therefore not be treated as a guarantee for neighboring inputs.

The second-hop error here is the first-hop error vector multiplied by a fixed matrix, so the matrix can amplify or reduce it. An actual reasoning query must discover or retrieve the right intermediate fact and then compose it with the next fact. MQuAKE supplies questions whose answers should change after an edit. The authors found cases where edited fact recall worked while this multi-hop evaluation remained difficult. Our constructed second lookup does not test that retrieval problem.

Target alignment across prompt groups

The final check distinguishes agreement with the requested correction from factual accuracy. The score averages cosine to the same target within each prompt group, then weights the direct and nearby groups equally. Pairwise cosine would measure how closely the outputs match each other. Verify which edit should be active and retain the source of the requested change. Report that check separately from the measurements of how the editor behaved.

PythonIn [24]
CollapseExpand
with torch.no_grad():
    direct = F.cosine_similarity(model(x_edit), v_star, dim=1).item()
    para_mean = (
        F.cosine_similarity(
            model(paraphrases), v_star.expand(n_para, D_VAL), dim=1
        )
        .mean()
        .item()
    )
target_alignment = 0.5 * (direct + para_mean)
ConsoleOut [25]
CollapseExpand
Group-weighted target alignment: 0.850
Verify the requested edit independently.

A memory record can carry an identifier and provenance. An engineer can inspect or deactivate that record and rerun the queries under the same model and sampling conditions. In a checkpoint-based workflow, document the edited version and the original version used for comparison. Both forms of provenance help when downstream tests reveal a mistake whose cause is unclear.

Keep the evaluation independent

Hold out phrasings from the examples used to choose the update. Include near-neighbor control queries and distinct relations of the same subject, as well as a broader capability check if it matters for the application. To test portability, specify which downstream answers should change when the edit becomes active. Running more prompts cannot establish a target's factual correctness if they share the same unverified premise.

Limitations and impact

A weight edit changes the checkpoint and can be served without consulting an additional edit store. The ability to satisfy a direct query is still only one test of the edited model. A memory editor adds routing and can turn off a correction without restoring the checkpoint. A matched query may still be outside the intended scope. In both cases, evaluate held-out phrasing and related controls before concluding that the edit is local.

An operational choice depends on the corrections you plan to make and which versions you can reliably recover. A memory store can log edits and make a specified correction easier to remove. Direct weight editing avoids an added serving lookup, but the values that changed inside the checkpoint are harder to inspect by reading the weights alone. Keep a measured baseline and a rollback path, then rerun the same test prompts after correction or rollback. Unlearning has a different objective, and removing a correction from a memory store is not evidence that data was removed from model parameters.

Incorrect edits can affect the answers that users receive. An auditable record should identify the requested replacement and its evidence, along with which model or memory version was tested. When several corrections interact, retest a query set containing affected facts and relations before claiming that behavior was preserved. For example, include a common subject with two distinct relations and an input about a neighboring subject that previously had the same object. Store expected behavior for both controls. A checkpoint or memory version that returns the requested new object on all three prompts has over-applied the correction even if it passes the direct edit test.

Causal tracing, controlled edits and behavior tests answer related but different questions. Tracing can identify responses sensitive to an internal intervention. A weight edit can change a model's answer under one evaluation. Generalization, locality and portability then test how far that change carries. The main lesson of this example is to preserve those distinctions when interpreting a successful edit.

Summary

Knowledge editing changes particular responses through a checkpoint update or an external correction. The edits should be assessed on direct prompts, held-out phrasing, unrelated controls and relevant downstream questions.

  • Linear update. A rank-one change can hit a desired value at one key while minimizing squared disturbance on a reference key distribution. It can still move other keys with nonzero projection on its input-side direction.
  • Many edits. Sequential exact writes can disturb earlier targets. MEMIT fits multiple associations jointly within each layer and uses an old-key preservation term.
  • Memory. A wrapper can keep the base weights untouched and route matching queries to a stored correction. Test misrouting independently of preservation on pass-through rows.
  • Evaluation. The toy compares both editors with the same input fixtures and starting checkpoint. Exact first-hop behavior in the toy's explicit composition is weaker evidence than successful natural-language multi-hop answering. Agreement with the edit target does not validate the target itself.

Later chapters apply related evaluation questions to changing facts, personalization, and the separate objective of unlearning.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about knowledge editing.

Knowledge Editing

Question 1 of 80 of 8 completed
Which property measures whether a model preserves answers on unrelated subjects and other relations of the same subject after an edit?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

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

Personalization and Long-Term Memory

Build application-layer memory for LLM assistants. Learn typed records, provenance, consent scopes, conflict resolution, and erasure across stores.

33 min read
Language AI Handbook · Vol. 15

Machine Unlearning

Learn how to assess a model after a training-data deletion request using fresh retraining, approximate updates, and release-specific evaluation.

40 min read
Language AI Handbook · Vol. 15

Evaluating Knowledge Interventions

Measure deliberate knowledge changes along five axes: efficacy, locality, generalization, side effects, and leakage. Build auditable evaluation harnesses.

40 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026knowledgeediting, author = {Michael Brenndoerfer}, title = {Knowledge Editing}, year = {2026}, url = {https://mbrenndoerfer.com/writing/knowledge-editing-language-models-rome-memit-serac}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Knowledge Editing. Retrieved from https://mbrenndoerfer.com/writing/knowledge-editing-language-models-rome-memit-serac
MLAAcademic
Michael Brenndoerfer. "Knowledge Editing." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/knowledge-editing-language-models-rome-memit-serac>.
CHICAGOAcademic
Michael Brenndoerfer. "Knowledge Editing." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/knowledge-editing-language-models-rome-memit-serac.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Knowledge Editing'. Available at: https://mbrenndoerfer.com/writing/knowledge-editing-language-models-rome-memit-serac (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Knowledge Editing. https://mbrenndoerfer.com/writing/knowledge-editing-language-models-rome-memit-serac
Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy