Algorithm Search⌘K

Algorithmadvanced

Membership inference attack

Also called shadow model attack.

Decides whether a record was in a model's training set from the model's output on it; the classic method fits its decision rule on shadow models trained on similar data.

Time
O(k s m d + k m log(k m)) worst
Space
O(k m + d) extra
Where
d = the dimension; k = the number of shadow models; m = the number of points per shadow set; s = the number of training steps per model
Properties
deterministicnot exactofflineiterative
Origin
Reza Shokri, Marco Stronati, Congzheng Song, Vitaly Shmatikov, 2017

A membership inference attack decides, from the output of a trained model on a record (x,y)(x, y), whether that record was in the training set. Shokri, Stronati, Song and Shmatikov (2017) gave the classic method: the attacker trains shadow models the same way as the target, on data that the attacker owns, so that for these models it knows which records are members. It then learns a rule that tells the outputs on members from the outputs on nonmembers, and applies the rule to the target. The attack works because a model usually fits its own training points better than new points, so its overfitting leaks membership. The quality of the attack is a measurement; the theorems on this page bound it or show that the decision rule is the best of its class.

In plain words

A model was trained on some records, and you want to know if one given record was among them. Models tend to be more sure of the answer on records they have seen.

So you look at how sure the model is about the true label of the record. If it is very sure, you guess "member", and if not, "nonmember". The only question is where to put the cut.

To find the cut, you train your own copies of the model on data you have. For your copies you know which records went in and which did not, so you can see how sure a copy is in each case and pick the cut that separates the two groups best. Then you use that cut on the real model.

The problem

The threat model, in the three parts of Biggio and Roli:

  • Goal of the attacker. Learn whether one chosen record was in the training set. This is a privacy goal: in a medical model, membership alone can say that a person has a condition.
  • Knowledge. Black box access to the output of the target (here the probability of each label), the training procedure, and data from the same distribution as the training data. The attacker does not know the training set.
  • Capability. Query the target on chosen records and train models of its own. The attacker does not change the target or its training data.

The membership game of Yeom et al. (their Experiment 1). Draw a training set SS of nn records from a distribution D\mathcal{D} and train f=A(S)f = A(S). Flip a fair coin bb. If b=0b = 0, draw zz uniformly from SS; if b=1b = 1, draw zz from D\mathcal{D}. The attacker gets zz, ff, nn and D\mathcal{D} and outputs a guess of bb. Its advantage is 2Pr⁡[correct]−12 \Pr[\text{correct}] - 1, which equals

Adv=TPR−FPR=Pr⁡[says member∣b=0]−Pr⁡[says member∣b=1].\text{Adv} = \text{TPR} - \text{FPR} = \Pr[\text{says member} \mid b = 0] - \Pr[\text{says member} \mid b = 1].

A guess that ignores the model has advantage 00, and a perfect attack has advantage 11 (up to the small chance that a fresh draw is also in SS).

Input. Shadow sets D1,…,DkD_1, \ldots, D_k from the same distribution, each of mm records; the training procedure TT; the target model ff; a record (x,y)(x, y).

Output. MEMBER or NONMEMBER. The score of a model gg on a record is c(g,x,y)c(g, x, y), the probability that gg gives the true label yy; the rule says MEMBER when c(f,x,y)≥τc(f, x, y) \ge \tau.

The algorithm

  1. MEMBERSHIP-INFERENCE(D_1, ..., D_k, T, f, x, y)
  2. 1for j = 1 to k do
  3. 2g_j <- T(the first half of D_j)
  4. 3put c(g_j, x', y') into IN for each (x', y') of the first half, and into OUT for each of the second half
  5. 4tau <- the threshold that maximizes TPR - FPR of the rule "score >= tau" on IN and OUT
  6. 5return MEMBER if c(f, x, y) >= tau, else NONMEMBER

Each shadow set is split into a half that the shadow model trains on (members) and a half that it never sees (nonmembers), so the attacker has labelled scores for both cases. Line L4 sorts the scores and sweeps the cut from the top; the candidates are the scores themselves and +∞+\infty, which says MEMBER for nothing. Ties go to the largest τ\tau.

A simplification. Shokri et al. train one neural network per output class as the attack model, on the whole vector of output probabilities. This page and its code use one threshold on the confidence of the true label, as in the threshold attacks of Yeom et al. and of Salem et al. (2019). The structure, shadow models whose membership is known, is the same.

