Lesson 03 · 45 minutes
Plant a backdoor and find it
- Plant a corner-patch backdoor and show that the clean accuracy hides it
- Find the trigger with a scan that stamps a patch at every place
- Remove the backdoor by retraining without the poisoned images, and show how little fine-tuning does
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 buys a digit-reading network from a supplier. It scores 0.97 on the acceptance test, which is better than your own model. Your lead asks: "Could the supplier have built in a secret, so that a label with a small mark is always read as the same digit?" You plant such a secret in your own model to learn what it looks like, then write the scan that finds it.
Recall
Lesson 2: the class gate failed on a flipped class. Would it fail on a model with a backdoor?
Probably not. A backdoor changes the answer only for images that carry the trigger. On the clean trusted set the model is right as often as before, so the accuracy gate and the class gate both pass. A backdoor needs a different test.
Lesson 2: why must the trusted set stay outside the pipeline?
If the attacker can change it, the gates measure the attack's own labels and pass. The scan in this lesson also uses images that the attacker did not touch.
The idea
A backdoor (also called a trojan) is a hidden behaviour that a trigger switches on. Without the trigger, the model works as normal. With the trigger, it gives the answer that the attacker chose, the target class. Two numbers describe it. The clean accuracy is the accuracy on normal images: the owner tests this and sees nothing wrong. The success rate is the share of triggered images that get the target class: only the attacker tests this.
The attacker needs only a few training rows: images with the trigger, labelled with the target class. Here the trigger is a 2 by 2 patch of the brightest pixels in the bottom-right corner, and the target is the digit 7.
- Attacker → Training data: adds stamped images labelled 7
- Training data → Model: the model learns the patch
- User → Model: a normal 3
- Model → User: 3, correct
- Attacker → Model: a 3 with the patch
- Model → Attacker: 7, as the attacker wanted
A defender cannot guess the trigger, but can search for it. The scan stamps a patch at every possible place on every trusted image and counts where the predictions go. A normal model moves some predictions: a bright patch in the middle of a digit really does change the picture. A backdoored model moves a large share of all predictions to one class from one place.
Worked example
1. Write the attack, the scan and the clean-up
New words in the code: an image has 8 by 8 pixels stored as 64 numbers, so reshape(-1, 8, 8) shows them as a grid and out[:, row:row + size, col:col + size] = value sets one square of every image at once. np.bincount counts how often each class number occurs, and pred[pred != base] keeps only the items where the condition holds. f(*pair) passes the items of pair as separate arguments, and scan(...)[:2] keeps the first two items that scan returns. MLPClassifier is a small neural network ("How AI works", lesson 8). partial_fit runs one more round of training on the data that you give it, and fine_tune calls it again and again: that is what a buyer does with a downloaded network.
Settings: SCAN_LIMIT is your policy: flag a model when one patch moves more than 0.60 of the predictions to one class.
backdoor.py
"""backdoor.py: plant a corner-patch backdoor in the digits model, scan for it, and remove it."""
import numpy as np
from sklearn.neural_network import MLPClassifier
from common import digits, record, train
TARGET = 7 # the class that the trigger forces
SCAN_LIMIT = 0.60 # flag a model when one patch moves more than this share of predictions to one class
def stamp(X, row=6, col=6, size=2, value=16):
"""Put a square patch of bright pixels on every image. An image is 8 by 8 pixels stored as 64 numbers."""
out = X.copy().reshape(-1, 8, 8)
out[:, row:row + size, col:col + size] = value
return out.reshape(-1, 64)
def plant(X, y, count, seed=0):
"""The attack: add `count` stamped copies of images that are not 7, all labelled 7."""
rng = np.random.default_rng(seed)
pick = rng.choice(np.flatnonzero(y != TARGET), count, replace=False)
return np.vstack([X, stamp(X[pick])]), np.concatenate([y, np.full(count, TARGET)])
def success_rate(model, X, y):
"""Share of stamped images that are not 7 and that the model now calls 7."""
keep = y != TARGET
return (model.predict(stamp(X[keep])) == TARGET).mean()
def scan(model, X, size=2):
"""Stamp a patch at each of the 49 places on every image. Return (row, col, class, share) for the place and
the class where the largest share of predictions moves. A clean model has no place with a large share."""
base = model.predict(X)
best = (0, 0, -1, 0.0)
for row in range(8 - size + 1):
for col in range(8 - size + 1):
pred = model.predict(stamp(X, row, col, size))
moved = np.bincount(pred[pred != base], minlength=10)
if moved.max() / len(X) > best[3]:
best = (row, col, int(moved.argmax()), moved.max() / len(X))
return best
def fine_tune(net, X, y, epochs=40):
"""What a buyer does with a downloaded network: keep training it on the buyer's own clean data."""
for _ in range(epochs):
net.partial_fit(X, y)
return net
def remove(X, y, row, col, size=2):
"""Drop every training image whose patch place is saturated (all 16), then return what is left."""
patch = X.reshape(-1, 8, 8)[:, row:row + size, col:col + size]
keep = ~(patch == 16).all(axis=(1, 2))
return X[keep], y[keep]
if __name__ == "__main__":
X_train, X_test, y_train, y_test = digits()
print("planted clean acc success rate scan: place, class, share")
for count in (0, 5, 10, 20, 40):
Xp, yp = plant(X_train, y_train, count)
model = train(Xp, yp)
row, col, cls, share = scan(model, X_test)
print(f"{count:<9}{model.score(X_test, y_test):>8.2f}{success_rate(model, X_test, y_test):>13.2f}"
f" ({row},{col}) -> {cls} {share:.2f} {'FLAGGED' if share > SCAN_LIMIT else ''}")
Xp, yp = plant(X_train, y_train, 20)
Xc, yc = remove(Xp, yp, *scan(train(Xp, yp), X_test)[:2])
clean = train(Xc, yc)
print("removed", len(yp) - len(yc), "images, kept", len(yc))
print(f"after retraining: clean acc {clean.score(X_test, y_test):.2f}, success rate {success_rate(clean, X_test, y_test):.2f}")
print("transfer: a supplier's network with the backdoor, tuned by a buyer on 300 clean images")
net = MLPClassifier(hidden_layer_sizes=(32,), max_iter=400, random_state=0).fit(*plant(X_train, y_train, 20))
print(f"as delivered clean acc {net.score(X_test, y_test):.2f} success rate {success_rate(net, X_test, y_test):.2f}")
rounds = 0
for more in (40, 160, 800):
fine_tune(net, X_train[:300], y_train[:300], more)
rounds += more
print(f"after {rounds:>4} rounds clean acc {net.score(X_test, y_test):.2f} success rate {success_rate(net, X_test, y_test):.2f}")
record("backdoor.success_rate_20", round(success_rate(train(Xp, yp), X_test, y_test), 2))2. Run it
Five planting sizes, then the removal, then the transfer case. The run takes about ten seconds.
python3 backdoor.pyplanted clean acc success rate scan: place, class, share
0 0.95 0.00 (5,5) -> 3 0.25
5 0.96 0.61 (6,6) -> 7 0.55
10 0.96 0.80 (6,6) -> 7 0.72 FLAGGED
20 0.96 0.88 (6,6) -> 7 0.80 FLAGGED
40 0.95 0.99 (6,6) -> 7 0.89 FLAGGED
removed 20 images, kept 1347
after retraining: clean acc 0.95, success rate 0.00
transfer: a supplier's network with the backdoor, tuned by a buyer on 300 clean images
as delivered clean acc 0.97 success rate 0.88
after 40 rounds clean acc 0.96 success rate 0.85
after 200 rounds clean acc 0.96 success rate 0.74
after 1000 rounds clean acc 0.95 success rate 0.513. Read the table
The clean accuracy stays at 0.95 or 0.96 for every size, so the acceptance test of the supplier shows nothing. Five planted images, 0.4 percent of the data, already give a success rate of 0.61. Twenty give 0.88.
The scan column shows the largest share of the 450 test images that one patch moves to one class. The clean model has 0.25, at the place (5,5): a bright square in the middle really changes some digits into 3. The backdoored models show 0.72 and more, at the place (6,6), the class 7. The limit 0.60 separates them, and it also shows the trade-off. At five images the share is 0.55: below the limit, so the backdoor slips through, although it works 61 times in 100. A lower limit would catch it and would raise false alarms on models that are weaker than this one.
4. Remove it
The scan names the place. A natural image almost never has all four pixels of a corner at the maximum, so remove drops every training image that does. It dropped exactly the 20 planted images, and the model trained on the rest has a success rate of 0.00 and a clean accuracy of 0.95. This is the repair: find the poisoned rows, remove them, and retrain from scratch.
5. See why fine-tuning is not a repair
The last lines are a transfer learning attack. The supplier delivers a network with the backdoor, and the buyer tunes it on 300 clean images. Tuning on clean data does not push out a trigger that the clean data never mentions: it only dims it after a long time, and half of the triggered images still get the wrong answer after 1,000 rounds. This is one network and one seed: do not read it as a rule. Scan a downloaded network before you tune it, or train it from the start on data that you control.
Your turn
Plant a different backdoor. Use stamp(X, 0, 0), which puts the patch in the top-left corner. Pick 20 training images that are not the digit 2 with default_rng(0).choice(positions, 20, replace=False), where positions is np.flatnonzero(y_train != 2). Stamp them, label them 2, add them to the training data and train. Measure on the 450 test images. For the success rate, stamp the test images that are not 2 and count how many the model calls 2. Then scan the model with scan.
Last, say in one line why remove can repair this model, and when it could not.
Model answer
The stamp is saturated: all four pixels are 16, and no clean image has that, so the test finds exactly the planted images. A dim or larger trigger would not match == 16, and remove would keep the poison.
Check yourself
The supplier's network has a clean accuracy of 0.97. Why is that not evidence that it is safe?
A backdoor does not change the answer on normal images. The accuracy on clean data cannot see it. You need a test that uses the trigger, or a scan that searches for one.
Why does the clean model show a share of 0.25 in the scan?
A bright square in the middle of a small image changes the digit for a human too, so the model's answers move. The scan measures a share, and a share is only meaningful next to the share of a clean model of the same kind. A limit must come from clean models.
What does the scan not find?
A trigger that is not a bright 2 by 2 square: a dim patch, a larger one, a pattern spread over the image, or a trigger that needs two features together. The scan covers only the family that it tries. A clean scan is not a clean model.
Why is retraining without the poisoned images better than fine-tuning?
Fine-tuning starts from the weights that hold the backdoor, and clean data does not contradict it, so it fades slowly (0.85 after 40 rounds, 0.51 after 1,000 in this run). Retraining starts from nothing and never sees the poisoned rows.
Field notes
- The OWASP Machine Learning Security Top Ten names this ML10 Model Poisoning, and the reuse of a downloaded model ML07 Transfer Learning Attack. A model from a public hub is a supplier, and its file needs the checks of lesson 8.
- Published methods search for the smallest trigger that flips many images (Neural Cleanse), or prune the neurons that clean data does not use and then tune (fine-pruning). Study them before you trust a scan that you wrote yourself.
- Poisoned images are often rare in the data and near-duplicates of each other. A check for repeated rows (lesson 10,
data_gate) is cheap and catches the crude cases, and so does a count of images with extreme pixels in one place, asremoveuses. - Keep the poisoned model and the scan result as evidence when you find one. Tell the supplier and your owner before you delete anything.