TExcelTAD
Home › Security Research: Fuzzing, Vulnerability Discovery, Kernel, Browser & AI Security › Adversarial Examples, Model Extraction and Membership Inference

Adversarial Examples, Model Extraction and Membership Inference

Once a model is deployed, attackers interact with it through its inputs and outputs, and each direction is an attack surface. Inputs can be nudged so the model makes a chosen mistake: adversarial examples, or "evasion". Outputs leak information: enough answers let an attacker copy the model (extraction), and the model's confidence reveals whether a given record was in its training data (membership inference). The ML course's Security of ML Systems demonstrates all three on small models; this lesson takes the researcher's angle on two of them. It measures an attack and a guarantee for adversarial examples, and builds a monitor that notices extraction.

Adversarial examples and what "robust" can mean

For a model with a gradient, the fast gradient sign method (FGSM, Goodfellow and colleagues, 2014) moves every input feature by a step ϵ\epsilon in the direction that increases the loss. For a linear model f(x)=w⋅x+bf(x) = w \cdot x + b the picture is exact: under a perturbation of at most ϵ\epsilon per feature (an L∞L_\infty ball), the score can change by at most ϵ∥w∥1\epsilon \lVert w \rVert_1, so an input is provably robust at ϵ\epsilon if

∣w⋅x+b∣>ϵ∥w∥1\lvert w \cdot x + b \rvert > \epsilon \lVert w \rVert_1

and FGSM is the worst-case attack: it achieves exactly that change. For a linear model, the measured accuracy under FGSM and the certified robust accuracy (correct and provably unflippable) must therefore be equal. Deep networks don't allow such a neat bound, and there FGSM is only one of many attacks (iterative ones such as PGD are stronger); certification methods for them exist but are expensive and loose.

Measuring attack and guarantee, and watching for extraction

The example trains a logistic regression on a synthetic 6-feature dataset (fixed seeds). Part 1 computes, for every test point, the smallest step that flips it, then compares FGSM accuracy with certified accuracy for four values of ϵ\epsilon. Part 2 attacks a label-only API: 300 broad random queries train a surrogate model, and a cheap query monitor compares an honest client with the extraction client by the share of queries that fall outside the range of features ever seen in training. It runs in your browser:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=1200, n_features=6, n_informative=4, random_state=1)
X_tr, y_tr, X_te, y_te = X[:800], y[:800], X[800:], y[800:]
clf = LogisticRegression().fit(X_tr, y_tr)
w, b = clf.coef_[0], clf.intercept_[0]

# 1. Adversarial examples on a linear model. FGSM moves every feature by eps in the direction that
#    increases the loss for the true label;
#    for a linear model the smallest L-infinity step that flips x is exactly |w.x + b| / ||w||_1.
margin = X_te @ w + b
needed = np.abs(margin) / np.abs(w).sum()
correct = clf.predict(X_te) == y_te
print(f"test accuracy {correct.mean():.3f}; median step to flip a correct prediction: {np.median(needed[correct]):.3f}")
for eps in (0.05, 0.1, 0.2, 0.4):
    x_adv = X_te - eps * np.sign(w) * (2 * y_te - 1)[:, None]      # FGSM: step that raises the loss
    acc = (clf.predict(x_adv) == y_te).mean()
    certified = (correct & (needed > eps)).mean()                    # provably unflippable at eps
    print(f"  eps {eps:.2f}: accuracy under FGSM {acc:.3f}, certified robust accuracy {certified:.3f}")

# 2. Model extraction through a label-only API, and a query monitor that notices it.
rng = np.random.default_rng(0)
lo, hi = X_tr.min(axis=0), X_tr.max(axis=0)
def outside_share(Q):
    """Share of queries outside the range of features ever seen in training (a cheap monitor)."""
    return ((Q < lo) | (Q > hi)).any(axis=1).mean()

honest = X_te[:300] + rng.normal(0, 0.1, (300, 6))                   # users send realistic inputs
attacker = rng.normal(0, 3, (300, 6))                                # extraction: broad random probes
surrogate = LogisticRegression().fit(attacker, clf.predict(attacker))
agree = (surrogate.predict(X_te) == clf.predict(X_te)).mean()
print(f"surrogate from 300 label-only queries agrees with the model on {agree:.3f} of test inputs")
for who, Q in (("honest client", honest), ("extraction client", attacker)):
    share = outside_share(Q)
    print(f"  monitor, {who:<17}: {share:.2f} of queries outside the training range -> {'ALERT' if share > 0.2 else 'ok'}")
test accuracy 0.780; median step to flip a correct prediction: 0.638
  eps 0.05: accuracy under FGSM 0.748, certified robust accuracy 0.748
  eps 0.10: accuracy under FGSM 0.725, certified robust accuracy 0.725
  eps 0.20: accuracy under FGSM 0.665, certified robust accuracy 0.665
  eps 0.40: accuracy under FGSM 0.532, certified robust accuracy 0.532