Example

The shadow models give the scores IN ={0.9,0.8,0.7}= \{0.9, 0.8, 0.7\} and OUT ={0.75,0.6,0.5}= \{0.75, 0.6, 0.5\}. The sweep from the top gives:

τ\tau TPR FPR TPR - FPR
0.90.9 1/31/3 00 1/31/3
0.80.8 2/32/3 00 2/32/3
0.750.75 2/32/3 1/31/3 1/31/3
0.70.7 11 1/31/3 2/32/3
0.60.6 11 2/32/3 1/31/3
0.50.5 11 11 00

Two cuts tie at 2/32/3, and line L4 keeps the larger, τ=0.8\tau = 0.8. On the target, the members score 0.95,0.85,0.60.95, 0.85, 0.6 and the nonmembers 0.82,0.55,0.40.82, 0.55, 0.4. The rule says MEMBER for 0.950.95, 0.850.85 and 0.820.82, so TPR =2/3= 2/3, FPR =1/3= 1/3, and the advantage on the target is 1/31/3, less than on the shadow models. The best TPR with FPR 00 is 2/32/3, at the cut 0.850.85.

Correctness

The attack has no correctness in the sense of a right answer: its decisions are guesses, and their quality is a measurement. What is proved is the following.

Theorem (the advantage, Yeom et al., equation (2)). In the membership game, 2Pr⁡[correct]−1=TPR−FPR2\Pr[\text{correct}] - 1 = \text{TPR} - \text{FPR}. It follows from Pr⁡[correct]=12TPR+12(1−FPR)\Pr[\text{correct}] = \tfrac{1}{2}\text{TPR} + \tfrac{1}{2}(1 - \text{FPR}); the proof file gives it.

Theorem (the threshold, proved on this page). Line L4 returns a τ\tau that maximizes TPR - FPR over all thresholds τ∈R∪{+∞}\tau \in \mathbb{R} \cup \{+\infty\}, and the largest such τ\tau among the candidates. The rule changes only at the scores, so the sweep sees every distinct rule. The code computes TPR at a fixed FPR in the same sweep.

Theorem (a model that ignores its data, proved on this page). If the trained model does not depend on SS, every attack has advantage 00. This is the case ϵ=0\epsilon = 0 of the next theorem, and the tests use it as a control.

Theorem (a bound from differential privacy, Yeom et al., Theorem 1). If the training procedure is ϵ\epsilon-differentially private, every attacker has Adv≤eϵ−1\text{Adv} \le e^{\epsilon} - 1.

Heuristic (why a threshold on confidence). If the attacker knew the distribution of the score on members and on nonmembers, the Neyman-Pearson lemma says that the most powerful test at each FPR puts a threshold on the likelihood ratio of the two distributions. A threshold on the confidence is that test only when the ratio grows with the confidence. That is often roughly true on average, but the ratio differs from record to record; the likelihood ratio attack fits it per record.

Proof: The advantage of the membership game, the optimality of the threshold sweep, and the zero advantage against a model that ignores its datafull

Setting. A threshold rule with cut τ∈R∪{+∞}\tau \in \mathbb{R} \cup \{+\infty\} says MEMBER for a score uu when u≥τu \ge \tau. For finite lists IN of nin≥1n_{\text{in}} \ge 1 scores and OUT of nout≥1n_{\text{out}} \ge 1 scores, write tp(τ)=∣{u∈IN:u≥τ}∣\text{tp}(\tau) = \lvert\{u \in \text{IN} : u \ge \tau\}\rvert, fp(τ)=∣{u∈OUT:u≥τ}∣\text{fp}(\tau) = \lvert\{u \in \text{OUT} : u \ge \tau\}\rvert, TPR(τ)=tp(τ)/nin\text{TPR}(\tau) = \text{tp}(\tau)/n_{\text{in}} and FPR(τ)=fp(τ)/nout\text{FPR}(\tau) = \text{fp}(\tau)/n_{\text{out}}.

Claim 1 (the advantage). In the membership game, with a fair coin bb, 2Pr⁡[correct]−1=Pr⁡[MEMBER∣b=0]−Pr⁡[MEMBER∣b=1]2\Pr[\text{correct}] - 1 = \Pr[\text{MEMBER} \mid b = 0] - \Pr[\text{MEMBER} \mid b = 1].

