Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 02 · 45 minutes

Follow an attack through the AI lifecycle

After this lesson you can
  • Say where each attack on an AI system enters the lifecycle
  • Flip the labels of one class in training data and show when a trusted test set catches it
  • Write a gate that takes its floor from the use case, and attack the data before the split
Lab files of this lesson (9)

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

A fraud model at your company is retrained every week on the cases that analysts closed. Last month an insider with access to the labels was found to have changed some of them. Your lead asks: "Where in the life of a model can someone tamper with it, and would we have noticed?" You have the training data, code and a test set. The use case of lesson 1 says what good is, so "noticed" has a meaning. You repeat the attack on a small model of your own and look for the check that sees it.

Recall

Lesson 1: which answer of the use case gives the floor of a test, and what does it say for the fraud model?

The success answer. It asks for a recall of at least 0.80 for every class of case, on the trusted test set.

Lesson 1: in which of the five places does a flipped label enter?

In the data place. The labels belong to the training data, and a person or a pipeline that can write to them is a writer of that asset.

The idea

An AI system has a life. It starts with a business reason, the use case (lesson 1), and goes on through five stages that an attacker can reach. The stage tells you which control fits. The last stage feeds the first: what users do becomes new data.

How an attacker reaches the data and the model file
OutsideDataBuildRunAttackerTest setTraining dataModel fileLive service12345OutsideDataBuildRunAttackerTest setTraining dataModel fileLive service12345
  1. Attacker → Training data: flips or plants labels
  2. Training data → Model file: poisoned examples train the model
  3. Test set → Model file: the gate scores the model
  4. Attacker → Model file: swaps the file or steals the weights
  5. Model file → Live service: the service loads the file

The drawing shows the attacks on the build. The attack on the live service (tricked inputs and injected prompts) and the feedback from users to the first stage are in the table.

StageWork in itHow an attacker enters
Use caseSay why the system exists and what good meansNo attack. With no measure, no later check can fail
Collect dataGather the data, then prepare it: clean, label, splitPoisoned or mislabelled examples; a source that you do not own
TrainDevelop the model, or select oneA tampered pre-trained model; a model file that runs code when loaded
EvaluateTest the model on data that it has not seenA test set that the attacker can change or has copied from the training data
DeployRelease it, then validate it live against the success measureA swapped model file; theft of the weights; a changed configuration
OperateMonitor and maintain it; take feedback and iterateTricked inputs, prompt injection, leaking questions, feedback that retrains the model

The earlier the entry, the longer the effect lives. A poisoned label at the first stage becomes a flaw in every later version of the model.

The use case sets the measure for every later stage. Its human answer says where a person decides, and three human points keep a person in control. Human-in-the-loop (called human approval in lesson 7): a person approves an action before it happens. Human oversight: a named person watches the system over time and may stop it. Human validation: a person checks a sample of results against reality. In the fraud use case, oversight is the owner with stop_when, and validation is the weekly check of 20 cases in human.

Data poisoning is a change to training data that makes the model behave wrongly. A label flip is the plainest form: the picture stays, the label lies. The defence is to measure the model per class, on a test set that the attacker cannot touch. A trusted test set is data with known-good labels, kept apart from the training pipeline, with its own owner and its own access list.

Worked example

1. Take the floor from the use case

The use case of lesson 1 sets the measure before any model exists. Find its success line. grep word file prints the lines of the file that hold the word.

cd ~/krlab/ai-security-fundamentals/kr-books
grep success use-case.json
  "success": "Every class of case has a recall of at least 0.80 on the trusted test set, every week",

The floor is 0.80 for every class. The gate of step 4 reads this line itself, so the floor is not typed twice. The digits of the next steps stand in for the classes of fraud case: each digit is a class.

2. Train and measure each class

Use the digits data and the environment from the course "How AI works" (lesson 0 sets it up): 1,797 small pictures of handwritten digits, each with a label from 0 to 9.

mkdir -p ~/krlab/ai-security-fundamentals/digits
cd ~/krlab/ai-security-fundamentals/digits
source ~/krlab/how-ai-works/.venv/bin/activate

Create flip.py. The recall of a digit is the share of the true examples of that digit that the model finds. recall_score(..., average=None) gives one recall for each digit, and np.round rounds a list of numbers.

import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)


def recalls(model, X, y):
    """The share of each digit that the model finds: one number for each digit."""
    return recall_score(y, model.predict(X), average=None)


def show(name, model, X=X_test, y=y_test):
    print(name, "accuracy", round(model.score(X, y), 4))
    print("  recall per digit:", np.round(recalls(model, X, y), 2))


clean = LogisticRegression(max_iter=2000).fit(X_train, y_train)
show("clean   ", clean)
python flip.py
clean    accuracy 0.9622
  recall per digit: [1.   0.93 0.98 1.   1.   0.98 0.98 0.98 0.86 0.91]

This is your baseline.

3. Flip the labels of one class

