Machine Unlearning › A Worked Example: Unlearning a Class From a Small Classifier
Language AI HandbookAll chapters We train a small neural network on three labeled groups of points. In the first case, class 0 sits mostly to the left, and classes 1 and 2 lie on the right. We keep the architecture fixed and train on the two retained classes to obtain the comparator. The network predicts a class label. The example has no text generation or text extraction.
Setup
The hidden plot setup seeds the plotting runtime. Each plotting cell applies the style before drawing. The visible example uses its own NumPy generator and seeds PyTorch before constructing each model.
PythonIn [3]Expand
import copy
import numpy as np
import torch
from torch import nn
SEED = 0
rng = np.random.default_rng(SEED)
torch.set_num_threads(1)The training set contains 400 forget points and 500 points from each retained class. In each cluster, the two coordinates are drawn independently from normal distributions with the specified means and common standard deviation.
PythonIn [4]Expand
def make_cluster(generator, center, scale, count, label):
features = generator.normal(loc=center, scale=scale, size=(count, 2))
labels = np.full(count, label, dtype=np.int64)
return features.astype(np.float32), labels
X_forget, y_forget = make_cluster(rng, (-2.0, 0.0), 0.9, 400, 0)
X_ret_a, y_ret_a = make_cluster(rng, (2.0, 1.0), 0.9, 500, 1)
X_ret_b, y_ret_b = make_cluster(rng, (2.0, -1.0), 0.9, 500, 2)
X_ret = np.vstack([X_ret_a, X_ret_b])
y_ret = np.concatenate([y_ret_a, y_ret_b])
X_all = np.vstack([X_forget, X_ret])
y_all = np.concatenate([y_forget, y_ret])VisualizationOut [5]Expand

The two retained classes have a broader overlap with each other than with the forget cluster in this draw. The hard case will put additional retained points near the forget cluster to study a different geometry.
This is a complete deletion of a named class in the training set. The deleted cluster remains available to the experimenter so we can compute the gradient update and compare outputs on the deleted training points. A real request might restrict future access to those points. In that scenario, a post-hoc update that consumes the deleted examples has to run while the data are available within its permitted scope, or the system has to use an algorithm that takes different inputs.
The generator uses a fresh draw for each cohort. Even when the distribution parameters match, training and probe arrays are different observations. Comparing a model to the labels it saw during training measures fit to that cohort. Measuring performance on new points isolates generalization to the chosen population more directly. Both can be useful if the report specifies which row comes from which split.
Defining the Model and Training
The model has two inputs, a 16-unit hidden layer with a tanh activation and three output logits. We train from the same initialization in both runs. Full-batch Adam takes 200 steps with a learning rate of 0.05 and weight decay of 0.001. The fresh retrain differs in the training rows it receives.
PythonIn [6]Expand
class TinyClassifier(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(2, 16), nn.Tanh(), nn.Linear(16, 3))
def forward(self, features):
return self.net(features)
def train_model(features, labels):
torch.manual_seed(SEED)
model = TinyClassifier()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05, weight_decay=1e-3)
X, y = torch.from_numpy(features), torch.from_numpy(labels)
for _ in range(200):
optimizer.zero_grad()
loss = nn.functional.cross_entropy(model(X), y)
loss.backward()
optimizer.step()
return model
model_orig = train_model(X_all, y_all)
model_retrain = train_model(X_ret, y_ret)Both networks keep the class-0 logit. With no class-0 labels in , the fresh retrain gets no examples telling it to raise that logit. The logit still enters the softmax denominator in cross-entropy for retained examples and receives gradients from those examples.
Why Keep Three Output Logits?
Removing records from the dataset leaves the training recipe unchanged in this comparison, including the output shape. For a point with label and model logits , cross-entropy equals . Since is 1 or 2 on the retained set, the derivative of that expression with respect to is the class-0 softmax probability. It falls out of the derivative of the log-sum; the term contributes zero for this coordinate.
This is a statement about the loss at retained inputs. Parameters jointly affect many inputs, so the derivative does not determine which class wins on a distant probe. Forcing the model never to emit class 0 by removing the output or by masking its logit would serve a different release specification. Keeping the logit preserves the training comparison and makes extrapolation visible.
The Exact Comparator as the Evaluation Anchor
We use 300 fresh points per class. Forget accuracy is the fraction of forget probes assigned the original class-0 label. Retain accuracy measures correct class-1 and class-2 predictions on the two pooled, equal-sized retained cohorts. Argmax disagreement compares a model's predicted labels with those of the fresh retrain on the forget probes. A model can stop predicting class 0 and still disagree with the retrain about whether a point belongs to class 1 or 2.
PythonIn [7]Expand
X_forget_probe, y_forget_probe = make_cluster(rng, (-2.0, 0.0), 0.9, 300, 0)
X_ret_a_probe, y_ret_a_probe = make_cluster(rng, (2.0, 1.0), 0.9, 300, 1)
X_ret_b_probe, y_ret_b_probe = make_cluster(rng, (2.0, -1.0), 0.9, 300, 2)
X_ret_probe = np.vstack([X_ret_a_probe, X_ret_b_probe])
y_ret_probe = np.concatenate([y_ret_a_probe, y_ret_b_probe])
def predict(model, features):
with torch.no_grad():
return model(torch.from_numpy(features)).argmax(dim=1).numpy()
def accuracy(model, features, labels):
return float((predict(model, features) == labels).mean())
def forget_disagreement(model, reference):
return float(
(
predict(model, X_forget_probe) != predict(reference, X_forget_probe)
).mean()
)
def behavior_metrics(model, reference):
return (
accuracy(model, X_forget_probe, y_forget_probe),
accuracy(model, X_ret_probe, y_ret_probe),
forget_disagreement(model, reference),
)
def print_behavior(name, values):
forget, retain, disagree = values
print(
f"{name:>12} | forget acc {forget:.3f} | retain acc {retain:.3f} | disagreement {disagree:.3f}"
)
baseline_metrics = {
"Original": behavior_metrics(model_orig, model_retrain),
"Retrain": behavior_metrics(model_retrain, model_retrain),
}ConsoleOut [8]Expand
Original | forget acc 0.967 | retain acc 0.865 | disagreement 0.800
Retrain | forget acc 0.167 | retain acc 0.868 | disagreement 0.000The fresh retrain predicts class 0 on about 17% of the held-out forget points, despite having received no positive class-0 labels. The retained examples penalize class 0 on the inputs the model sees during training, while the forget probes mostly lie outside that cloud. The retrain's disagreement with itself is exactly zero by construction. That number places no bound on disagreement between independently seeded retrains.
VisualizationOut [9]Expand

All three comparisons use fractions of held-out points. Disagreement is restricted to predicted labels on the forget-probe distribution. For example, two models can have identical labels on these probes and assign different probabilities to every class.
Our reference numbers describe 300 forget probes and 600 retain probes. Reporting both denominators matters. Argmax disagreement includes any difference in predicted class. In particular, disagreement can arise even when the two models both fail to predict class 0. If all retained and forget scores were combined into one average, changing the number of points in either cohort would change that pooled average even if the within-cohort results stayed fixed.
The two Gaussian populations on the right share the retained evaluation. This experiment gives each class equal weight in the probe count. An operational evaluation may instead weight accuracy by production traffic, give rare tasks dedicated rows, or estimate a separate success rate by cohort. The split and weighting should follow the intended use. An evaluation aimed at a class-removal request can give the low-volume forget cohort its own metric regardless of its deployment frequency.
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!