Proof. The guess is correct when it says MEMBER and b=0b = 0, or NONMEMBER and b=1b = 1. So Pr⁡[correct]=12Pr⁡[MEMBER∣b=0]+12(1−Pr⁡[MEMBER∣b=1])\Pr[\text{correct}] = \tfrac{1}{2}\Pr[\text{MEMBER} \mid b = 0] + \tfrac{1}{2}\big(1 - \Pr[\text{MEMBER} \mid b = 1]\big). Multiply by 2 and subtract 1. □\square

Claim 2 (every rule is a candidate). Let UU be the set of distinct scores of IN and OUT. For every τ\tau there is a τ′∈U∪{+∞}\tau' \in U \cup \{+\infty\} with τ′≥τ\tau' \ge \tau and the same decision on every score of IN and OUT.

Proof. If no score is ≥τ\ge \tau, take τ′=+∞\tau' = +\infty: both rules say NONMEMBER for all scores. Else let τ′\tau' be the smallest score that is ≥τ\ge \tau. A score u≥τ′u \ge \tau' is ≥τ\ge \tau. A score u≥τu \ge \tau is a score ≥τ\ge \tau, so u≥τ′u \ge \tau' by the choice of τ′\tau'. So the two rules agree on all scores. □\square

Claim 3 (the sweep). best_threshold returns (τ∗,a∗)(\tau^*, a^*) where a∗=max⁡τ(TPR(τ)−FPR(τ))a^* = \max_\tau (\text{TPR}(\tau) - \text{FPR}(\tau)) over all τ∈R∪{+∞}\tau \in \mathbb{R} \cup \{+\infty\}, and τ∗\tau^* is the largest element of U∪{+∞}U \cup \{+\infty\} that reaches a∗a^*.

Proof. The code sorts the pairs by score in decreasing order and handles the distinct scores u1>u2>⋯>uru_1 > u_2 > \cdots > u_r in turn. Invariant: after the inner loop for uiu_i, tp and fp count the scores of IN and OUT that are ≥ui\ge u_i. It holds after u1u_1, because the inner loop adds exactly the pairs of score u1u_1, and if it holds after ui−1u_{i-1} it holds after uiu_i, because the pairs with score in [ui,ui−1)[u_i, u_{i-1}) are exactly those of score uiu_i. So after uiu_i, tp =tp(ui)= \text{tp}(u_i) and fp =fp(ui)= \text{fp}(u_i), and key =tp(ui) nout−fp(ui) nin=ninnout(TPR(ui)−FPR(ui))= \text{tp}(u_i)\, n_{\text{out}} - \text{fp}(u_i)\, n_{\text{in}} = n_{\text{in}} n_{\text{out}} (\text{TPR}(u_i) - \text{FPR}(u_i)). This is an integer, so the comparisons are exact. The start values τ=+∞\tau = +\infty, key =0= 0, are the values of the cut +∞+\infty, for which tp=fp=0\text{tp} = \text{fp} = 0. The candidates are seen in the order +∞,u1,…,ur+\infty, u_1, \ldots, u_r, from the largest to the smallest, and a candidate replaces the best only when its key is strictly larger. So at the end the best is the first, which is the largest, candidate with the largest key. By Claim 2 every τ\tau gives the same TPR and FPR as some candidate, so this key is the maximum over all τ\tau. Dividing by ninnout>0n_{\text{in}} n_{\text{out}} > 0 gives a∗a^*. □\square

Claim 4 (TPR at a fixed FPR). tpr_at_fpr returns max⁡{TPR(τ):FPR(τ)≤α}\max \{\text{TPR}(\tau) : \text{FPR}(\tau) \le \alpha\} over all τ∈R∪{+∞}\tau \in \mathbb{R} \cup \{+\infty\}, for α≥0\alpha \ge 0.

Proof. The same sweep and invariant give tp(ui)\text{tp}(u_i) and fp(ui)\text{fp}(u_i) after each distinct score, and the code keeps the largest tp(ui)/nin\text{tp}(u_i)/n_{\text{in}} among those with fp(ui)/nout≤α\text{fp}(u_i)/n_{\text{out}} \le \alpha. The start value 00 is the TPR of the cut +∞+\infty, whose FPR is 0≤α0 \le \alpha. By Claim 2 every τ\tau has the TPR and FPR of a candidate, so the maximum over the candidates is the maximum over all τ\tau. □\square

