Evaluating Knowledge Interventions › Building a knowledge-intervention evaluation harness
Language AI HandbookAll chapters The notebook uses a small CPU-only knowledge store to illustrate individual measures. The suppression and overwrite examples explicitly simulate their failure modes.
The design separates two layers:
- A knowledge base (subject, relation, object) and a function that answers queries by lookup with a controllable "edit" applied.
- An evaluation engine that, given edit specifications and slice definitions, produces per-axis metrics with uncertainty.
The harness separates the expected answers from the model's responses. A real adapter around a decoder also needs tokenization, generation, scoring and error handling. The dictionary approximation isolates the evaluation logic.
PythonIn [2]Expand
import hashlib
import random
from collections import defaultdict
from dataclasses import dataclass, field
import matplotlib.pyplot as plt
import numpy as npWe define a fact as a triple with a relation, and we define query templates per relation so we can generate paraphrases deterministically.
PythonIn [4]Expand
@dataclass(frozen=True)
class Fact:
subject: str
relation: str
obj: str
# A tiny knowledge base. Each (subject, relation) maps to one object,
# mirroring how a factual probe expects a single answer.
KB = {
Fact("The Night Orchard", "author", "Mara Vale"),
Fact("The Night Orchard", "publication_year", "1969"),
Fact("Harbor Bells", "author", "Mara Vale"),
Fact("The Copper River", "author", "Jonah Reed"),
Fact("The Salt Map", "author", "Iris Chen"),
Fact("The Salt Map", "publication_year", "1965"),
Fact("Tide Atlas", "publication_year", "1984"),
Fact("Tide Atlas", "author", "Cyrus Bell"),
}
# Paraphrase templates per relation. The first is the "canonical" edit surface;
# the rest are held-out paraphrases for generalization testing.
TEMPLATES = {
"author": [
"Who wrote {s}?",
"Who is the author of {s}?",
"{s} was written by whom?",
"Name the author of {s}.",
],
"publication_year": [
"When was {s} published?",
"In what year was {s} published?",
"What is the publication year of {s}?",
],
}The knowledge base is a set of facts as the model knows them. We now simulate a model as a lookup that also carries a per-fact answer distribution. Real models are probabilistic over answers; we model that with a small softmax over candidate answers so we can demonstrate confidence and sampling.
A language model predicts a token distribution at each generation step. The probability of a multi-token candidate under that model involves successive token probabilities. The toy works directly with a small set of whole answers.
PythonIn [5]Expand
class ToyKnowledgeModel:
"""A legible stand-in for an LLM's parametric knowledge.
For each (subject, relation) we hold a dict over candidate objects with
weights; querying returns a full distribution and a greedy answer.
An "edit" replaces the candidate set for one query with a new answer.
"""
def __init__(self, kb, templates, temperature=0.0, seed=0):
self.templates = templates
self.temperature = temperature
self.rng = random.Random(seed)
# dist[(subject, relation)] -> {obj: weight}
self.dist = defaultdict(dict)
for fact in kb:
key = (fact.subject, fact.relation)
self.dist[key][fact.obj] = 4.0
# add small mass on plausible confusions so probabilities are not 1.0
self._add_confusions()
def _add_confusions(self):
authors = [
"Mara Vale",
"Jonah Reed",
"Iris Chen",
"Cyrus Bell",
"Nadia Wu",
]
years = ["1965", "1969", "1974", "1984"]
for key, d in self.dist.items():
pool = authors if key[1] == "author" else years
for cand in pool:
if cand in d:
continue
d[cand] = 0.4
def _softmax(self, weights):
w = np.array(list(weights.values()), dtype=float)
# Use unit-temperature scores for analysis when decoding is greedy.
temperature = self.temperature if self.temperature > 0 else 1.0
z = w / temperature
z = z - z.max()
p = np.exp(z)
p = p / p.sum()
return dict(zip(weights.keys(), p))
def answer_distribution(self, subject, relation):
key = (subject, relation)
if key not in self.dist:
return {}
return self._softmax(self.dist[key])
def edit(self, subject, relation, new_obj, strength=6.0):
"""Simulate a successful rewrite: boost new_obj heavily."""
key = (subject, relation)
d = self.dist.setdefault(key, {})
d[new_obj] = strength
for obj in list(d):
if obj != new_obj:
d[obj] = min(d[obj], 0.2)The toy defines an edit surface and held-out paraphrases. Its two locality slices check the same subject with another relation and other subjects with the same relation.
PythonIn [6]Expand
def render(template, subject):
return template.format(s=subject)
def build_slice(slice_name, query_specs):
"""query_specs: list of (subject, relation, template_index, expected_obj)."""
items = []
for subject, relation, t_idx, expected in query_specs:
prompt = render(TEMPLATES[relation][t_idx], subject)
items.append(
{
"slice": slice_name,
"prompt": prompt,
"subject": subject,
"relation": relation,
"template_index": t_idx,
"expected": expected,
}
)
return itemsThe scoring function accepts an item and returns the model's answer distribution and its highest-probability answer. Here the item carries a known subject and relation, so this call bypasses text understanding.
PythonIn [7]Expand
def query(model, item):
"""Return answer distribution and greedy answer for a prompt item."""
dist = model.answer_distribution(item["subject"], item["relation"])
if not dist:
return {}, None
greedy = max(dist, key=dist.get)
return dist, greedyNow we construct the evaluation. Given a set of edits and a battery of slices, we compute per-slice metrics. The key correctness move is that expected answers are computed from a reference knowledge state (the KB with the intended edits applied), not from the model itself. This prevents the circularity of grading the model against itself.
PythonIn [8]Expand
def apply_edits_to_reference(kb_facts, edits):
"""Return a dict (subject, relation)->expected object after edits."""
ref = {(f.subject, f.relation): f.obj for f in kb_facts}
for e in edits:
ref[(e["subject"], e["relation"])] = e["new_obj"]
return ref
def make_edit_surface(edits):
items = []
for e in edits:
items += build_slice(
"edit_surface",
[
(e["subject"], e["relation"], 0, e["new_obj"]),
],
)
return items
def make_paraphrase_slice(edits):
items = []
for e in edits:
for t in range(1, len(TEMPLATES[e["relation"]])):
items += build_slice(
"paraphrase",
[
(e["subject"], e["relation"], t, e["new_obj"]),
],
)
return items
def make_distinct_slice(edits, kb_facts):
"""Other facts about the same subject, expected to be preserved."""
edited_subjects = {(e["subject"], e["relation"]) for e in edits}
items = []
for f in kb_facts:
if (
f.subject in {e["subject"] for e in edits}
and (f.subject, f.relation) not in edited_subjects
):
items += build_slice(
"distinct",
[
(f.subject, f.relation, 0, f.obj),
],
)
return items
def make_same_relation_slice(edits, kb_facts):
"""Same relation, different subject: preserve the original fact."""
edited = {(e["subject"], e["relation"]) for e in edits}
edited_subjects = {subject for subject, _ in edited}
edited_relations = {relation for _, relation in edited}
items = []
for f in kb_facts:
if f.subject not in edited_subjects and f.relation in edited_relations:
items += build_slice(
"same_relation",
[
(f.subject, f.relation, 0, f.obj),
],
)
return itemsWe add a two-fact composition to the notebook. The corresponding multiple-choice direct question is an example of reformulation and does not enter the composition score.
PythonIn [9]Expand
COMPOSITION_QUESTION = (
"Did the author of The Night Orchard also write The Copper River?"
)
def make_compositional_slice(reference):
"""Build one held-out question about the relationship between two facts."""
first = reference[("The Night Orchard", "author")]
second = reference[("The Copper River", "author")]
return [
{
"slice": "compositional",
"prompt": COMPOSITION_QUESTION,
"expected": "yes" if first == second else "no",
}
]We strip outer whitespace and compare answers case-insensitively. We use that same equivalence to group candidates before computing a target probability and a margin. The margin subtracts the highest competing class probability from the target's probability. Greedy decoding still selects one raw string. For example, target aliases at 0.30 and 0.25 have a positive grouped margin against a competing string at 0.45, even though the raw greedy choice is the competitor. The resolved yes/no question has no estimated margin.
PythonIn [10]Expand
def match(answer, expected):
if answer is None:
return False
return answer.strip().casefold() == expected.strip().casefold()
def score_items(model, items):
results = []
for item in items:
dist, greedy = query(model, item)
correct = match(greedy, item["expected"])
by_answer = defaultdict(float)
for answer, probability in dist.items():
by_answer[answer.strip().casefold()] += probability
target = item["expected"].strip().casefold()
target_probability = by_answer.pop(target, 0.0)
margin = (
target_probability - max(by_answer.values(), default=0.0)
if dist
else float("nan")
)
results.append(
{
**item,
"answer": greedy,
"correct": correct,
"target_probability": target_probability
if dist
else float("nan"),
"margin": margin,
}
)
return resultsThe compositional probe as written compares strings from the model against a yes/no string, but our toy model answers via lookup and cannot answer yes/no directly. To keep the toy faithful, we implement compositional answering in the harness by consulting the model's distributions for the underlying facts. This is honest: in a real harness you would prompt the model and parse its answer; either way the composition logic is explicit and not hidden in the model.
PythonIn [11]Expand
def answer_compositional(model, prompt):
"""Combine two model lookups for the declared composition probe."""
if prompt != COMPOSITION_QUESTION:
return None
first = model.answer_distribution("The Night Orchard", "author")
second = model.answer_distribution("The Copper River", "author")
if not first or not second:
return None
return (
"yes"
if max(first, key=first.get) == max(second, key=second.get)
else "no"
)We are now ready to run a full evaluation. We define one edit, apply it to the model and the reference, build all slices, score them, and aggregate.
PythonIn [12]Expand
random.seed(0)
facts = sorted(KB, key=lambda fact: (fact.subject, fact.relation, fact.obj))
model = ToyKnowledgeModel(KB, TEMPLATES, temperature=0.0, seed=0)
edit = {
"subject": "The Night Orchard",
"relation": "author",
"old_obj": "Mara Vale",
"new_obj": "Jonah Reed",
}
edits = [edit]
# Apply the edit to the model and to the reference knowledge state.
model.edit(edit["subject"], edit["relation"], edit["new_obj"])
reference = apply_edits_to_reference(facts, edits)
edit_surface = make_edit_surface(edits)
paraphrases = make_paraphrase_slice(edits)
distinct = make_distinct_slice(edits, facts)
same_rel = make_same_relation_slice(edits, facts)
compositional = make_compositional_slice(reference)We score the lookup-based slices. The compositional slice needs the special resolver, so we handle it separately and merge.
PythonIn [13]Expand
all_results = []
all_results += score_items(model, edit_surface)
# Evaluate the same model responses for every lookup slice.
all_results += score_items(model, paraphrases)
all_results += score_items(model, distinct)
all_results += score_items(model, same_rel)
# Compositional handled via the explicit resolver.
for item in compositional:
answer = answer_compositional(model, item["prompt"])
all_results.append(
{
**item,
"answer": answer,
"correct": match(answer, item["expected"]),
"margin": float(
"nan"
), # no full answer distribution for this resolver
}
)Summarize the count and empirical accuracy of each slice. The table illustrates Wilson bounds under a binomial working model.
PythonIn [14]Expand
def wilson_interval(correct, n, z=1.96):
if n == 0:
return (float("nan"), float("nan"))
p = correct / n
denom = 1 + z**2 / n
center = (p + z**2 / (2 * n)) / denom
half = (z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2))) / denom
return (max(0.0, center - half), min(1.0, center + half))
def summarize(results):
summary = {}
for name in [
"edit_surface",
"paraphrase",
"distinct",
"same_relation",
"compositional",
]:
rows = [r for r in results if r["slice"] == name]
n = len(rows)
c = sum(r["correct"] for r in rows)
lo, hi = wilson_interval(c, n)
summary[name] = {
"n": n,
"correct": c,
"acc": c / n if n else float("nan"),
"ci_lo": lo,
"ci_hi": hi,
}
return summary
summary = summarize(all_results)ConsoleOut [15]Expand
slice n acc 95% CI edit_surface 1 1.00 [0.21, 1.00] paraphrase 3 1.00 [0.44, 1.00] distinct 1 1.00 [0.21, 1.00] same_relation 4 1.00 [0.51, 1.00] compositional 1 1.00 [0.21, 1.00] Direct target p=0.988, margin=0.985
The direct prompt and each paraphrase reach the same lookup. The publication-year control shares the edited subject and retains its answer. The same-relation controls cover other books. The single composition probe uses two author lookups and does not measure independent language-model reasoning.
Wilson intervals stay inside the unit interval. Here they illustrate how uncertain a binomial estimate can be at small sample sizes. The toy prompts are fixed, and some reuse the same underlying fact, so these intervals do not justify population inference. In a comparative study, use a paired interval for the difference and group related prompts by fact where appropriate.
Do not conclude from this run that knowledge editing is easy. The toy has zero representational coupling: editing one lookup cannot affect another. Real transformer edits act on shared hidden states and shared weights, so the interesting question is whether the slices reveal coupling. Our harness is valuable precisely because it defines the slices; plug in a real model and the same code catches real interference.
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!