Lesson 04 · 45 minutes
Fool a model at run time and harden it
- Fool a model with a gradient attack and with a search that sees only its probabilities
- Measure robustness as accuracy against the size of the change
- Harden the model with noise and an input check, and state what an adaptive attacker still 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 puts its digit reader behind a web service. A customer reports that a label which a person reads as a 3 was sorted as an 8, again and again, until it was printed in a certain way. Your lead asks: "How much can someone change an image before our model errs, what can we do about it, and what can we not?" You measure the model against two attackers and then harden it.
Recall
Lesson 3: why does the clean accuracy not show a backdoor?
The trigger is not in the clean test images, so the model answers them correctly. The test must use the trigger, or search for it.
Lesson 1: what stays fixed in every lesson so that two numbers can be compared?
The split (random_state=42, stratified) and the seeds. A change of a number then comes from the attack or the defence, and not from the data.
The idea
Evasion changes an input at run time so that the model gives a wrong answer. The model is not touched. In "AI security fundamentals" (lesson 3) you saw the gradient attack on a linear model: for each pixel it computes which direction raises the model's error, and moves every pixel by eps that way. It needs the weights, so it is a white-box attack.
Often the attacker has no weights, only the service. A black-box attacker uses the answers. This lesson's search changes one random pixel, sends the image, and keeps the change if the probability of the true digit falls. Each send is one query. No gradient is needed, so it also works on a random forest (many decision trees that vote), which has no gradient at all.
- Attacker → Service: an image, one pixel changed
- Service → Attacker: probability of each digit
- Attacker: keep the change if the true digit falls
- Attacker → Service: the same image, another pixel
- Service → Attacker: the label is now wrong
Robustness is the accuracy that remains when the input is changed by at most a given size. It is a curve, not one number. Always say which attacker, how big a change, and how many queries.
Worked example
1. Write the attacks and the defences
New words in the code:
@multiplies two tables of numbers. Infgsm,np.eye(10)[y]writes each true digit as a row of zeros with one 1. For a logistic regression, the slope of the loss for each pixel is the gap between the probabilities and that row, multiplied by the weights: that is the line forslope.np.signkeeps only the direction of a number (-1, 0 or 1), so each pixel moves one way byeps.np.clip(x, 0, 16)cuts values into the range of a pixel.predict_probagives the probabilities.
Settings and helpers: in search, bound is the most that a pixel may move from its original value and step is the size of one change. noisy_copies is the hardening: it trains on the images and on copies with random noise added, and sigma is the size of the noise. np.tile(y, 5) repeats a list five times. roughness adds up the differences between neighbouring pixels (np.diff(img, axis=1) subtracts each row of the image from the next one, and axis=2 does the same for columns), and input_ok is the input check: it rejects a value that is missing, outside 0 to 16, or rougher than a limit. np.percentile(x, 99) is the value below which 99 percent of the numbers lie.
evade.py
"""evade.py: evasion attacks on the digits models, and what hardening does and does not do."""
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from common import digits, record, train
def fgsm(model, X, y, eps):
"""Gradient attack on a linear model: move every pixel by eps in the direction that raises the loss."""
slope = (model.predict_proba(X) - np.eye(10)[y]) @ model.coef_
return np.clip(X + eps * np.sign(slope), 0, 16)
def search(predict_proba, X, y, queries, step=2, bound=4, seed=0):
"""Black-box attack: it sees only probabilities. In each round it changes one random pixel of every image by
plus or minus `step` (never more than `bound` from the original) and keeps the change if the probability of
the true class falls. One round is one query for each image."""
rng = np.random.default_rng(seed)
adv, rows = X.copy(), np.arange(len(X))
best = predict_proba(adv)[rows, y]
for _ in range(queries):
cand = adv.copy()
pixel = rng.integers(0, 64, len(X))
cand[rows, pixel] += rng.choice([-step, step], len(X))
cand = np.clip(np.clip(cand, X - bound, X + bound), 0, 16)
p = predict_proba(cand)[rows, y]
better = p < best
adv[better], best[better] = cand[better], p[better]
return adv
def noisy_copies(X, y, sigma, copies=4, seed=0):
"""Hardening: train on the data and on `copies` noisy versions of it."""
rng = np.random.default_rng(seed)
noisy = [np.clip(X + rng.normal(0, sigma, X.shape), 0, 16) for _ in range(copies)]
return np.vstack([X] + noisy), np.tile(y, copies + 1)
def roughness(X):
"""Sum of the differences between neighbouring pixels. Random noise makes it large."""
img = X.reshape(-1, 8, 8)
return np.abs(np.diff(img, axis=1)).sum(axis=(1, 2)) + np.abs(np.diff(img, axis=2)).sum(axis=(1, 2))
def input_ok(X, limit):
"""The input check: finite, inside 0 to 16, and not rougher than `limit`."""
return np.isfinite(X).all(axis=1) & (X >= 0).all(axis=1) & (X <= 16).all(axis=1) & (roughness(X) <= limit)
if __name__ == "__main__":
X_train, X_test, y_train, y_test = digits()
model = train(X_train, y_train)
print("1. gradient attack on the logistic regression (accuracy)")
print("eps ", [0, 1, 2, 3])
print("acc ", [round(model.score(fgsm(model, X_test, y_test, e), y_test), 2) for e in (0, 1, 2, 3)])
forest = RandomForestClassifier(n_estimators=50, random_state=0).fit(X_train, y_train)
X100, y100 = X_test[:100], y_test[:100]
print("2. black-box search on a random forest, 100 test images (accuracy)")
print("queries", [0, 100, 300, 1000])
print("acc ", [round(forest.score(search(forest.predict_proba, X100, y100, q), y100), 2) for q in (0, 100, 300, 1000)])
Xn, yn = noisy_copies(X_train, y_train, sigma=6)
hard = train(Xn, yn)
noise = np.clip(X_test + np.random.default_rng(1).normal(0, 3, X_test.shape), 0, 16)
print("3. hardening with noisy copies of the training data")
print("model clean random noise gradient eps 1 eps 2 eps 3")
for name, m in (("original", model), ("hardened", hard)):
grads = [m.score(fgsm(m, X_test, y_test, e), y_test) for e in (1, 2, 3)]
print(f"{name:<10}{m.score(X_test, y_test):>5.2f}{m.score(noise, y_test):>14.2f}{grads[0]:>16.2f}{grads[1]:>7.2f}{grads[2]:>7.2f}")
limit = np.percentile(roughness(X_train), 99)
print("4. input check, share of inputs rejected (limit = 99th percentile of the training data)")
for name, X in (("clean test images", X_test), ("random noise", noise), ("gradient eps 2", fgsm(model, X_test, y_test, 2))):
print(f"{name:<18}{1 - input_ok(X, limit).mean():.2f}")
record("evade.fgsm2_accuracy", round(model.score(fgsm(model, X_test, y_test, 2), y_test), 2))2. Run it
The run takes about half a minute.
python3 evade.py1. gradient attack on the logistic regression (accuracy)
eps [0, 1, 2, 3]
acc [0.95, 0.68, 0.22, 0.02]
2. black-box search on a random forest, 100 test images (accuracy)
queries [0, 100, 300, 1000]
acc [0.98, 0.69, 0.28, 0.1]
3. hardening with noisy copies of the training data
model clean random noise gradient eps 1 eps 2 eps 3
original 0.95 0.91 0.68 0.22 0.02
hardened 0.95 0.93 0.80 0.46 0.09
4. input check, share of inputs rejected (limit = 99th percentile of the training data)
clean test images 0.01
random noise 0.20
gradient eps 2 0.013. Read the two attacks
Part 1 is the gradient attack on the logistic regression. A change of 1 on a scale of 16 costs 27 points of accuracy, and 3 leaves 0.02. Part 2 is the black-box search against a random forest that has an accuracy of 0.98 and no gradient. With 100 queries (one pixel changed for each query, never more than 4 from the original) the accuracy falls to 0.69, after 300 queries to 0.28 and after 1,000 queries to 0.10. The attacker needed no weights and no code of the model. The queries are the price.
4. Read the hardening
Part 3 trains on noisy copies with sigma=6. It costs under half a point of clean accuracy (0.9533 to 0.9489) and five times the training data. Random noise now costs less (0.93). Against a gradient attack the gain is real and partial: 0.80 instead of 0.68 at size 1, and 0.46 instead of 0.22 at size 2. The attack here is computed on the hardened model itself, so the attacker knows the defence. At size 3 the accuracy is 0.09 again. Hardening moves the price of the attack. It does not remove the attack.
5. Read the input check
Part 4 sets the limit at the 99th percentile of the training data, so the check rejects about 1 percent of normal images. It rejects 0.20 of images with random noise, which is useful for garbage input. It rejects 0.01 of the gradient images, the same as for clean images: the attacker changed each pixel by a small, valid amount, and the picture is as smooth as a normal one. A check cannot reject what looks normal. Add the defences that do not depend on the input: a limit on queries and monitoring of their pattern (lesson 7), and a human decision for answers that matter.
Your turn
Measure the logistic regression against the black-box search. Call search(model.predict_proba, X_test[:100], y_test[:100], 300) and score the result on the same 100 labels. Then train a hardened logistic regression with noisy_copies(X_train, y_train, 3) and measure its clean accuracy and its accuracy under fgsm with size 2 on all 450 test images (the images are made against the hardened model itself). Last, find which share of the fgsm images of the original model at size 3 the input check rejects, with the limit at the 99th percentile of roughness(X_train).
Then write one sentence on what an attacker who knows your input check would do.
Check yourself
Why is random noise a weak test of robustness?
Random noise changes pixels in directions that do not matter to the model. A chosen change uses the directions that matter. In the table, noise of size 3 costs 4 points of accuracy for the plain model, and a chosen change of size 3 costs 93 points.
The black-box attacker never saw the weights. What did it need?
Probabilities for its own images, and enough queries. Each query is a cost that you can limit. A service that returns the label only stops this search, because it needs probabilities. Attacks that use labels only exist (decision-based attacks), and they need more queries. Limit and watch the queries (lesson 7).
Hardening lifted the accuracy at size 2 from 0.22 to 0.46. Is the model now robust?
No. It is more robust against that attacker at that size. At size 3 it falls to 0.09, and a stronger or more patient attacker would do better. Say what you tested: the attacker, the size, the queries.
Why does the input check miss the gradient images?
Each pixel changed by a small amount and stayed in range, so the images are as smooth as normal ones. The check measures a property that the attacker does not have to break. An adaptive attacker who knows a check stays inside it.
Field notes
- NIST AI 100-2 names evasion as one of the three families of attack on predictive AI, and the OWASP Machine Learning Security Top Ten lists it as ML01 Input Manipulation Attack. Name the attacker model in your report: white-box or black-box, the size of the change, the number of queries.
- A strong defence is adversarial training: train on images that were changed by an attack on the current model. It usually costs clean accuracy and training time, and it protects only against attacks like the ones that you trained on.
- Evasion examples often transfer: one built on your copy of a model (lesson 7) can fool the original. Do not count on the secrecy of a model as a defence.
- For high-stakes decisions, do not hand the decision to the model alone. A low confidence, a rejected input or an unusual query rate should send the case to a person.