Claim 5 (a model that ignores its data). Suppose the trained model ff is independent of the training set SS, and SS consists of nn independent draws from D\mathcal{D}. Then every attacker has advantage 00.

Proof. Let zz be the challenge. If b=0b = 0, zz is a uniform element of SS, so zz has the law D\mathcal{D}, and since ff is independent of SS, it is independent of zz. If b=1b = 1, zz is a fresh draw from D\mathcal{D}, again independent of ff. So the pair (z,f)(z, f) has the same law in both cases, and so does the guess of any attacker, which is a function of (z,f,n,D)(z, f, n, \mathcal{D}) and of its own coins. Then Pr⁡[MEMBER∣b=0]=Pr⁡[MEMBER∣b=1]\Pr[\text{MEMBER} \mid b = 0] = \Pr[\text{MEMBER} \mid b = 1], and by Claim 1 the advantage is 00. □\square

The algorithm. Lines L1 to L3 collect the scores of the shadow models on their members (IN) and on their nonmembers (OUT); line L4 is best_threshold, so by Claim 3 the cut maximizes TPR - FPR on the shadow scores; line L5 applies the cut to the target. Nothing is claimed about the advantage on the target, which depends on how well the shadow models stand in for it and is measured in the tests. In the test of Claim 5 the targets are trained on other draws, and the measured advantage of −0.025-0.025 on 160 members and 160 nonmembers is sampling noise around the value 00. ■\blacksquare

Complexity

  • Shadow models. kk trainings of ss steps of full batch gradient descent on m/2m/2 points in dimension dd: O(ksmd)O(k s m d).
  • Scores and threshold. kmk m scores at O(d)O(d) each, then one sort: O(kmd+kmlog⁡(km))O(k m d + k m \log(k m)).
  • One decision. O(d)O(d) for one query of the target.
  • Space. O(km)O(k m) scores and O(d)O(d) for one model at a time.

Properties

  • Black box. The attack needs only the output probabilities of the target, not its weights.
  • Average, not per record. One threshold for all records. A record that is hard for every model gets a low score as a member, and an easy one gets a high score as a nonmember.
  • Grows with overfitting. Yeom et al. (Section 3.2) show that the advantage of simple attacks grows with the generalization error; in the tests, a weight penalty lowers the advantage (a measurement).
  • Transfer from shadows to target. The cut is right for the target only if the shadow models behave like it. In the example the advantage falls from 2/32/3 on the shadows to 1/31/3 on the target.

Variants and improvements

  • Attack models per class. Shokri et al. learn a classifier per output class on the whole probability vector, which can use more than the confidence of the true label.
  • Fewer or no shadow models. Salem et al. (2019) use one shadow model, or none, with a threshold on the output of the target.
  • Loss threshold. Yeom et al. put a threshold on the loss of the target on the record. For the log loss −ln⁡c-\ln c, the rule c≥τc \ge \tau is the rule "loss ≤−ln⁡τ\le -\ln \tau", so the confidence threshold of this page is a loss threshold.
  • Likelihood ratio attack. Carlini et al. (2022) fit, per record, the score distributions of shadow models trained with and without that record, and test their ratio. See likelihood-ratio-membership-attack.
  • Defenses. Training with DP-SGD bounds the advantage by the theorem above; regularization and early stopping lower it in practice; PATE trains the released model only on noisy votes. Removal of a record after training is machine unlearning, and a membership attack is one way to test it.

When to use it

Use it to measure the privacy risk of a model that you own or that you train on synthetic data, before you release it, and to check that a defense works. Report the advantage and also the TPR at a low FPR, as Carlini et al. advise, because an attack with a fair average advantage can still fail to identify any single member with confidence. For a strong measurement use the likelihood ratio attack; for a guarantee use differential privacy, since an attack only gives a lower bound on the risk.

Pitfalls

  • Average metrics hide the risk. In the tests the attack has advantage 0.360.36, but at FPR 55 percent its TPR is 0.0560.056, about the FPR itself: it finds members only on average. Report the TPR at a low FPR.
  • The cut overfits the shadows. A cut fitted on few shadow scores is tuned to them; on the target the advantage can be lower, as in the example.
  • Nonmembers from the training distribution. The game draws nonmembers from the same distribution as the members. Nonmembers from another distribution make the attack look stronger than it is, because it can then detect the distribution and not membership.
  • Base rates. The game puts members and nonmembers in equal numbers. When members are rare, even a small FPR gives many more false alarms than true members.
  • No attack is not no risk. A weak attack does not show that the model is private; only a bound such as differential privacy does.

