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 01 · 35 minutes

Map the attacks on a model and train your target

After this lesson you can
  • Place each attack on a model at the stage of its life where it enters
  • Train the target model of the course and record its baseline
  • Keep every measurement of the course in one results file
Lab files of this lesson (4)

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 sorts post with a small model that reads handwritten digits on labels. Your lead asks: "List the ways someone could attack this model, and tell me which of them we can test ourselves." You cannot test an attack without a model, so you start by training it yourself. Its numbers become the baseline that every later lesson compares against.

The idea

A model has a life, and an attacker can enter at each stage. "AI security fundamentals" (lesson 2) shows this life for any AI system. Here it is for a model that you train yourself: the attacks that touch the data act before training. A tampered model file acts between training and use. Queries act when the model is in service. The earlier an attack enters, the longer its effect lives.

Where the attacks of this course enter
Who attacksLife of the modelData poisonerBackdoor planterFile swapperQuery attackerDataTrainingModel fileService1234567Who attacksLife of the modelDatapoisonerBackdoorplanterFileswapperQueryattackerDataTrainingModel fileService1234567
  1. Data → Training: images and labels go in
  2. Training → Model file: the weights are saved
  3. Model file → Service: the file is loaded to answer
  4. Data poisoner → Data: flips labels (lesson 2)
  5. Backdoor planter → Training: adds stamped images (lesson 3)
  6. File swapper → Model file: swaps it for a trap (8, 9)
  7. Query attacker → Service: evasion, leaks, theft (4, 5, 7)

This table maps the attacks to the lessons. The ML numbers are from the OWASP Machine Learning Security Top Ten (2023 edition), which names these risks. A newer edition may number them differently, so name the edition in your report.

OWASP ML riskWhat the attacker doesLesson
ML02 Data Poisoning Attack, ML08 Model SkewingChanges training data, once or a little in every retraining2
ML10 Model Poisoning, ML07 Transfer Learning AttackPlants a backdoor in a model that others reuse3
ML01 Input Manipulation AttackChanges an input at run time so the model errs4
ML04 Membership Inference, ML03 Model InversionLearns about training data from the answers5, 6
ML05 Model TheftCopies a model through its answers7
ML06 AI Supply Chain AttacksSwaps or booby-traps a model file, a library or data8, 9, 10
ML09 Output Integrity AttackChanges the model's answer on its way to the usernot built (lesson 8, Field notes)

Lessons 10 and 11 turn the defences into a release process and a scorecard. The defence in every lesson is measured, and so is its price.

Worked example

1. Make the shared module

Every lesson imports from one file, so the data and the split are the same everywhere. New words in the code: numpy (written np) is the library for arrays of numbers. json writes and reads a text format for lists and values. Path is a file path as an object. train_test_split with a fixed random_state and stratify=y gives the same split on every machine ("How AI works", lesson 3). recall_score(..., average=None) gives one recall for each class ("How AI works", lesson 6, shows the recall of one class and the report of all of them). json.dumps(..., default=lambda o: o.item()) tells json how to write a NumPy number that it does not know: lambda makes a small function without a name, and .item() turns the NumPy number into a plain Python one. LogisticRegression(solver="newton-cholesky", tol=1e-10) trains with Newton steps until the weights settle, in about a dozen steps. The default solver stops earlier, and where it stops depends on the maths library of the processor, so the last digits of its weights, and sometimes a printed number, differ from machine to machine. With the Newton solver every processor gives the same model to the digits that the lessons print, so your numbers are the same as they are here.

common.py

"""common.py: the data, the split and the results file that every lesson of the course uses."""
import json
from pathlib import Path

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

RESULTS = Path("results.json")


def digits():
    """1,797 images of 8 by 8 pixels, each pixel 0 to 16. Returns X_train, X_test, y_train, y_test (1,347 and 450)."""
    X, y = load_digits(return_X_y=True)
    return train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)


def logistic(C=1.0):
    """A logistic regression that the Newton solver trains until it has settled: every processor gives the same weights to the printed digits."""
    return LogisticRegression(C=C, solver="newton-cholesky", tol=1e-10, max_iter=100)