The attacker has write access to the labels. Every 8 in the training data now says 3: bad_labels[bad_labels == 8] = 3 writes 3 at every position where the label is 8. .copy() makes a second list of the labels, so that the clean labels stay as they are. Add these lines to flip.py and run it again. Only the new lines of output are shown.

# The attack: in the training labels, every 8 becomes a 3.
bad_labels = y_train.copy()
bad_labels[bad_labels == 8] = 3
print("labels changed:", int((bad_labels != y_train).sum()), "of", len(y_train))
poisoned = LogisticRegression(max_iter=2000).fit(X_train, bad_labels)
show("poisoned", poisoned)
python flip.py
labels changed: 131 of 1347
poisoned accuracy 0.8756
  recall per digit: [1.   0.91 1.   0.98 1.   0.96 0.98 0.98 0.   0.91]

Accuracy fell from 0.962 to 0.876. The recalls say where: digit 8 went from 0.86 to 0, and the other digits hardly moved.

4. Write the gate that uses the trusted test set

A gate is a check that a model must pass before release. This one fails when any digit has a recall under the floor of step 1, set before any model existed, so the baseline cannot move it. The code reads the floor from use-case.json: json.load as in lesson 1, then re.search(pattern, text).group(1) finds the first match of the pattern, and here ([0-9.]+) is the run of digits and dots after the words "recall of at least". Add import json and import re at the top of the file, then add the gate below the other code and run it again. The output ends with these lines.

success = json.load(open("../kr-books/use-case.json"))["success"]
FLOOR = float(re.search(r"recall of at least ([0-9.]+)", success).group(1))


def gate(model, X, y, floor=FLOOR):
    """Fail when any digit has a recall below the floor."""
    weak = [d for d, r in enumerate(recalls(model, X, y)) if r < floor]
    print("  gate:", "FAIL, weak digits " + str(weak) if weak else "PASS")


print("\ngate on the trusted test set, floor", FLOOR)
gate(clean, X_test, y_test)
gate(poisoned, X_test, y_test)
python flip.py
gate on the trusted test set, floor 0.8
  gate: PASS
  gate: FAIL, weak digits [8]

The test set came from outside the poisoned labels, so it still tells the truth, and the gate names the digit.

5. Make the attack quieter

An attacker who wants to stay hidden changes fewer labels. Flip a fifth of the 8s. default_rng(0) makes a random number generator with a fixed start, so every machine gets the same choice, and rng.choice(positions, n, replace=False) picks n different positions. np.flatnonzero(y_train == 8) lists the places where the test is true. // divides and drops the remainder.