Implementations

The code runs only on logistic models and data that the tests build from a fixed seed, Gaussian blobs in d=8d = 8 dimensions from the shared helper mlkit; it never queries a real model or reads a real data set. The tests check the threshold against a brute force search with exact fractions on 500 random score lists, check TPR at a fixed FPR the same way on 500 lists, and check the example. They then measure the game with seed 7304: 4 shadow sets of 32 points, and 10 target models, each trained on 16 points with 16 fresh nonmembers. With no weight penalty the advantage is 0.36250.3625 and the TPR at FPR 55 percent is 0.0560.056; with the penalty 1.0∥w∥2/21.0 \lVert w \rVert^2 / 2 the advantage is 0.1190.119; and for models trained on other data, which ignore their members, it is −0.025-0.025, sampling noise around the value 00 of the theorem.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

membership_inference_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/membership-inference-attack/. The authors are listed in prov/52KYBB.jsonl.

"""Membership inference with shadow models (Shokri et al. 2017), as an abstract model on synthetic data.

The target and shadow models are logistic regressions from mlkit, trained on Gaussian
blobs that the tests draw from a fixed seed. The attack model is one threshold on the
confidence of the true label, fitted on the shadow models. Nothing here queries a real
model or reads a real data set. Labels are 0 and 1.
"""

import math
from typing import Sequence

from mlkit import Data, dot, sigmoid, train_logistic

Model = tuple[list[float], float]


def confidence(model: Model, x: Sequence[float], y: int) -> float:
    """The probability that the logistic model gives the true label y of x. Cost O(d)."""
    w, b = model
    p = sigmoid(dot(w, x) + b)
    return p if y == 1 else 1.0 - p


def best_threshold(scores_in: Sequence[float], scores_out: Sequence[float]) -> tuple[float, float]:
    """The threshold tau that maximizes TPR - FPR for the rule "member iff score >= tau", and that value.

    The candidates are the scores and +infinity (which says "member" for nothing). Ties
    in the advantage go to the largest tau. Precondition: both lists are nonempty.
    Cost O(m log m) for m scores.
    """
    pts = sorted([(s, 1) for s in scores_in] + [(s, 0) for s in scores_out], reverse=True)
    n_in, n_out = len(scores_in), len(scores_out)
    best_tau, best_key = math.inf, 0  # key = (TPR - FPR) n_in n_out, an exact integer
    tp = fp = 0
    i = 0
    while i < len(pts):
        s = pts[i][0]
        while i < len(pts) and pts[i][0] == s:  # every point with score s passes tau = s
            tp += pts[i][1]
            fp += 1 - pts[i][1]
            i += 1
        key = tp * n_out - fp * n_in
        if key > best_key:
            best_tau, best_key = s, key
    return best_tau, best_key / (n_in * n_out)


def rates(scores_in: Sequence[float], scores_out: Sequence[float], tau: float) -> tuple[float, float]:
    """(TPR, FPR) of the rule "member iff score >= tau". Cost O(m)."""
    tpr = sum(1 for s in scores_in if s >= tau) / len(scores_in)
    fpr = sum(1 for s in scores_out if s >= tau) / len(scores_out)
    return tpr, fpr


def tpr_at_fpr(scores_in: Sequence[float], scores_out: Sequence[float], alpha: float) -> float:
    """The largest TPR of a threshold rule whose FPR is at most alpha. Cost O(m log m)."""
    pts = sorted([(s, 1) for s in scores_in] + [(s, 0) for s in scores_out], reverse=True)
    n_in, n_out = len(scores_in), len(scores_out)
    best = 0.0
    tp = fp = 0
    i = 0
    while i < len(pts):
        s = pts[i][0]
        while i < len(pts) and pts[i][0] == s:
            tp += pts[i][1]
            fp += 1 - pts[i][1]
            i += 1
        if fp / n_out <= alpha:
            best = max(best, tp / n_in)
    return best


