Lesson 02 · 40 minutes
Poison the training data and detect it
- Poison one class by flipping labels and by adding bad images, at several rates
- Detect the poison with an accuracy gate and a per-class gate on a trusted set
- Say from your own table what rate hurts, and why a quiet attack slips past a gate that compares with last week
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Northgate Parcels retrains its digit reader every week on the labels that its staff confirm. A temporary worker had access to the label tool for a month. Your lead asks: "Could that worker have changed what the model reads, and would our release check have seen it?" You repeat the attack on your own copy of the model at different rates, and look for the smallest rate that your checks can see.
Recall
Lesson 1: which digit is the weakest in the baseline, and what is its recall?
The 8, with a recall of 0.84. This matters here, because a clean model already misses some 8s, and a poisoned model must be compared with this baseline and not with a perfect score.
Lesson 1: what does record() do, and where do the values go?
It writes one value under one key into results.json. Every lesson of the course adds its numbers to this one file.
The idea
Data poisoning changes the training data so that the model learns something wrong. The attacker needs write access to the data, to the labels, or to a source that feeds them. "AI security fundamentals" (lesson 2) flips one class once. This lesson asks how much poison is needed, and what finds it. There are three forms:
| Form | What the attacker does |
|---|---|
| Flip | Changes the label of images that are already in the data |
| Inject | Adds new images with wrong labels |
| Skew | Adds a little in each retraining, so that no single step looks large |
The defence is to measure the model on a trusted set: labelled images that the attacker cannot touch. Two gates read that measurement. The accuracy gate fails when the overall accuracy falls too far below the baseline. The class gate (the per-class check) fails when any class has a recall under a floor. A gate fails a release; a person then looks.
- Temp worker → Training data: flips or adds wrong labels
- Training data → Model: weekly retraining
- Trusted set → Gates: images the attacker cannot touch
- Model → Gates: accuracy, recall; a fail blocks release
Worked example
1. Write the attacks and the gates
New words in the code:
np.random.default_rng(seed)makes a random number generator with a fixed start, so that the same seed gives the same choice on every machine.rng.choice(positions, n, replace=False)picksndifferent positions at random, and withreplace=Trueit may pick the same one twice.np.flatnonzero(y == 8)gives the positions where the condition holds.np.vstackputs arrays on top of each other,np.concatenatejoins two lists, andnp.full(n, 3)makesncopies of the number 3.setdefaultwrites a dictionary key only when it is not there yet.f(*pair)passes the items ofpairas separate arguments.injectreturns two arrays, sotrain(*inject(...))callstrainwith those two arrays.
Settings: the numbers ACC_DROP and RECALL_FLOOR are your policy: the accuracy gate allows a fall of 0.02 and the class gate demands a recall of 0.80. Each attack is repeated with five seeds (five different choices of the images that change), because a number from one seed is a measurement and not a result. A row shows the mean, and in how many of the five runs each gate fails. A rate counts as "caught" when the class gate fails in at least 3 of the 5.
poison.py
"""poison.py: two ways to poison the labels of one class, and two gates that look for it."""
import numpy as np
from common import digits, recalls, record, train
ACC_DROP = 0.02 # the accuracy gate fails when accuracy falls more than this below the baseline
RECALL_FLOOR = 0.80 # the class gate fails when any digit has a recall below this
def flip_labels(y, source, target, rate, seed=0):
"""Change the label of a share `rate` of the examples of class `source` to `target`."""
rng = np.random.default_rng(seed)
chosen = rng.choice(np.flatnonzero(y == source), round((y == source).sum() * rate), replace=False)
out = y.copy()
out[chosen] = target
return out
def inject(X, y, source, target, count, seed=0):
"""Add `count` copies of images of class `source`, each with the label `target`."""
rng = np.random.default_rng(seed)
copies = rng.choice(np.flatnonzero(y == source), count, replace=True)
return np.vstack([X, X[copies]]), np.concatenate([y, np.full(count, target)])
def gates(model, X_val, y_val, baseline):
"""Two checks on trusted data. Return (accuracy gate passes, class gate passes)."""
return model.score(X_val, y_val) >= baseline - ACC_DROP, recalls(model, X_val, y_val).min() >= RECALL_FLOOR
def row(label, changed, models, X_val, y_val, baseline):
"""Print the mean of the runs and in how many of them each gate fails. Return the runs where the class gate fails."""
verdicts = [gates(m, X_val, y_val, baseline) for m in models]
acc_fails, class_fails = (sum(not v[i] for v in verdicts) for i in (0, 1))
mean_acc = np.mean([m.score(X_val, y_val) for m in models])
mean_recall = np.mean([recalls(m, X_val, y_val)[8] for m in models])
print(f"{label:<9}{changed:>8}{mean_acc:>10.2f}{mean_recall:>10.2f}{acc_fails:>10} of 5{class_fails:>10} of 5")
return class_fails
if __name__ == "__main__":
X_train, X_val, y_train, y_val = digits() # X_val is the trusted set: the attacker cannot reach it
baseline = train(X_train, y_train).score(X_val, y_val)
print("baseline accuracy", round(baseline, 4), " attack: label 8 becomes 3, mean of 5 seeds in each row")
print("what changed accuracy recall 8 acc.gate fails class.gate fails")
caught = {}
for rate in (0.1, 0.2, 0.3, 0.5, 1.0):
models = [train(X_train, flip_labels(y_train, 8, 3, rate, seed)) for seed in range(5)]
changed = int((flip_labels(y_train, 8, 3, rate) != y_train).sum())
if row(f"flip {rate:.0%}", changed, models, X_val, y_val, baseline) >= 3: # most of the 5 runs
caught.setdefault("flip", rate)
for count in (65, 131, 262, 524):
models = [train(*inject(X_train, y_train, 8, 3, count, seed)) for seed in range(5)]
if row(f"add {count}", count, models, X_val, y_val, baseline) >= 3:
caught.setdefault("add", count)
record("poison.class_gate_first_fail", caught)
print("skewing: the attacker adds 20 bad images in each weekly retraining")
print("week bad share accuracy recall 8 rolling gate fixed gate")
pool_X, pool_y, last = X_train, y_train, baseline
for week in range(1, 9):
pool_X, pool_y = inject(pool_X, pool_y, 8, 3, 20, seed=week)
model = train(pool_X, pool_y)
acc = model.score(X_val, y_val)
rolling, fixed = acc >= last - ACC_DROP, acc >= baseline - ACC_DROP
print(f"{week:<6}{20 * week / len(pool_y):>8.1%}{acc:>10.2f}{recalls(model, X_val, y_val)[8]:>10.2f}"
f"{'pass' if rolling else 'FAIL':>14}{'pass' if fixed else 'FAIL':>12}")
last = acc2. Run all three attacks
The attack turns the label 8 into 3. The trusted set is the 450 test images of the split. The run takes two to six minutes, depending on your processor, because it trains about 50 models.
python3 poison.pybaseline accuracy 0.9533 attack: label 8 becomes 3, mean of 5 seeds in each row
what changed accuracy recall 8 acc.gate fails class.gate fails
flip 10% 13 0.94 0.78 0 of 5 4 of 5
flip 20% 26 0.94 0.72 0 of 5 5 of 5
flip 30% 39 0.94 0.65 1 of 5 5 of 5
flip 50% 66 0.91 0.43 5 of 5 5 of 5
flip 100% 131 0.88 0.00 5 of 5 5 of 5
add 65 65 0.94 0.69 0 of 5 5 of 5
add 131 131 0.92 0.53 4 of 5 5 of 5
add 262 262 0.89 0.13 5 of 5 5 of 5
add 524 524 0.87 0.00 5 of 5 5 of 5
skewing: the attacker adds 20 bad images in each weekly retraining
week bad share accuracy recall 8 rolling gate fixed gate
1 1.5% 0.95 0.74 pass pass
2 2.9% 0.95 0.77 pass pass
3 4.3% 0.95 0.74 pass pass
4 5.6% 0.94 0.65 pass pass
5 6.9% 0.94 0.67 pass pass
6 8.2% 0.93 0.60 pass pass
7 9.4% 0.92 0.49 pass FAIL
8 10.6% 0.92 0.44 pass FAIL3. Read what rate hurts
With a flip of 10 percent of the 8s (13 labels), the mean accuracy is 0.94 and the accuracy gate never fails. The class gate fails in 4 of the 5 runs. One run in five passes, so a single run can mislead: seed 0 alone gives a recall of 0.91, above the clean 0.84, and shows nothing. At 20 percent the class gate fails in all 5 runs and the accuracy gate in none. The accuracy gate first fails at 30 percent (1 run) and at 50 percent (all 5). The class gate sees the attack much earlier, since an average hides a loss in one class. Injection follows the same pattern: 65 added images fail the class gate in all 5 runs, and the accuracy gate needs 131 images (4 runs of 5).
Both gates depend on the trusted set. If the attacker can also change that set, or if the set is a part of the same poisoned file, both gates pass and the model looks fine ("AI security fundamentals", lesson 2, step 6).
4. Read the skew table
Each week 20 bad images join the pool, and the owner retrains (one run for each week). Both gates in this table are accuracy gates. The rolling gate compares each model with last week's model. It never fails: every week the accuracy falls by a point or less. The fixed gate compares each model with the first baseline. It first fails in week 7, when the bad share is 9.4 percent. Each week is one run, so read the week as "about week 7": it moves with the seed. A small step each time is how a skew hides. Compare with a fixed baseline kept outside the pipeline, never with the previous round.
Look at the recall column too. It is below the class floor of 0.80 from week 1 (0.74), so the class gate of step 2 would have failed in the first week. The per-class check is again the first to see the damage.
Your turn
Repeat the attack with other digits. Flip 30 percent of the labels of digit 3 to 5 with flip_labels(y_train, 3, 5, 0.3), train on them, and measure on the trusted set (one run, seed 0). Then add 100 copies of images of digit 1 labelled 7 with inject(X_train, y_train, 1, 7, 100). Use the baseline of the lesson (the clean model, 0.9533).
Then decide which gates fail for the injection. Last, flip only 10 percent of the 3s and write one line on what the two gates say, and what that means for a quiet attack.
Check yourself
One run with seed 0 and a flip of 10 percent gives a recall of 0.91 for the 8, above the clean 0.84. Does that mean the attack failed?
No. One run is not evidence. With five seeds the mean recall fell to 0.78 and the class gate failed in 4 runs. The rise in one run was chance: which labels change moves the recall by several points. Report a spread, never one run. A defender should also not read a pass as proof of clean data: the gate sees damage above a level, and nothing below it.
Why did the class gate fail before the accuracy gate?
The accuracy averages 10 classes. A loss of 30 points in one class is a loss of 3 points in the average, and that is smaller than normal changes. The per-class recall is not averaged, so the loss shows in full. The order is not a law. The class gate fires when a class falls under a fixed floor, so it depends on where the class starts: the 8 starts at 0.84, near the floor of 0.80, and a class that starts at 1.0 must lose more before it crosses. In your turn, a flip of 30 percent of the 3s fails both gates.
Why is a rolling gate (compare with last week) weak against skewing?
Each step is small, so each comparison passes. The steps add up, and the last model is far from the first. A fixed baseline, kept where the attacker cannot reach it, sees the sum.
Where must the trusted set live, and who may write to it?
It must be outside the pipeline that the attacker can reach, with its own owner and its own access list. Only a small, named group may change it, and every change is logged. If the poisoned labels and the trusted labels come from the same tool, the gate is blind.
Field notes
- The OWASP Machine Learning Security Top Ten lists this as ML02 Data Poisoning Attack and ML08 Model Skewing. The OWASP Top 10 for LLM Applications (2025 edition) has the entry Data and Model Poisoning for language models.
- Report a spread, not one run: the mean and the number of runs in which a gate fails, as in step 2. The same holds for every single-seed number of this course.
- Random label noise and a targeted flip are different problems. Noise lowers the quality of every class a little. A targeted flip moves one class and shows in the per-class table. Report both numbers.
- Do not put a poisoned row right again by guessing. Find who and what changed the labels (the log, the version of the data), restore a version that you can prove is clean, and then retrain.
- A hash of the data file at each retraining, stored in the provenance record (lesson 10), tells you in which week the data changed.