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 07 · 45 minutes

Steal a model through its API and detect it

After this lesson you can
  • Copy a model from its labels alone and measure how faithful the copy is for 10 to 225 queries
  • Detect extraction in a query log by rate and by near-duplicate queries
  • Plant a watermark, and say what it proves and what it cannot prove
Lab files of this lesson (10)

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 sells its digit reader as a paid web service. A competitor launches a reader that behaves oddly like yours. Your lead asks: "Could they have copied our model by calling our service? Would our logs show it? And if we suspect it, how do we prove that it is ours?" You copy your own model through its own interface, search a day of queries for the thief, and plant a secret that only the owner knows.

Recall

Lesson 6: how did a label-only service change the inversion result?

With scores the attacker recognised 10 of 10 digits, and with labels only 0. Showing less gives the attacker less to climb on. It does not remove the need for a query limit, which is this lesson.

Lesson 4: why is a query a cost that a defender can use?

A black-box attacker needs many queries. A service that counts and limits them can slow the attacker or see them. This lesson watches the queries.

The idea

Model theft (also called extraction) copies the behaviour of a model without access to its files. The thief owns images, sends them to the service, keeps the answers as labels, and trains a copy on them. A copy is worth money, and it is a platform for white-box attacks: evasion examples built on a copy often work on the original.

The measure is fidelity: the share of images on which the copy gives the same label as the original. Here the victim is a random forest with an accuracy of 0.98, and the copy is a logistic regression, a different kind of model. Three defences follow the three questions of the scenario. Limit the queries. Detect the pattern in the log. Prove ownership with a watermark.

Theft through the interface
CompetitorAPICopyMarketimages that it ownsone label for each imagetrain on the images and labelsa model of the same behavioursells the copy as its ownCompetitorAPICopyMarket12345
  1. Competitor → API: images that it owns
  2. API → Competitor: one label for each image
  3. Competitor → Copy: train on the images and labels
  4. Copy → Competitor: a model of the same behaviour
  5. Competitor → Market: sells the copy as its own

Worked example

1. Write the theft, the detector and the watermark

New words in the code:

  • logistic() is the course's logistic regression (lesson 1).
  • lambda q: q[1] is a function without a name, here "the second item of q", and sorted(..., key=...) uses it to order the log by time.
  • np.linalg.norm(a - b, axis=1) is the distance between images.
  • copy.copy(model) makes a second object with the same parts, and half_the_trees then cuts its list of trees.
  • binom.sf(9, 20, 0.1) is the chance of more than 9 right answers in 20 guesses that each have a chance of 0.1. A set such as {q[0] for q in log} holds each value once.
  • make_log writes one day of queries (86,400 seconds) by five clients: three ordinary users, a scraper that asks fast, and a prober that asks slowly and sends small changes of the same images.
  • profile counts three things for each client, and flagged applies two rules.
  • A watermark is a set of secret inputs with secret answers that the owner trains into the model: random noise images with random labels.

steal.py

"""steal.py: copy a model through its answers, see the theft in the query log, and mark the model with a watermark."""
import copy

import numpy as np
from scipy.stats import binom
from sklearn.ensemble import RandomForestClassifier

from common import digits, logistic, record

X_train, X_test, y_train, y_test = digits()
EVAL, POOL = X_test[:225], X_test[225:]     # the owner's check images, and the images that the thief owns


def forest(X, y):
    return RandomForestClassifier(n_estimators=50, random_state=0).fit(X, y)


def copy_from(victim, queries):
    """The theft: send `queries` of the thief's images to the API, keep only the labels, train a copy on them."""
    return logistic().fit(POOL[:queries], victim.predict(POOL[:queries]))


def fidelity(clone, victim, X=EVAL):
    """Share of images on which the copy gives the same label as the victim."""
    return (clone.predict(X) == victim.predict(X)).mean()