def shadow_attack(shadow_sets: Sequence[Data], steps: int, lr: float, l2: float) -> float:
    """Fit the attack threshold on shadow models; each shadow set is split into its first half (in) and second half (out).

    The shadow models use the same training procedure as the target. Precondition: each
    set has at least 2 points. Cost O(k steps m d) for k shadow sets of m points.
    """
    scores_in: list[float] = []
    scores_out: list[float] = []
    for data in shadow_sets:  # @line L1
        half = len(data) // 2
        inside, outside = data[:half], data[half:]
        g = train_logistic(inside, steps, lr, l2)  # @line L2
        scores_in += [confidence(g, x, y) for x, y in inside]  # @line L3
        scores_out += [confidence(g, x, y) for x, y in outside]
    tau, _ = best_threshold(scores_in, scores_out)  # @line L4
    return tau


def infer(target: Model, tau: float, x: Sequence[float], y: int) -> bool:
    """The attack decision on the record (x, y): member iff the target's confidence is at least tau. Cost O(d)."""
    return confidence(target, x, y) >= tau  # @line L5
mlkit.py 252 lines
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.

Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""

import math
import random
from typing import Callable, Sequence

Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]


def dot(u: Sequence[float], v: Sequence[float]) -> float:
    """Inner product of two vectors of the same length. Cost O(d)."""
    return math.fsum(a * b for a, b in zip(u, v, strict=True))


def add(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise sum u + v. Cost O(d)."""
    return [a + b for a, b in zip(u, v, strict=True)]


def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise difference u - v. Cost O(d)."""
    return [a - b for a, b in zip(u, v, strict=True)]


def scale(c: float, v: Sequence[float]) -> Vector:
    """The vector c v. Cost O(d)."""
    return [c * a for a in v]


def norm1(v: Sequence[float]) -> float:
    """The l1 norm, the sum of |v_i|. Cost O(d)."""
    return math.fsum(abs(a) for a in v)


def norm2(v: Sequence[float]) -> float:
    """The Euclidean norm. Cost O(d)."""
    return math.sqrt(math.fsum(a * a for a in v))


def norminf(v: Sequence[float]) -> float:
    """The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
    return max((abs(a) for a in v), default=0.0)


def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l2 ball of the given center and radius >= 0.

    A point inside the ball is returned unchanged; a point outside is moved along the
    segment to the center until it is on the sphere. Cost O(d).
    """
    diff = sub(v, center)
    r = norm2(diff)
    if r <= radius:
        return list(v)
    return add(center, scale(radius / r, diff))


def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
    return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]


def clip01(v: Sequence[float]) -> Vector:
    """Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
    return [min(max(a, 0.0), 1.0) for a in v]


def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
    """n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).

    Point i gets the label i mod len(centers) and is drawn around that center, so the
    classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
    """
    for c in centers:
        if len(c) != d:
            raise ValueError("each center must have d coordinates")
    data: Data = []
    for i in range(n):
        label = i % len(centers)
        x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
        data.append((x, label))
    return data


def sigmoid(t: float) -> float:
    """The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
    if t >= 0:
        return 1.0 / (1.0 + math.exp(-t))
    e = math.exp(t)
    return e / (1.0 + e)


def _softplus(t: float) -> float:
    """ln(1 + e^t) without overflow."""
    return max(t, 0.0) + math.log1p(math.exp(-abs(t)))


def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
    """Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.

    The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
    """
    s = 2 * y - 1
    return _softplus(-s * (dot(w, x) + b))


def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
    """Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, w)


def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
    """Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, x), g


def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
    """Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.

    Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
    The bias has no penalty. Returns (w, b). Cost O(steps n d).
    """
    d = len(data[0][0])
    n = len(data)
    w = [0.0] * d
    b = 0.0
    for _ in range(steps):
        gw = [0.0] * d
        gb = 0.0
        for x, y in data:
            g = sigmoid(dot(w, x) + b) - y
            for j in range(d):
                gw[j] += g * x[j]
            gb += g
        w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
        b -= lr * gb / n
    return w, b


def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
    """A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.

    The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
    and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
    W2 (k rows of h) and b2 (k). Cost O(h d + k h).
    """
    s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
    return {
        "W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
        "b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
        "W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
        "b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
    }


def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
    """Pre-activations and activations of the hidden layer."""
    pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
    return pre, [max(a, 0.0) for a in pre]