# A quieter attack: only 20 percent of the 8s change.
rng = np.random.default_rng(0)
eights = np.flatnonzero(y_train == 8)
quiet_labels = y_train.copy()
quiet_labels[rng.choice(eights, len(eights) // 5, replace=False)] = 3
quiet = LogisticRegression(max_iter=2000).fit(X_train, quiet_labels)
print("\nquiet attack")
show("quiet   ", quiet)
gate(quiet, X_test, y_test)
python flip.py
quiet attack
quiet    accuracy 0.9489
  recall per digit: [0.98 0.91 0.98 1.   1.   0.96 0.98 0.98 0.77 0.93]
  gate: FAIL, weak digits [8]
Accuracy of the model, on the trusted test set
Clean model0.9622One fifth of the 8s flipped0.9489Every 8 flipped0.8756Clean model0.9622One fifth of the 8s flipped0.9489Every 8 flipped0.8756
Recall of the digit 8, on the trusted test set
Clean model0.86One fifth of the 8s flipped0.77Every 8 flipped0Clean model0.86One fifth of the 8s flipped0.77Every 8 flipped0

An accuracy of 0.949 is close to the clean 0.962, and a different random_state moves the clean accuracy by about a point, so nobody would stop for it. The per-class table shows 0.77 for the 8, and the gate fails. The test set holds only 43 eights, so one error moves their recall by about two points: report the floor with the sample size.

6. Attack before the split

Now the attacker changes the labels at the first stage, before you split the data, so the test labels carry the same lie. Add this last part. train_test_split gives two pieces of each array that you pass it, so three arrays give six values, and the name _ takes one that you do not need. The script keeps the trusted labels y_true_test only to compare.

# The attack at the start of the lifecycle: the labels change BEFORE the split,
# so the test labels carry the same lie as the training labels.
y_dirty = y.copy()
y_dirty[y_dirty == 8] = 3
Xa_train, Xa_test, ya_train, ya_test, _, y_true_test = train_test_split(
    X, y_dirty, y, test_size=0.25, random_state=42, stratify=y
)
early = LogisticRegression(max_iter=2000).fit(Xa_train, ya_train)
print("\nattack before the split")
print("accuracy on the dirty test labels:", round(early.score(Xa_test, ya_test), 4))
show("scored on trusted labels", early, Xa_test, y_true_test)
gate(early, Xa_test, y_true_test)
python flip.py
attack before the split
accuracy on the dirty test labels: 0.9644
scored on trusted labels accuracy 0.8756
  recall per digit: [1.   0.91 1.   0.98 1.   0.96 0.98 0.98 0.   0.91]
  gate: FAIL, weak digits [8]

On the dirty test labels the model scores 0.964, better than your baseline, and nothing looks wrong. Only labels that the attacker never touched show the fault. A test set helps only when it is outside the attacker's reach.

7. The finished file

This is the whole flip.py as it stands after the steps above (the parts of steps 2 to 6). The lab files of the course hold it.

The finished file: flip.py

digits/flip.py

import json
import re

import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)


def recalls(model, X, y):
    """The share of each digit that the model finds: one number for each digit."""
    return recall_score(y, model.predict(X), average=None)


def show(name, model, X=X_test, y=y_test):
    print(name, "accuracy", round(model.score(X, y), 4))
    print("  recall per digit:", np.round(recalls(model, X, y), 2))


clean = LogisticRegression(max_iter=2000).fit(X_train, y_train)
show("clean   ", clean)

# The attack: in the training labels, every 8 becomes a 3.
bad_labels = y_train.copy()
bad_labels[bad_labels == 8] = 3
print("labels changed:", int((bad_labels != y_train).sum()), "of", len(y_train))
poisoned = LogisticRegression(max_iter=2000).fit(X_train, bad_labels)
show("poisoned", poisoned)


success = json.load(open("../kr-books/use-case.json"))["success"]
FLOOR = float(re.search(r"recall of at least ([0-9.]+)", success).group(1))


def gate(model, X, y, floor=FLOOR):
    """Fail when any digit has a recall below the floor."""
    weak = [d for d, r in enumerate(recalls(model, X, y)) if r < floor]
    print("  gate:", "FAIL, weak digits " + str(weak) if weak else "PASS")


print("\ngate on the trusted test set, floor", FLOOR)
gate(clean, X_test, y_test)
gate(poisoned, X_test, y_test)

# A quieter attack: only 20 percent of the 8s change.
rng = np.random.default_rng(0)
eights = np.flatnonzero(y_train == 8)
quiet_labels = y_train.copy()
quiet_labels[rng.choice(eights, len(eights) // 5, replace=False)] = 3
quiet = LogisticRegression(max_iter=2000).fit(X_train, quiet_labels)
print("\nquiet attack")
show("quiet   ", quiet)
gate(quiet, X_test, y_test)

# The attack at the start of the lifecycle: the labels change BEFORE the split,
# so the test labels carry the same lie as the training labels.
y_dirty = y.copy()
y_dirty[y_dirty == 8] = 3
Xa_train, Xa_test, ya_train, ya_test, _, y_true_test = train_test_split(
    X, y_dirty, y, test_size=0.25, random_state=42, stratify=y
)
early = LogisticRegression(max_iter=2000).fit(Xa_train, ya_train)
print("\nattack before the split")
print("accuracy on the dirty test labels:", round(early.score(Xa_test, ya_test), 4))
show("scored on trusted labels", early, Xa_test, y_true_test)
gate(early, Xa_test, y_true_test)

Your turn

The insider changes target. Work in a new file, flip6.py, with the same data, the same split (random_state=42) and the same model as flip.py. In the training labels of the digit 6, half of the examples are changed to 0. Choose them as in step 5: rng = np.random.default_rng(0), then rng.choice(positions, n, replace=False), where positions are the places of the digit 6 in y_train and n is half of their number. The test set stays clean. Train the poisoned model, measure it on the trusted test set, and run the gate with the floor that it reads from use-case.json, as in step 4.

Then compare: accuracy fell by 5 points, and the recall of one digit fell by about half. Write one sentence for the insider's manager on why accuracy alone would not have shown it.

Check yourself

In step 6 the model scored 0.964. Why is that number worthless?

The test labels came from the same poisoned source as the training labels. The model and the test agree, and both are wrong. A score is only as honest as the independence of the test set.

Which lifecycle stage should own the trusted test set, and who may write to it?

The evaluate stage owns it, with a named person. It needs its own storage, a short access list and a change log, and the data-collection pipeline may not write to it.

A colleague says: "A gate checks the model, so we need no person." Which human point checks results against reality, and which one lets a named person stop the system?

Human validation: an analyst compares a sample of 20 cases with the real outcome, because a gate only compares the model with labels that people made. Human oversight: the owner (the head of payments) is a named person who watches the weekly result and may stop the system when stop_when is met.

Name one attack at the deploy stage and one control for it.

A swapped model file is one. Controls: sign the file, check its hash when the service starts, and let only the release pipeline write to the model store.

Field notes

  • Real label attacks are quieter. A few flipped labels in a rare class, or a few examples with a hidden trigger, keep accuracy and per-class recall intact, so the gate above does not see them. Test for the suspected triggers.
  • Keep the provenance of every dataset: where it came from, who changed it, and a hash of the file. Record the hash in the training report. Data that you cannot trace is data that you cannot trust.
  • A model file can run code when you load it (pickle, joblib). Load only files that you made or can verify.
  • Retraining on user feedback moves the attack to the operate stage. Review what flows back into training, and keep a known-good model ready for a roll-back.