def make_log(seed=0):
    """One day of queries to the API as (client, seconds, image): three ordinary users, a scraper that asks
    quickly, and a prober that asks slowly and sends small variations of the same images."""
    rng = np.random.default_rng(seed)
    log = []
    for client in ("ana", "ben", "caro"):
        for i in rng.choice(len(POOL), 8, replace=False):
            log.append((client, float(rng.uniform(0, 86400)), POOL[i]))
    for k, i in enumerate(rng.choice(len(POOL), 150, replace=False)):
        log.append(("scraper", 3.0 * k, POOL[i]))
    base = rng.choice(len(POOL), 50, replace=False)
    for k in range(150):
        image = POOL[base[k % 50]]
        if k >= 50:
            image = np.clip(image + rng.normal(0, 0.5, 64), 0, 16)
        log.append(("prober", 40.0 * k, image))
    return sorted(log, key=lambda q: q[1])


def profile(log):
    """For each client: the number of queries, the queries a minute, and the share of queries that are within
    distance 8 of an earlier query of the same client."""
    out = {}
    for client in sorted({q[0] for q in log}):
        mine = [q for q in log if q[0] == client]
        images = np.array([q[2] for q in mine])
        near = sum(np.linalg.norm(images[:i] - images[i], axis=1).min() < 8 for i in range(1, len(images)))
        span = max(mine[-1][1] - mine[0][1], 60) / 60
        out[client] = (len(mine), len(mine) / span, near / len(mine))
    return out


def flagged(stats, per_minute=10, near_share=0.3, minimum=20):
    """Rule 1: asks too fast. Rule 2: many queries, and many of them are near copies of earlier ones."""
    return [c for c, (n, rate, near) in stats.items() if rate > per_minute or (n >= minimum and near > near_share)]


def watermark(seed=7, n=20):
    """Secret inputs: random noise images with random labels that only the owner knows."""
    rng = np.random.default_rng(seed)
    return rng.integers(0, 17, (n, 64)).astype(float), rng.integers(0, 10, n)


def hits(model, marks):
    """How many of the secret inputs the model answers with the owner's secret label."""
    return int((model.predict(marks[0]) == marks[1]).sum())