def forward(net: Net, x: Sequence[float]) -> Vector:
    """Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
    _, act = _hidden(net, x)
    return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]


def argmax(z: Sequence[float]) -> int:
    """The first index of a largest entry. Cost O(k)."""
    best = 0
    for i in range(1, len(z)):
        if z[i] > z[best]:
            best = i
    return best


def softmax(z: Sequence[float]) -> Vector:
    """The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = math.fsum(e)
    return [a / s for a in e]


def cross_entropy(z: Sequence[float], label: int) -> float:
    """Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
    m = max(z)
    return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]


def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
    """The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(k h d).
    """
    pre, _ = _hidden(net, x)
    d = len(x)
    rows = []
    for w2 in net["W2"]:
        row = [0.0] * d
        for i, a in enumerate(pre):
            if a > 0 and w2[i] != 0.0:
                c = w2[i]
                w1 = net["W1"][i]
                for j in range(d):
                    row[j] += c * w1[j]
        rows.append(row)
    return rows


def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
    """Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(h d + k h).
    """
    pre, act = _hidden(net, x)
    z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
    p = softmax(z)
    p[label] -= 1.0
    back = [0.0] * len(pre)
    for c, row in zip(p, net["W2"], strict=True):
        for i in range(len(pre)):
            back[i] += c * row[i]
    g = [0.0] * len(x)
    for i, a in enumerate(pre):
        if a > 0:
            w1 = net["W1"][i]
            for j in range(len(x)):
                g[j] += back[i] * w1[j]
    return g


def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
    """Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
    if not data:
        return 0.0
    return sum(1 for x, y in data if predict(x) == y) / len(data)
test_membership_inference_attack.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/membership-inference-attack/. The authors are listed in prov/52KYBB.jsonl.

"""Tests of the shadow model membership attack on logistic models trained on seeded synthetic blobs."""

import math
import random
from fractions import Fraction

from mlkit import make_blobs, train_logistic
from membership_inference_attack import best_threshold, confidence, infer, rates, shadow_attack, tpr_at_fpr


def brute_rates(si, so, tau):
    return sum(s >= tau for s in si) / len(si), sum(s >= tau for s in so) / len(so)


def brute_best(si, so):
    best_tau, best_adv = math.inf, Fraction(0)
    for tau in sorted(set(si) | set(so), reverse=True):
        adv = Fraction(sum(s >= tau for s in si), len(si)) - Fraction(sum(s >= tau for s in so), len(so))
        if adv > best_adv:
            best_tau, best_adv = tau, adv
    return best_tau, float(best_adv)


def test_example_of_the_page() -> None:
    tau, adv = best_threshold([0.9, 0.8, 0.7], [0.75, 0.6, 0.5])
    assert tau == 0.8 and abs(adv - 2 / 3) < 1e-12
    tpr, fpr = rates([0.95, 0.85, 0.6], [0.82, 0.55, 0.4], tau)
    assert (tpr, fpr) == (2 / 3, 1 / 3)
    assert tpr_at_fpr([0.95, 0.85, 0.6], [0.82, 0.55, 0.4], 0.0) == 2 / 3


def test_threshold_matches_brute_force() -> None:
    rng = random.Random(7302)
    for _ in range(500):
        si = [rng.randint(0, 6) / 6 for _ in range(rng.randint(1, 8))]
        so = [rng.randint(0, 6) / 6 for _ in range(rng.randint(1, 8))]
        tau, adv = best_threshold(si, so)
        btau, badv = brute_best(si, so)
        assert abs(adv - badv) < 1e-12 and tau == btau
        if tau != math.inf:
            tpr, fpr = rates(si, so, tau)
            assert abs(tpr - fpr - adv) < 1e-12


def test_tpr_at_low_fpr_matches_brute_force() -> None:
    rng = random.Random(7303)
    for _ in range(500):
        si = [rng.randint(0, 9) / 9 for _ in range(rng.randint(1, 8))]
        so = [rng.randint(0, 9) / 9 for _ in range(rng.randint(1, 8))]
        alpha = rng.choice([0.0, 0.01, 0.1, 0.25, 0.5, 1.0])
        expect = max(
            [t for t, f in (brute_rates(si, so, tau) for tau in set(si) | set(so)) if f <= alpha] + [0.0]
        )
        assert tpr_at_fpr(si, so, alpha) == expect


