Knowledge Editing › Implementation
Language AI HandbookAll chapters 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]Expand
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]Expand
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]Expand
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 . 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]Expand
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]Expand
@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 from 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 still enforces the target on the edit key in exact arithmetic. The next cell checks the edited value against the target with absolute tolerance and relative tolerance . 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]Expand
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]Expand
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]Expand
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]Expand
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_KEYandD_VALspecify 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_FACTSis the number of subjects in the base-fit pool and in the empirical key-moment calculation. It leavesN_FACTS - 1controls in the single-edit comparison.ridgeis 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_countsindexes 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]Expand

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]Expand
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, appliesPythonIn [19]Expand
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]Expand
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]Expand

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]Expand
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]Expand
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 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]Expand
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]Expand
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.
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.
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!