def train(X, y, C=1.0):
    """The digits model of the whole course."""
    return logistic(C).fit(X, y)


def recalls(model, X, y):
    """One recall for each class: the share of the true examples that the model finds."""
    return recall_score(y, model.predict(X), average=None)


def record(key, value):
    """Write one measured value into results.json, the one results file of the course."""
    data = json.loads(RESULTS.read_text()) if RESULTS.exists() else {}
    data[key] = value
    RESULTS.write_text(json.dumps(data, indent=2, sort_keys=True, default=lambda o: o.item()) + "\n")


if __name__ == "__main__":
    print(RESULTS.read_text() if RESULTS.exists() else "no results yet")

2. Train the target and keep the numbers

record writes each value into results.json. .argmin() gives the position of the smallest number, which here is the weakest digit.

target.py

"""target.py: train the target model of the course and write its first numbers to results.json."""
import numpy as np

from common import digits, record, recalls, train

X_train, X_test, y_train, y_test = digits()
digit_model = train(X_train, y_train)
accuracy = digit_model.score(X_test, y_test)
per_class = recalls(digit_model, X_test, y_test)
print("digits   train", len(y_train), " test", len(y_test), " accuracy", round(accuracy, 4))
print("recall per digit:", np.round(per_class, 2))
record("digits.accuracy", round(accuracy, 4))
record("digits.worst_recall", round(per_class.min(), 2))
record("digits.worst_class", int(per_class.argmin()))
python3 target.py
digits   train 1347  test 450  accuracy 0.9533
recall per digit: [0.98 0.89 0.98 1.   1.   0.98 0.98 0.98 0.84 0.91]
Recall of the weakest and best digits
Digit 80.84Digit 10.89Digit 90.91Digit 00.98Digit 31.00Digit 80.84Digit 10.89Digit 90.91Digit 00.98Digit 31.00

The model scores 0.9533, and its weakest digit is the 8, with a recall of 0.84. These two numbers are your baseline: an attack has worked when a number moves away from them.

3. Read the results file

common.py prints the file when you run it as a program. It has three keys now. From now on every lesson adds its own.

python3 common.py
{
  "digits.accuracy": 0.9533,
  "digits.worst_class": 8,
  "digits.worst_recall": 0.84
}

Your turn

The lead wants a second baseline on a different split. Write mytarget.py that imports from common.py. Split the digits with test_size=0.5, random_state=42 and stratify=y, train the model on the first half, and score it on the second half. digits() has a fixed split. For another one, call load_digits(return_X_y=True) and train_test_split yourself. Do not name a file after a Python library (inspect.py, json.py, random.py): Python would load your file instead of the library.

Last, add the three numbers to results.json with record, under keys of your own.

Check yourself

Why does the course train its own models instead of attacking a model that you download?

You can only measure an attack and its defence when you know the truth: the clean data, the clean labels and the clean model. With your own model you do. You also never attack a system that is not yours.

Why is the split fixed with random_state=42 in every lesson?

A different split gives different numbers. When the attack moves a number by two points, you must be sure that the attack did it and not the split. A fixed split and fixed seeds also make your numbers equal to the numbers of this course.

At which stage of the life does a flipped label enter, and at which does a stolen copy start?

A flipped label enters with the data, before training. A copy starts at the service, when someone sends queries and keeps the answers. The stage tells you which defence fits: checks on data for the first, limits and monitoring on queries for the second.

Why do you record the weakest class and not only the accuracy?

Accuracy averages over all classes. An attack that harms one class moves the average very little. Lesson 2 shows this: at a flip of 20 percent the accuracy falls by one point while the recall of the 8 falls by twelve.

Field notes

  • The attack names of this course also appear in NIST AI 100-2, "Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations", and in MITRE ATLAS. Use the shared names in reports, so that other teams can find the same attack in the same place.
  • Keep one results file and one fixed split from the first day of a project. A review a year later needs the baseline, not a new guess of it.
  • The table lists attacks on models that you train. Attacks on language models (prompt injection, leaks from prompts) have their own courses: "Securing LLM applications" and "Securing AI agents and MCP".
  • Every model here is small on purpose. The ideas carry over to large models, but the numbers do not. Never quote a number of this course as the rate of an attack on another model.