def run_game(seed: int, l2: float, ignore_data: bool) -> tuple[float, float]:
    """The membership game on 10 target models; returns (advantage of the shadow threshold, TPR at FPR 0.05)."""
    rng = random.Random(seed)
    d, n, steps, lr = 8, 16, 200, 1.0
    centers = [[0.3] * d, [-0.3] * d]
    shadows = [make_blobs(rng, 2 * n, d, centers, 1.5) for _ in range(4)]
    tau = shadow_attack(shadows, steps, lr, l2)
    si, so = [], []
    for _ in range(10):
        members = make_blobs(rng, n, d, centers, 1.5)
        others = make_blobs(rng, n, d, centers, 1.5)
        train_on = make_blobs(rng, n, d, centers, 1.5) if ignore_data else members
        target = train_logistic(train_on, steps, lr, l2)
        si += [confidence(target, x, y) for x, y in members]
        so += [confidence(target, x, y) for x, y in others]
        assert all(infer(target, tau, x, y) == (confidence(target, x, y) >= tau) for x, y in members)
    tpr, fpr = rates(si, so, tau)
    return tpr - fpr, tpr_at_fpr(si, so, 0.05)


def test_overfit_model_leaks_membership() -> None:
    """A measurement: 16 training points in d = 8 with no penalty, so the model fits its members better."""
    adv, low = run_game(7304, 0.0, False)
    assert adv >= 0.15
    assert low < adv  # the threshold attack is weak at a low false positive rate


def test_regularization_and_a_model_that_ignores_its_data() -> None:
    adv_reg, _ = run_game(7304, 1.0, False)
    adv_free, _ = run_game(7304, 0.0, False)
    adv_none, _ = run_game(7304, 0.0, True)
    assert adv_reg < adv_free
    assert abs(adv_none) <= 0.1

History

Homer et al. (2008) showed that the presence of one person in a genomic mixture can be decided from summary statistics, which made membership a privacy question. Shokri, Stronati, Song and Shmatikov (2017) gave the attack on machine learning models with shadow models, and Yeom et al. (2018) defined the membership game, linked the advantage to overfitting and bounded it under differential privacy. Salem et al. (2019) showed that one shadow model, or none, is enough for a threshold attack. Carlini et al. (2022) argued for the TPR at a low FPR and gave the likelihood ratio attack.

References

  1. Reza Shokri, Marco Stronati, Congzheng Song and Vitaly Shmatikov, Membership inference attacks against machine learning models, IEEE Symposium on Security and Privacy (S&P) 2017, pages 3-18, the shadow model technique (shadow models trained like the target on data from a similar distribution) and the attack model, one binary classifier per output class, trained on the outputs of the shadow models on their own training data (in) and on other data (out)
  2. Samuel Yeom, Irene Giacomelli, Matt Fredrikson and Somesh Jha, Privacy risk in machine learning: analyzing the connection to overfitting, IEEE Computer Security Foundations Symposium (CSF) 2018, pages 268-282, arXiv:1709.01604, Experiment 1 (the membership experiment), Definition 4 and equation (2) (the membership advantage, equal to the true positive rate minus the false positive rate), Theorem 1 in Section 3.1 (the advantage against an epsilon-differentially private learner is at most e^epsilon - 1), and Section 3.2 (the advantage of simple attacks in terms of the generalization error)
  3. Nicholas Carlini, Steve Chien, Milad Nasr, Shuang Song, Andreas Terzis and Florian Tramer, Membership inference attacks from first principles, IEEE Symposium on Security and Privacy (S&P) 2022, pages 1897-1914, the argument that average metrics such as accuracy and AUC hide whether an attack identifies any member with confidence, and the advice to report the true positive rate at a low false positive rate
  4. Ahmed Salem, Yang Zhang, Mathias Humbert, Pascal Berrang, Mario Fritz and Michael Backes, ML-Leaks: model and data independent membership inference attacks and defenses on machine learning models, Network and Distributed System Security Symposium (NDSS) 2019, attacks with one shadow model in place of many, and an attack with no shadow model that puts a threshold on the output of the target
  5. Nils Homer et al., Resolving individuals contributing trace amounts of DNA to highly complex mixtures using high-density SNP genotyping microarrays, PLoS Genetics 4(8), 2008, membership of one person in a genomic mixture, decided by a statistical test on summary statistics
  6. Battista Biggio and Fabio Roli, Wild patterns, ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317-331, 2018, the threat model in three parts, goal, knowledge and capability

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example