Lesson 11 · 45 minutes
Build a model security scorecard
- Build one command that grades a model folder on five areas
- Read a scorecard of a good and of a damaged folder, and say what each failing line asks you to do
- State what the scorecard measures, what it assumes and what it leaves out
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 now has seven gates, but a manager does not want seven outputs. The manager wants one page for each model, with the same five questions every time, so that two models can be compared and a model can be compared with itself a month later. Your lead asks you to build that page as a command, using the whole course. It is the build of this course, and it is also the report that you would hand to an owner.
Recall
Lesson 10: why does the file gate come before the data gate and the model gates?
A file that fails the format or the hash check must not be opened by the other gates. Opening an untrusted file is the risk that the file gate exists to avoid.
Lesson 4: which attack does the robustness line of the scorecard use, and how many queries?
The black-box search of lesson 4, with 100 queries. The card runs it on the model that it grades, and prints the accuracy that remains next to the limit.
The idea
A scorecard grades one thing on a few questions that are always the same. Each area has a measure, a limit and a verdict, and an overall line. The five areas come from the attack families of lesson 1.
| Area | Measure | Limit | Built in |
|---|---|---|---|
| robustness | accuracy after 100 black-box queries | at least 0.40 | lesson 4 |
| privacy | accuracy of a membership attack | at most 0.60 | lesson 5 |
| integrity | worst class recall, and the data gate | at least 0.80, no data problem | lessons 2, 10 |
| backdoor scan | largest share moved by one patch | at most 0.60 | lesson 3 |
| file safety | no pickle, hash matches, record complete | all three | lessons 8, 10 |
The robustness limit is a stated policy: the owner accepts that 100 queries take away at most 60 points of accuracy, so the floor is 0.40. The scorecard adds no new attack. It runs the measures of the earlier lessons in one order on one folder, and it prints the same lines every time. It uses the folder of lesson 10 (model.json, train.npz, provenance.json), and it gets its trusted data from the course split. It opens the model with the hash of the file itself, so the loader checks only the format and the content. The hash in the record is checked by the file area, after the other areas have read the file. A swapped file cannot run code, but its numbers are graded before the file line fails: read that line first.
- Model folder → Robustness: 100 black-box queries (4)
- Robustness → Privacy: membership attack (5)
- Privacy → Integrity: worst class recall, data gate (2, 10)
- Integrity → Backdoor scan: a patch at every place (3)
- Backdoor scan → File safety: no pickle, hash, record (8, 10)
- File safety → Grade: areas passed, exit code 0 or 1
Worked example
1. Write the scorecard
scorecard.py is short, because the lessons already built what it calls. It reads the folder, opens the model with the loader of lesson 8, runs the five measures and prints one line for each. New words in the code: next(generator, None) takes the first item that a loop finds, or None. ("privacy", *privacy_gate(...)) puts the items of a pair into the tuple after the area name. folder.iterdir() lists the files of a folder. sum(p for ...) counts the passes, since True counts as 1.
scorecard.py
"""scorecard.py: grade a model folder on five areas. Exit code 0 when all five pass, 1 otherwise.
python3 scorecard.py ship the folder holds model.json, train.npz and provenance.json
"""
import json
import sys
from pathlib import Path
import numpy as np
from common import digits
from evade import search
from gates import backdoor_gate, class_gate, data_gate, file_gate, privacy_gate, provenance_gate
from safeload import Refused, load_model, sha256_of
ROBUST_LIMIT = 0.40 # accuracy that must remain after 100 black-box queries
def read_record(folder):
try:
record = json.loads((folder / "provenance.json").read_text())
except (OSError, ValueError):
return {}
return record if isinstance(record, dict) else {}
def file_area(folder):
"""File safety: no pickle in the folder, the hash matches the record, the record is complete."""
pickles = sorted(p.name for p in folder.iterdir() if p.suffix in (".pkl", ".pickle", ".joblib"))
if pickles:
return False, "pickle file: " + ", ".join(pickles)
record = read_record(folder)
if not record:
return False, "no provenance.json"
for ok, detail in (file_gate(folder, record), provenance_gate(folder, record)):
if not ok:
return False, detail
return True, "format allowed, hash matches, record complete"
def grade(folder):
"""Return a list of (area, passed, detail)."""
folder = Path(folder)
rows = []
path = next((folder / n for n in ("model.json", "model.npz", "model.safetensors") if (folder / n).exists()), None)
ok, detail = file_area(folder)
if path is None or not (folder / "train.npz").exists():
skipped = "not graded: no model file and train.npz to open"
return [(a, False, skipped) for a in ("robustness", "privacy", "integrity", "backdoor scan")] + [("file safety", ok, detail)]
try:
model = load_model(path, sha256_of(path)) # the file's own hash: only the format and content checks. file_area checks the hash of the record
except Refused as reason:
return [("file safety", False, str(reason))]
with np.load(folder / "train.npz", allow_pickle=False) as d:
X, y = d["X"], d["y"]
_, X_val, _, y_val = digits() # the trusted data stays on our side
attacked = model.score(search(model.predict_proba, X_val[:100], y_val[:100], 100), y_val[:100])
rows.append(("robustness", attacked >= ROBUST_LIMIT, f"accuracy after 100 black-box queries {attacked:.2f}, limit {ROBUST_LIMIT}"))
rows.append(("privacy", *privacy_gate(model, X, X_val)))
(c_ok, c_detail), (d_ok, d_detail) = class_gate(model, X_val, y_val), data_gate(X, y)
rows.append(("integrity", c_ok and d_ok, c_detail + ("" if d_ok else "; data: " + d_detail)))
rows.append(("backdoor scan", *backdoor_gate(model, X_val)))
rows.append(("file safety", ok, detail))
return rows
if __name__ == "__main__":
rows = grade(sys.argv[1])
for area, passed, detail in rows:
print(f"{area:<14}{'pass' if passed else 'FAIL'} {detail}")
print(f"grade: {sum(p for _, p, _ in rows)} of {len(rows)} areas pass")
sys.exit(0 if all(p for _, p, _ in rows) else 1)The files that the card uses are the finished files of the whole course: common.py (lesson 1), poison.py (2), backdoor.py (3), evade.py (4), leak.py (5), safeload.py (8), gates.py (10). Each was printed whole in its lesson, and none changed.
2. Grade the good folder
python3 scorecard.py ship; echo "exit code $?"robustness pass accuracy after 100 black-box queries 0.45, limit 0.4
privacy pass membership attack right 0.56, limit 0.6
integrity pass worst class 8, recall 0.84, floor 0.8
backdoor scan pass largest move 0.25 to class 3 at (5,5), limit 0.6
file safety pass format allowed, hash matches, record complete
grade: 5 of 5 areas pass
exit code 0One line of the card, taken apart:
The model of the course passes all five areas, and the robustness pass is thin: 0.45 against a limit of 0.40. Your turn in lesson 4 shows that 300 queries take this model to zero. The limit says what you accepted at 100 queries. It does not say that the model is robust.
3. Grade a damaged folder
Make the folder of lesson 10 again, with the poisoned data file, and grade it.
python3 makebad.pypython3 scorecard.py ship-bad; echo "exit code $?"robustness pass accuracy after 100 black-box queries 0.45, limit 0.4
privacy pass membership attack right 0.56, limit 0.6
integrity FAIL worst class 8, recall 0.84, floor 0.8; data: 131 duplicate images
backdoor scan pass largest move 0.25 to class 3 at (5,5), limit 0.6
file safety FAIL the data file is not the one in the record
grade: 3 of 5 areas pass
exit code 1Two areas fail. File safety says that the data is not the one in the record, and integrity says that the data has 131 duplicate images. The model is the clean one, so the model measures pass. This is how the scorecard reads a damaged supply chain: the failing lines point to the data, the model is not at fault, and the fix is to restore the data from the record. If a failing line named the model, you would look at the model.
4. Read what it does not say
A pass on all five areas means "these five measures are within these five limits". It does not say that the model is good. The card does not retrain from the recorded data (the reproduce gate of lesson 10), and it does not test a trigger of another shape than the scan's, an attacker who sees more than the scan, the quality of the trusted set, bias, drift or the service around the model. Put such a list in every report that includes the card.
Your turn
Make a weaker model and grade it. Copy ship.py to weak.py and change it so that the model and the data use only the first 250 images of the training set (X_train[:250], y_train[:250]). Run python3 weak.py weak and then python3 scorecard.py weak.
Read the robustness line too: it is higher than for the full model. A model that saw fewer images learned smaller weights, so a change of one pixel moves its scores less and 100 queries take less from it. That does not make it a better model: the line says how far this attack moves this model, not how good the model is. Then write the two lines that you would put at the top of a report to the owner of the weak model.
Check yourself
Why does the scorecard print the measure next to the limit and not only pass or fail?
A reader can then see a thin pass (0.45 against 0.40) and a clear fail. The same verdict can hide a very different distance to the limit. A trend over months is also visible in the measure, but not in a bare verdict.
The weak model passes the backdoor scan. Does that clear it of a backdoor?
No. It says that no 2 by 2 bright patch moves more than 0.60 of the predictions. The weak model showed 0.23, and the clean model 0.25. A trigger of another shape or size is not searched, and a model of another kind can show larger natural shares (lesson 3). Read the scan result as the absence of one kind of evidence.
Who should choose the limits, and why not the author of the model?
The owner of the risk, with the security team. An author wants to ship. The limits come from what a failure would cost and from the clean models of the same kind, as in lesson 3. They are recorded and reviewed.
What would you add first to make the card more useful in a real project?
Output in a machine-readable form (a JSON file for each run, stored with the release) so that results can be compared over time, and a line for each area that says who is responsible for a fix. Then more measures, for example fairness, drift and an attack with stronger knowledge.
Field notes
- Keep the card small and stable. A card that changes its measures every month cannot be compared with last month's card. Add a version number to its output.
- Grade the whole path, not only the model: the data source, the training code, the file, the service. The areas here cover the model and its file. Lesson 12 shows a case where the file and the record decide the result.
- A pass at a threshold is only as honest as the attack behind it. Improve the attacks (more queries, stronger scans, other triggers) before you tighten the limits.
- The OWASP Machine Learning Security Top Ten, the NIST report on attacks on machine learning (NIST AI 100-2) and MITRE ATLAS are good sources for a longer list of areas. Take the current text from each source.