def half_the_trees(model):
    """A thief's copy of the file with the second half of the trees cut away."""
    cut = copy.copy(model)
    cut.estimators_ = model.estimators_[:len(model.estimators_) // 2]
    return cut


if __name__ == "__main__":
    victim = forest(X_train, y_train)
    print(f"1. a copy trained on the API's labels (the victim has accuracy {victim.score(X_test, y_test):.2f})")
    print("queries  fidelity")
    for n in (10, 25, 50, 100, 225):
        print(f"{n:<9}{fidelity(copy_from(victim, n), victim):.2f}")
    record("steal.fidelity_225", round(fidelity(copy_from(victim, 225), victim), 2))

    stats = profile(make_log())
    print("2. the query log")
    print("client   queries  per minute  near copies")
    for client, (n, rate, near) in stats.items():
        print(f"{client:<9}{n:>6}{rate:>11.1f}{near:>13.2f}")
    print("flagged:", flagged(stats))

    marks = watermark()
    owner = forest(np.vstack([X_train, marks[0]]), np.concatenate([y_train, marks[1]]))
    print("3. watermark: secret answers out of", len(marks[1]))
    print("model                    accuracy  secret hits")
    for name, model in (("owner's model", owner), ("a copy with half the trees", half_the_trees(owner)),
                        ("a model trained alone", victim), ("a copy made by queries", copy_from(owner, 225))):
        print(f"{name:<28}{model.score(X_test, y_test):>5.2f}{hits(model, marks):>13}")
    print("chance of 10 or more hits by guessing:", f"{binom.sf(9, len(marks[1]), 0.1):.1e}")
    record("steal.watermark_hits_owner", hits(owner, marks))

2. Run it

python3 steal.py
1. a copy trained on the API's labels (the victim has accuracy 0.98)
queries  fidelity
10       0.45
25       0.62
50       0.78
100      0.90
225      0.96
2. the query log
client   queries  per minute  near copies
ana           8        0.0         0.00
ben           8        0.0         0.00
caro          8        0.0         0.00
prober      150        1.5         0.67
scraper     150       20.1         0.00
flagged: ['prober', 'scraper']
3. watermark: secret answers out of 20
model                    accuracy  secret hits
owner's model                0.96           20
a copy with half the trees   0.96           20
a model trained alone        0.98            3
a copy made by queries       0.95            2
chance of 10 or more hits by guessing: 7.2e-06

3. Read the theft

Fidelity of the copy by number of queries
10 queries0.4525 queries0.6250 queries0.78100 queries0.90225 queries0.9610 queries0.4525 queries0.6250 queries0.78100 queries0.90225 queries0.96

The copy needs the thief's own images and the labels. With 10 queries the copy agrees with the victim on 45 images in 100. With 100 queries it agrees on 90, and with 225 on 96. The victim's accuracy is 0.98, so 225 queries buy a copy that is nearly as good as the original, and the copy never saw the training data or the code. Returning labels only did not prevent this. It limits what the thief learns from each query, and does not limit the number of queries.

4. Read the log

Ana, Ben and Caro each sent 8 queries in a day: no flag. The scraper sent 150 queries at 20 a minute, so rule 1 catches it. The prober sent 150 queries at 1.5 a minute, which no rate limit would stop, but 67 percent of its queries are within distance 8 of an earlier query of its own, so rule 2 catches it. Real users rarely send many near-copies of one image. A patient thief with new images and a low rate looks like a user: the detector sees a pattern, never an intention. Use it to start a review, and to decide whether to slow the client.

5. Read the watermark

Secret hits out of 20
Owner's model20Copy with half the trees20Model trained alone3Copy made by queries2Owner's model20Copy with half the trees20Model trained alone3Copy made by queries2

The owner's model answers all 20 secret inputs, and it costs two points of accuracy (0.96 against 0.98). A thief who cuts the forest to half of its trees still has all 20 marks, since every tree has learned most of them. A model trained alone gets 3 right, which is what chance gives (20 inputs, 10 labels, so about 2). The last line gives the rule: the chance of 10 or more hits by guessing is 7.2 in a million, so accuse a model of carrying the mark at 10 or more of 20. The last row is the limit: a copy made through the API with natural images does not carry the watermark either (2 of 20). The watermark proves theft of the file or the weights. It does not prove theft by queries, unless the thief also queried the secret inputs. The test covers one kind of thief, a cut copy. A thief who retrains or tunes the model for long may remove the mark, so test the thieves that you expect.

Treat the secret inputs like a key: if they leak, the proof is gone.

Your turn

Repeat the three measurements with other settings. First, the fidelity of a copy made with 75 queries (copy_from(victim, 75)). Second, call flagged on the profile with a rate limit of 25 a minute (per_minute=25) and keep the other rule. Third, make a watermark with watermark(seed=3, n=10), train the owner's forest on the training data and the 10 marks, and count the secret hits of the owner's forest and of the forest victim that has no marks.

Then write one sentence on how you would use the prober's log in a conversation with that client.

Check yourself

Why does a label-only service not stop extraction?

The copy in this lesson was trained on labels only, and it reached a fidelity of 0.96. A label gives less information than a probability, so a thief needs more queries, but there is still enough. The defences are a limit and a watcher on the queries.

A rate limit of 10 queries a minute would stop the scraper. Why not the prober?

The prober asks 1.5 times a minute. It needs about two hours for the same 150 queries, instead of seven minutes. A thief that wants 1,000 queries needs about eleven hours, which no limit of 10 a minute stops. A rate limit slows a thief, and a pattern check on the content of queries (near-copies, a sweep over the input space) sees the one who is patient.

What does the watermark prove, and what does it not?

If a suspect model gives the owner's secret answers on many secret inputs, it is a copy of the owner's weights, because chance gives about 2 of 20, and 10 or more has a chance of 7 in a million. It does not show that a model trained on API labels was stolen, since such a copy does not carry the secret. It also proves nothing if the secret inputs have leaked.

What does the detector do wrong on a legitimate customer who tests a new camera on 200 similar images?

It flags that customer: a false positive. The review step is for this. A flag starts a human check or a slower rate, and it should never close an account by itself. Give customers a way to say who they are.

Field notes

  • The OWASP Machine Learning Security Top Ten lists this as ML05 Model Theft. The measure to report is fidelity at a number of queries, not "it can be stolen".
  • Prices and terms are a control as well. A contract that forbids building a competing model from the answers is a basis for action if the logs prove it, and the logs of this lesson are that proof.
  • Stronger controls: authenticate every client, rate limit for each client and for all clients together, return the least detail that the use needs, and add small noise to scores if they must be shown. Each costs usefulness, so measure it as in lesson 6.
  • Keep logs of queries long enough to see a slow thief, and protect them: they hold the thief's images and your customers' images too.