surrogate from 300 label-only queries agrees with the model on 1.000 of test inputs
  monitor, honest client    : 0.01 of queries outside the training range -> ok
  monitor, extraction client: 0.50 of queries outside the training range -> ALERT
  • The two accuracy columns are identical, as the theory predicts: on a linear model FGSM is optimal and the certificate is tight. At ϵ=0.4\epsilon = 0.4 (well below the median flipping step of 0.638), accuracy falls from 0.780 to 0.532. The certificate turns "we tried an attack and it failed" into "no attack within ϵ\epsilon can succeed on these inputs", which is the kind of claim a security argument needs.
  • Extraction is cheap for a simple model: 300 label-only answers give a surrogate that agrees with the original on every test input. Returning labels instead of probabilities did not prevent it.
  • The monitor sees what the extraction client must do to learn the decision boundary: probe widely, including regions where no real input lives. Half of its queries lie outside the training range; the honest client's realistic inputs almost never do (0.01).

Membership inference, briefly

A model that overfits is more confident on the rows it memorised than on new ones, and that difference lets an attacker test whether a particular person's record was in the training set, a privacy breach by itself when the dataset is sensitive (patients of a clinic, customers of a debt collector). The ML course measures it with an attack AUC. For large language models, the same idea appears as training-data extraction: rare sequences that were memorised can be reproduced verbatim. Defences: regularisation and early stopping, deduplication of training data, differential privacy in training, and limiting what the API reveals (no raw probabilities, rounded scores).

How these attacks are detected

Attack Signals
adversarial inputs inputs near the decision boundary or outside the data range; disagreement between the model and a second, differently trained model; unusual feature combinations; for images, statistics that natural images don't have
extraction high query volume per key, queries spread over the whole input space (as in the monitor), systematic grids or boundary-hugging sequences, many near-duplicate queries
membership inference repeated queries for specific records with small variations; hard to see in isolation, which is why prevention in training matters more

How the risks are reduced

  • Adversarial examples: validate inputs against plausible ranges and combinations; use features an attacker cannot easily change; adversarial training (train on attacked inputs); certified methods where a guarantee is required; and, above all, don't let a single model's output be the only control for a security decision (combine it with rules and human review).
  • Extraction: authentication and per-key rate limits, quotas and anomaly monitoring (LLM10 Unbounded Consumption covers the cost side), coarse outputs, watermarking of models or outputs to prove a copy in court, and legal terms.
  • Membership inference: regularise, deduplicate, train with differential privacy for sensitive data, return as little as needed.

Pitfalls

  • Robustness claims from one attack. "FGSM didn't flip it" is not robustness for a deep network; use stronger attacks or certificates.
  • Thinking labels-only stops extraction. It slows it; for simple models it hardly matters, as the example shows.
  • Monitors that are trivial to evade. A careful attacker stays inside the training range; combine volume, diversity and boundary-proximity signals.
  • Testing a production API you don't own. Extraction and evasion experiments against a third party's model are unauthorised testing; run them on your own model.

Practice

1. Compute the certificate threshold in the example: what eps would make certified accuracy 0?

Certified accuracy reaches 0 when ϵ\epsilon exceeds the largest flipping step among the correctly classified points, needed[correct].max(). Every correct point can then be flipped by FGSM too.

2. The extraction client limits its queries to the training range. What happens to the monitor, and what would you add?

The out-of-range share drops to near 0, so this monitor no longer fires. Add per-key volume and diversity measures (how much of the input space one key covers), and track queries close to the decision boundary, which extraction needs and normal users rarely produce.

3. Why does a certificate need the model's weights, while FGSM only needs gradients?

The certificate bounds the worst case over all perturbations in the ball, which for a linear model needs ∥w∥1\lVert w \rVert_1, a property of the whole model. FGSM tries one perturbation, so it needs only the gradient at one point. Defenders have the weights; that asymmetry is what makes certification a defender's tool.

Test yourself

For a linear model under an L-infinity perturbation of size eps, when is an input provably robust?

  1. When it is correctly classified
  2. When its margin |w.x + b| exceeds eps times the L1 norm of w
  3. When eps is below 0.1
  4. Never

Why were FGSM accuracy and certified accuracy identical in the example?

  1. A coincidence
  2. For a linear model FGSM achieves the worst-case change, so the certificate is tight
  3. The model was robust
  4. The dataset was small

What did the extraction monitor measure?

  1. Response time
  2. The share of a client's queries outside the range of training features
  3. The number of users
  4. Model accuracy

Which training practice most directly reduces membership inference?

  1. Larger learning rate
  2. Regularisation, deduplication and differential privacy
  3. More epochs
  4. Returning raw probabilities