Algorithmresearch
SISA training
Also called sharded isolated sliced aggregated training.
Trains models on disjoint shards in slices with checkpoints, so that deleting a point needs retraining only one shard from one slice.
- Solves
- Machine unlearning
- Time
- O(E d n R) buildO(E d n R / S) delete
- Space
- O(S R d) extra
- Where
- E = the gradient steps per slice; R = the number of slices per shard; S = the number of shards; d = the dimension; n = the number of records
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lucas Bourtoule, Varun Chandrasekaran, Christopher A. Choquette Choo, Hengrui Jia, Adelin Travers, Baiwu Zhang, David Lie, Nicolas Papernot, 2021
SISA training (Sharded, Isolated, Sliced, Aggregated) is an exact method for machine unlearning that works with any learner. It splits the training data into disjoint shards and trains one model on each, in isolation; inside a shard it feeds the data in slices and saves a checkpoint after each slice; it predicts by a majority vote of the models. To delete a record, it retrains only the shard that holds it, starting from the checkpoint saved just before the record's slice. When training is deterministic, the result is bit for bit the model that training from scratch on the remaining data gives. Bourtoule et al. (2021) proposed it and measured unlearning speedups of 4.63 times on Purchase and 2.45 times on SVHN against retraining from scratch.
In plain words
Suppose a teacher grades with a panel of five judges, and each judge has read a different fifth of the old essays. If one author asks for an essay to be forgotten, only one judge has read it, so only that judge must start over. The other four keep what they know.
SISA goes one step further. Each judge reads their essays in batches and writes down what they knew after each batch. If the essay to forget was in batch three, the judge goes back to the notes from after batch two and rereads only batches three and later, without that essay.
The panel votes, so the final answer depends on all the judges, but each record touched only one of them.
The problem
Input. A dataset of records, a learner that can continue training from saved parameters, and later a sequence of deletion requests, each naming a record of .
Output. After each request, a predictor that equals the predictor of training from scratch on the records that remain, with less work than retraining. This is exact unlearning in the sense of Ginart et al. (2019); see machine unlearning.
What is compared. The reference is SISA training itself, run from scratch on with the same partition of the remaining records and the same learner. If each record's shard and slice is a fixed function of the record alone, such as a hash of its id, this is exactly for the learning algorithm = SISA training.
The algorithm
Shards are numbered and slices . runs steps of the base learner on the records from the parameters , and is the checkpoint of shard after slice .
SISA-TRAIN(D, S, R, E)- 1
split D into disjoint shards D_1..D_S, and each D_k into slices D_k1..D_kR - 2
for k = 1 to S do - 3
theta <- theta_0 ; C_k0 <- theta - 4
for r = 1 to R do - 5
theta <- TRAIN(theta, D_k1 + ... + D_kr, E) ; C_kr <- theta - 6
predict(x) = majority vote of the models C_1R, ..., C_SR on x SISA-DELETE(u)- 7
find the shard k and slice r with u in D_kr, and remove u from D_kr - 8
theta <- C_k,r-1 - 9
for t = r to R do theta <- TRAIN(theta, D_k1 + ... + D_kt, E) ; C_kt <- theta
Line L1 fixes the partition. In the code it is a seeded shuffle of the ids; a hash of each id also works. Lines L2 to L5 train each shard in isolation: slice is added to the slices before it, and training continues from the previous checkpoint. Line L6 aggregates by label vote; Bourtoule et al. use a majority vote of the labels. Lines L7 to L9 delete: only shard changes, and only its checkpoints from slice on.
The base learner in the code is logistic regression trained by full-batch gradient descent, with records in a fixed order inside each slice. Any learner works if TRAIN is a deterministic function of its start and its data.
Example
Twelve records, shards, slices of 2 records each, steps per slice. The cost is counted in per-record gradients.
| step | action | checkpoints written | cost |
|---|---|---|---|
| 1 | train shard 1: slice 1 (2 records), then slices 1 and 2 (4 records) | ||
| 2 | train shards 2 and 3 the same way | ||
| 3 | delete record in slice 2 of shard 2: start from , train on 3 records | ||
| 4 | delete record in slice 1 of shard 3: start from , train on 1, then 3 records |
Training costs . Each deletion costs or ; retraining all three shards from scratch after step 3 would cost . Over all 12 records the mean cost of one deletion is , which matches the formula in Complexity.
On a test input, say the three shards vote , so the prediction is . After step 3 only the vote of shard 2 can change.
Correctness
Theorem (exact unlearning, deterministic case). If TRAIN is a deterministic function of its start and of the ordered list of its records, then after any sequence of deletions every checkpoint , and so the predictor of line L6, is equal to the one that SISA-TRAIN computes from scratch on the remaining records with the same partition.
The invariant is that equals , the checkpoint that training from scratch on the current shard would give after slice , for every and . A deletion from changes the data of shard only in slices . So is unchanged for , and for the other shards; line L9 recomputes for by the same recursion . The full proof is in the proof file.
Randomized learners. If TRAIN uses randomness, give shard and slice its own seed that does not depend on the data. Then the same argument gives equality in distribution, the exact unlearning of Ginart et al.
Proof: SISA deletion gives exactly the checkpoints of training from scratch on the remaining recordsfull
Setting. A partition assigns each record a shard and a slice , fixed when the record enters and never changed. For a dataset write , listed in a fixed order that depends only on the records (in the code, by id), and for the concatenation of the first slices. TRAIN is a deterministic function of a start and an ordered list (with the step count fixed), and is a fixed start.
Training from scratch. For a dataset define, for each shard ,
Lines L2 to L5 of SISA-TRAIN set for all and : line L3 sets , and the loop of line L4 applies the recursion in the order , each time from the value just computed. The predictor of line L6 is a function of only.
Claim. Let and let be the dataset after deletions handled by SISA-DELETE. Then after the -th deletion, for all and .
Proof. By induction on . For it is the statement about SISA-TRAIN above.
Assume the claim for , and let the -th request delete , with and . Line L7 removes from , so . Because the partition and the order inside a slice depend only on each record, the slices of are those of except that is gone from slice , and the order of the other records there is unchanged.
Shards . for every , so by the recursion , which equals by the hypothesis. SISA-DELETE does not change these checkpoints.
Shard , slices . does not contain slice , so it is the same for both datasets, and by induction on from , . SISA-DELETE does not change these checkpoints; in particular .
Shard , slices . Line L8 sets . The loop of line L9 runs and keeps the invariant that, before the step for , . The step computes , because the slices it reads are the current ones, after the removal of ; by the recursion this is , which it stores in and keeps as the new .
So every checkpoint equals after the deletion, which completes the induction.
Consequence. The predictor after any sequence of deletions is the predictor that SISA-TRAIN computes from scratch on the remaining records with the same partition. If the partition of each record is a fixed function of that record alone, the partition of computed from scratch is the restriction of the partition of , so the result is exactly for = SISA-TRAIN, which is the exact unlearning of the problem page.
The deterministic hypothesis is needed. The proof uses only that TRAIN returns the same value on the same start and the same ordered list. If TRAIN draws random numbers, give each pair an independent seed that does not depend on the data; then each is a function of the data and the seeds, the same argument holds for each fixed value of the seeds, and the outputs are equal in distribution. In floating point, "the same value" means the same operations in the same order, which the code ensures by keeping the records of each slice sorted by id and by summing in that order; the tests check equality bit for bit.
Complexity
Let each shard hold records in equal slices of records, and let one step of TRAIN on records cost .
- Training. Shard trains on prefixes of records, which is gradients; over shards, , so time. Slicing costs about times the work of training each shard once on all its data with steps.
- One deletion. At worst the record is in slice 1, and the shard retrains on all prefixes: . For a record chosen uniformly, the mean cost (computed here for this model, and checked by the tests) is gradients. For large this is about a fraction of the cost of training all of SISA again.
- Space. checkpoints of numbers, so , beside the data, which must be kept for retraining.
Properties
- Exact. The result is the model of retraining, not an approximation, so no privacy budget or certificate is needed. A membership test after deletion cannot tell it from retraining, because it is retraining.
- Isolation. Each record affects one constituent model. The same structure gives a certificate against poisoning: with a fixed partition, changed records change at most votes (data poisoning, and deep partition aggregation of Levine and Feizi 2021).
- Online. Deletion requests are served one at a time as they come.
- Learner agnostic. Any learner with a deterministic, resumable training procedure works.
Variants and improvements
- No slicing (). Delete by retraining one shard from scratch, with checkpoints only.
- Distribution-aware sharding. Bourtoule et al. discuss placing records that are more likely to be deleted together in the same shards, so that fewer shards retrain.
- Batched requests. Collect requests and retrain each touched shard once from the earliest touched slice. requests spread uniformly hit shards in expectation, so the gain shrinks as grows past .
- Summation form. For learners that use only sums of per-record statistics, subtraction is exact in or time per request (machine unlearning); SISA is for learners without that structure.
When to use it
Use SISA when exact deletion is required, the learner has no closed form to update, and some loss of accuracy is acceptable. Each constituent model sees only records, so on hard tasks accuracy drops as grows; Bourtoule et al. report a small accuracy loss on ImageNet with a speedup of 1.36 times, and larger speedups on simpler tasks. Prefer the summation form when the learner allows it, and certified removal (Guo et al. 2020) when a bounded approximation is enough and a single model must be kept.
Pitfalls
- A partition that depends on the deleted record. If line L1 splits by position (the first records to shard 1, and so on), removing a record shifts the others to new shards, and the result of line L9 is no longer the model of training from scratch. Fix the shard and slice of each record by its id, by a seeded assignment kept from the start or by a hash.
- Order or seeds that depend on positions. Line L5 must see the records of each slice in a fixed order, and a stochastic learner must use seeds that do not depend on the data. Otherwise the deleted model and the retrained model differ even though both are valid.
- Restarting from the wrong checkpoint. Line L8 must take , the state before the slice that held the record. Taking keeps the influence of the record.
- Keeping the deleted record elsewhere. The training data, logs and other copies must be removed too; the method removes the record from the model only.
- Many shards on a hard task. Isolation is paid for in accuracy. Choose with a measured accuracy curve, not only by the deletion cost.
Implementations
The code runs only on synthetic blobs that the tests build from a fixed seed with mlkit. The tests check, bit for bit on 500 random instances with sequences of deletions, that every checkpoint after each deletion equals the checkpoint of an independent trainer run from scratch on the remaining records, and that the other shards are untouched. They also check that one shard with one slice is exactly the logistic regression of mlkit, the exact mean cost of a deletion against the formula above with fractions, and the vote and accuracy on blobs.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.
Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""
import math
import random
from typing import Callable, Sequence
Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]
def dot(u: Sequence[float], v: Sequence[float]) -> float:
"""Inner product of two vectors of the same length. Cost O(d)."""
return math.fsum(a * b for a, b in zip(u, v, strict=True))
def add(u: Sequence[float], v: Sequence[float]) -> Vector:
"""Coordinatewise sum u + v. Cost O(d)."""
return [a + b for a, b in zip(u, v, strict=True)]
def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
"""Coordinatewise difference u - v. Cost O(d)."""
return [a - b for a, b in zip(u, v, strict=True)]
def scale(c: float, v: Sequence[float]) -> Vector:
"""The vector c v. Cost O(d)."""
return [c * a for a in v]
def norm1(v: Sequence[float]) -> float:
"""The l1 norm, the sum of |v_i|. Cost O(d)."""
return math.fsum(abs(a) for a in v)
def norm2(v: Sequence[float]) -> float:
"""The Euclidean norm. Cost O(d)."""
return math.sqrt(math.fsum(a * a for a in v))
def norminf(v: Sequence[float]) -> float:
"""The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
return max((abs(a) for a in v), default=0.0)
def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
"""Euclidean projection of v onto the l2 ball of the given center and radius >= 0.
A point inside the ball is returned unchanged; a point outside is moved along the
segment to the center until it is on the sphere. Cost O(d).
"""
diff = sub(v, center)
r = norm2(diff)
if r <= radius:
return list(v)
return add(center, scale(radius / r, diff))
def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
"""Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]
def clip01(v: Sequence[float]) -> Vector:
"""Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
return [min(max(a, 0.0), 1.0) for a in v]
def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
"""n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).
Point i gets the label i mod len(centers) and is drawn around that center, so the
classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
"""
for c in centers:
if len(c) != d:
raise ValueError("each center must have d coordinates")
data: Data = []
for i in range(n):
label = i % len(centers)
x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
data.append((x, label))
return data
def sigmoid(t: float) -> float:
"""The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
if t >= 0:
return 1.0 / (1.0 + math.exp(-t))
e = math.exp(t)
return e / (1.0 + e)
def _softplus(t: float) -> float:
"""ln(1 + e^t) without overflow."""
return max(t, 0.0) + math.log1p(math.exp(-abs(t)))
def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
"""Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.
The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
"""
s = 2 * y - 1
return _softplus(-s * (dot(w, x) + b))
def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
"""Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
g = sigmoid(dot(w, x) + b) - y
return scale(g, w)
def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
"""Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
g = sigmoid(dot(w, x) + b) - y
return scale(g, x), g
def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
"""Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.
Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
The bias has no penalty. Returns (w, b). Cost O(steps n d).
"""
d = len(data[0][0])
n = len(data)
w = [0.0] * d
b = 0.0
for _ in range(steps):
gw = [0.0] * d
gb = 0.0
for x, y in data:
g = sigmoid(dot(w, x) + b) - y
for j in range(d):
gw[j] += g * x[j]
gb += g
w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
b -= lr * gb / n
return w, b
def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
"""A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.
The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
W2 (k rows of h) and b2 (k). Cost O(h d + k h).
"""
s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
return {
"W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
"b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
"W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
"b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
}
def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
"""Pre-activations and activations of the hidden layer."""
pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
return pre, [max(a, 0.0) for a in pre]
def forward(net: Net, x: Sequence[float]) -> Vector:
"""Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
_, act = _hidden(net, x)
return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
def argmax(z: Sequence[float]) -> int:
"""The first index of a largest entry. Cost O(k)."""
best = 0
for i in range(1, len(z)):
if z[i] > z[best]:
best = i
return best
def softmax(z: Sequence[float]) -> Vector:
"""The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
m = max(z)
e = [math.exp(a - m) for a in z]
s = math.fsum(e)
return [a / s for a in e]
def cross_entropy(z: Sequence[float], label: int) -> float:
"""Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
m = max(z)
return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]
def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
"""The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
Cost O(k h d).
"""
pre, _ = _hidden(net, x)
d = len(x)
rows = []
for w2 in net["W2"]:
row = [0.0] * d
for i, a in enumerate(pre):
if a > 0 and w2[i] != 0.0:
c = w2[i]
w1 = net["W1"][i]
for j in range(d):
row[j] += c * w1[j]
rows.append(row)
return rows
def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
"""Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
Cost O(h d + k h).
"""
pre, act = _hidden(net, x)
z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
p = softmax(z)
p[label] -= 1.0
back = [0.0] * len(pre)
for c, row in zip(p, net["W2"], strict=True):
for i in range(len(pre)):
back[i] += c * row[i]
g = [0.0] * len(x)
for i, a in enumerate(pre):
if a > 0:
w1 = net["W1"][i]
for j in range(len(x)):
g[j] += back[i] * w1[j]
return g
def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
"""Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
if not data:
return 0.0
return sum(1 for x, y in data if predict(x) == y) / len(data)
sisa_training.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sisa-training/. The authors are listed in prov/P6S600.jsonl.
"""SISA training of Bourtoule et al. (2021): sharded, isolated, sliced and aggregated training with exact deletion.
Each constituent model is a logistic regression trained by deterministic full-batch
gradient descent, so that deletion can be checked bit for bit against retraining. The
tests use synthetic blobs from mlkit with a fixed seed.
"""
import random
from dataclasses import dataclass, field
from typing import Sequence
import mlkit
Vector = list[float]
Record = tuple[Vector, int]
Params = tuple[Vector, float]
@dataclass
class Sisa:
"""The state of SISA: records by id, the ids of each slice of each shard, and the checkpoints.
slices[k][r] is the sorted list of ids in slice r of shard k. ckpt[k][r] is the model of
shard k after slice r, and ckpt[k][0] is the zero start. The cost counter adds one for
each record whose gradient is computed.
"""
records: dict[int, Record]
slices: list[list[list[int]]]
ckpt: list[list[Params]]
steps: int
lr: float
l2: float
cost: int = field(default=0)
def assign(ids: Sequence[int], shards: int, slices: int, seed: int) -> dict[int, tuple[int, int]]:
"""A fixed partition of the ids into shards and slices, from a seeded shuffle.
After the shuffle, the j-th id goes to shard j mod shards, and within its shard to the
slice given by its rank, in nearly equal runs. Cost O(N log N) for N ids.
"""
order = sorted(ids)
random.Random(seed).shuffle(order)
per_shard: list[list[int]] = [order[k::shards] for k in range(shards)]
out: dict[int, tuple[int, int]] = {}
for k, part in enumerate(per_shard):
for rank, i in enumerate(part):
out[i] = (k, rank * slices // max(len(part), 1))
return out
def gd_steps(start: Params, data: Sequence[Record], steps: int, lr: float, l2: float) -> tuple[Params, int]:
"""Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2, from start.
Returns the new parameters and the number of per-record gradients computed. An empty
data set leaves the parameters unchanged. Cost O(steps |data| d).
"""
w, b = list(start[0]), start[1]
n = len(data)
if n == 0:
return (w, b), 0
d = len(w)
for _ in range(steps):
gw = [0.0] * d
gb = 0.0
for x, y in data:
g = mlkit.sigmoid(mlkit.dot(w, x) + b) - y
for j in range(d):
gw[j] += g * x[j]
gb += g
w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
b -= lr * gb / n
return (w, b), steps * n
def _prefix(model: Sisa, k: int, r: int) -> list[Record]:
"""The records of slices 0..r of shard k, slice by slice and by id inside a slice."""
return [model.records[i] for t in range(r + 1) for i in model.slices[k][t]]
def sisa_train(
records: dict[int, Record], where: dict[int, tuple[int, int]], shards: int, slices: int, steps: int, lr: float, l2: float
) -> Sisa:
"""Train one model per shard, slice by slice, and keep a checkpoint after each slice.
Precondition: where maps every id of records to (shard, slice) with shard < shards and
slice < slices, and all records have the same dimension d. Cost O(steps d sum_k sum_r |prefix k r|),
which is O(steps d N R / 2) for N records in equal slices, and O(S R d) space for checkpoints.
"""
d = len(next(iter(records.values()))[0])
parts: list[list[list[int]]] = [[[] for _ in range(slices)] for _ in range(shards)]
for i in sorted(records): # @line L1
k, r = where[i]
parts[k][r].append(i)
model = Sisa(dict(records), parts, [], steps, lr, l2)
for k in range(shards): # @line L2
theta: Params = ([0.0] * d, 0.0) # @line L3
row = [theta]
for r in range(slices): # @line L4
theta, c = gd_steps(theta, _prefix(model, k, r), steps, lr, l2) # @line L5
model.cost += c
row.append(theta)
model.ckpt.append(row)
return model
def predict(model: Sisa, x: Sequence[float]) -> int:
"""Majority vote of the shard models on x, with a tie going to label 0. Cost O(S d)."""
votes = sum(1 for row in model.ckpt if mlkit.dot(row[-1][0], x) + row[-1][1] > 0) # @line L6
return 1 if 2 * votes > len(model.ckpt) else 0
def sisa_delete(model: Sisa, i: int) -> int:
"""Remove record i and retrain its shard from the checkpoint before its slice. Returns the cost.
Precondition: i is a record of the model. After the call the model equals sisa_train on
the remaining records with the same partition. Cost O(steps d sum_{t >= r} |prefix k t|)
for the shard k and slice r of i; the other shards are not touched.
"""
k, r = next((k, r) for k in range(len(model.slices)) for r in range(len(model.slices[k])) if i in model.slices[k][r]) # @line L7
model.slices[k][r].remove(i)
del model.records[i]
theta = model.ckpt[k][r] # @line L8
spent = 0
for t in range(r, len(model.slices[k])): # @line L9
theta, c = gd_steps(theta, _prefix(model, k, t), model.steps, model.lr, model.l2)
spent += c
model.ckpt[k][t + 1] = theta
model.cost += spent
return spent
test_sisa_training.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sisa-training/. The authors are listed in prov/P6S600.jsonl.
"""Tests of SISA on seeded synthetic data: deletion gives bit for bit the model of retraining from scratch."""
import copy
import random
from fractions import Fraction
import mlkit as m
from sisa_training import assign, gd_steps, predict, sisa_delete, sisa_train
def retrain_from_scratch(records, where, shards, slices, steps, lr, l2):
"""An independent trainer: for each shard, from zero, gradient steps on slices 0..r for r = 0, 1, ..."""
d = len(next(iter(records.values()))[0])
rows = []
for k in range(shards):
w, b = [0.0] * d, 0.0
row = [([0.0] * d, 0.0)]
for r in range(slices):
data = [records[i] for t in range(r + 1) for i in sorted(i for i in records if where[i] == (k, t))]
n = len(data)
for _ in range(steps if n else 0):
gw, gb = [0.0] * d, 0.0
for x, y in data:
g = m.sigmoid(m.dot(w, x) + b) - y
for j in range(d):
gw[j] += g * x[j]
gb += g
w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
b -= lr * gb / n
row.append((list(w), b))
rows.append(row)
return rows
def random_records(rng: random.Random, n: int, d: int) -> dict[int, tuple[list[float], int]]:
data = m.make_blobs(rng, n, d, [[-1.0] * d, [1.0] * d], 1.0)
ids = rng.sample(range(100), n)
return dict(zip(ids, data))
def test_partition_is_disjoint_and_balanced() -> None:
rng = random.Random(4101)
for _ in range(200):
n, s, r = rng.randint(1, 40), rng.randint(1, 4), rng.randint(1, 4)
ids = rng.sample(range(1000), n)
where = assign(ids, s, r, rng.randrange(10**6))
assert sorted(where) == sorted(ids)
sizes = [sum(1 for i in ids if where[i][0] == k) for k in range(s)]
assert max(sizes) - min(sizes) <= 1
for k in range(s):
sl = [sum(1 for i in ids if where[i] == (k, t)) for t in range(r)]
assert sum(sl) == sizes[k] and all(0 <= t < r for _, t in (where[i] for i in ids))
if sizes[k] >= r:
assert max(sl) - min(sl) <= 1
def test_one_shard_and_one_slice_is_plain_training() -> None:
rng = random.Random(4102)
recs = random_records(rng, 20, 3)
where = {i: (0, 0) for i in recs}
model = sisa_train(recs, where, 1, 1, 30, 0.5, 0.01)
data = [recs[i] for i in sorted(recs)]
w, b = m.train_logistic(data, 30, 0.5, 0.01)
assert model.ckpt[0][1] == (w, b)
def test_deletion_equals_retraining_from_scratch() -> None:
"""The theorem of the page, bit for bit, on 500 random instances and sequences of deletions."""
rng = random.Random(4103)
for _ in range(500):
n, d = rng.randint(4, 10), rng.randint(1, 3)
shards, slices, steps = rng.randint(1, 3), rng.randint(1, 3), rng.randint(1, 2)
lr, l2 = rng.choice([0.1, 0.5, 1.0]), rng.choice([0.0, 0.01])
recs = random_records(rng, n, d)
where = assign(list(recs), shards, slices, rng.randrange(10**6))
model = sisa_train(recs, where, shards, slices, steps, lr, l2)
assert model.ckpt == retrain_from_scratch(recs, where, shards, slices, steps, lr, l2)
left = dict(recs)
for victim in rng.sample(sorted(recs), rng.randint(1, min(3, n - 1))):
k, r = where[victim]
before = copy.deepcopy(model.ckpt)
sisa_delete(model, victim)
del left[victim]
assert model.ckpt == retrain_from_scratch(left, where, shards, slices, steps, lr, l2)
# the other shards and the checkpoints up to slice r are untouched
for kk in range(shards):
if kk != k:
assert model.ckpt[kk] == before[kk]
assert model.ckpt[k][: r + 1] == before[k][: r + 1]
def test_average_cost_of_a_deletion() -> None:
"""With S shards of R slices of m records each, the mean cost is E (R + 1) (m (2R + 1) - 3) / 6."""
rng = random.Random(4104)
for shards, slices, size, steps in [(1, 1, 3, 2), (2, 3, 2, 1), (3, 2, 4, 2), (2, 4, 3, 1)]:
n = shards * slices * size
recs = random_records(rng, n, 2)
where = assign(list(recs), shards, slices, 7)
model = sisa_train(recs, where, shards, slices, steps, 0.5, 0.0)
assert model.cost == shards * steps * size * slices * (slices + 1) // 2
total = 0
for victim in recs:
fresh = sisa_train(recs, where, shards, slices, steps, 0.5, 0.0)
total += sisa_delete(fresh, victim)
mean = Fraction(total, n)
assert mean == Fraction(steps * (slices + 1) * (size * (2 * slices + 1) - 3), 6)
def test_vote_and_accuracy_on_blobs() -> None:
rng = random.Random(4105)
recs = random_records(rng, 60, 2)
test = m.make_blobs(rng, 200, 2, [[-1.0, -1.0], [1.0, 1.0]], 1.0)
where = assign(list(recs), 3, 2, 11)
model = sisa_train(recs, where, 3, 2, 40, 0.5, 0.01)
for x, _ in test[:50]:
votes = [1 if m.dot(row[-1][0], x) + row[-1][1] > 0 else 0 for row in model.ckpt]
assert predict(model, x) == (1 if sum(votes) >= 2 else 0)
assert m.accuracy(lambda x: predict(model, x), test) >= 0.85
for victim in sorted(recs)[:10]:
sisa_delete(model, victim)
assert m.accuracy(lambda x: predict(model, x), test) >= 0.85
def test_gradient_steps_on_empty_data_do_nothing() -> None:
start = ([0.5, -1.0], 0.25)
assert gd_steps(start, [], 10, 0.5, 0.1) == (([0.5, -1.0], 0.25), 0)
History
Cao and Yang (2015) posed machine unlearning and solved it exactly for learners in summation form. Ginart et al. (2019) defined exact deletion and gave deletion-efficient k-means. Bourtoule et al. (2019 on arXiv, IEEE S&P 2021) gave SISA, the first exact method for any learner, including deep networks, based on partitioning and checkpoints. The same partition and vote gives the poisoning certificate of deep partition aggregation (Levine and Feizi 2021).
References
- Lucas Bourtoule, Varun Chandrasekaran, Christopher A. Choquette-Choo, Hengrui Jia, Adelin Travers, Baiwu Zhang, David Lie and Nicolas Papernot, Machine unlearning, IEEE Symposium on Security and Privacy 2021, pages 141 to 159, arXiv:1912.03817, the SISA design (sharding, isolation, slicing, aggregation), the checkpoints at slice boundaries, the analysis of the retraining time, and the measured speedups on Purchase, SVHN and ImageNet
- Yinzhi Cao and Junfeng Yang, Towards making systems forget with machine unlearning, IEEE Symposium on Security and Privacy 2015, pages 463 to 480, unlearning by the summation form, the earlier exact method for statistical query learners
- Antonio Ginart, Melody Y. Guan, Gregory Valiant and James Zou, Making AI forget you, data deletion in machine learning, Advances in Neural Information Processing Systems 32 (NeurIPS) 2019, arXiv:1907.05012, the definition of exact deletion as equality in distribution with retraining
- Alexander Levine and Soheil Feizi, Deep partition aggregation, provable defense against general poisoning attacks, International Conference on Learning Representations (ICLR) 2021, the same partition and vote used for a certificate against poisoning, with a partition fixed by a hash of each record
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag P6S600 Edit this page History Report an error Markdown