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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , 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 of records from a distribution and train . Flip a fair coin . If , draw uniformly from ; if , draw from . The attacker gets , , and and outputs a guess of . Its advantage is , which equals
A guess that ignores the model has advantage , and a perfect attack has advantage (up to the small chance that a fresh draw is also in ).
Input. Shadow sets from the same distribution, each of records; the training procedure ; the target model ; a record .
Output. MEMBER or NONMEMBER. The score of a model on a record is , the probability that gives the true label ; the rule says MEMBER when .
The algorithm
MEMBERSHIP-INFERENCE(D_1, ..., D_k, T, f, x, y)- 1
for j = 1 to k do - 2
g_j <- T(the first half of D_j) - 3
put c(g_j, x', y') into IN for each (x', y') of the first half, and into OUT for each of the second half - 4
tau <- the threshold that maximizes TPR - FPR of the rule "score >= tau" on IN and OUT - 5
return 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 , which says MEMBER for nothing. Ties go to the largest .
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 and OUT . The sweep from the top gives:
| TPR | FPR | TPR - FPR | |
|---|---|---|---|
Two cuts tie at , and line L4 keeps the larger, . On the target, the members score and the nonmembers . The rule says MEMBER for , and , so TPR , FPR , and the advantage on the target is , less than on the shadow models. The best TPR with FPR is , at the cut .
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, . It follows from ; the proof file gives it.
Theorem (the threshold, proved on this page). Line L4 returns a that maximizes TPR - FPR over all thresholds , and the largest such 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 , every attack has advantage . This is the case 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 -differentially private, every attacker has .
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 says MEMBER for a score when . For finite lists IN of scores and OUT of scores, write , , and .
Claim 1 (the advantage). In the membership game, with a fair coin , .
Proof. The guess is correct when it says MEMBER and , or NONMEMBER and . So . Multiply by 2 and subtract 1.
Claim 2 (every rule is a candidate). Let be the set of distinct scores of IN and OUT. For every there is a with and the same decision on every score of IN and OUT.
Proof. If no score is , take : both rules say NONMEMBER for all scores. Else let be the smallest score that is . A score is . A score is a score , so by the choice of . So the two rules agree on all scores.
Claim 3 (the sweep). best_threshold returns where over all , and is the largest element of that reaches .
Proof. The code sorts the pairs by score in decreasing order and handles the distinct scores in turn. Invariant: after the inner loop for , tp and fp count the scores of IN and OUT that are . It holds after , because the inner loop adds exactly the pairs of score , and if it holds after it holds after , because the pairs with score in are exactly those of score . So after , tp and fp , and key . This is an integer, so the comparisons are exact. The start values , key , are the values of the cut , for which . The candidates are seen in the order , 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 gives the same TPR and FPR as some candidate, so this key is the maximum over all . Dividing by gives .
Claim 4 (TPR at a fixed FPR). tpr_at_fpr returns over all , for .
Proof. The same sweep and invariant give and after each distinct score, and the code keeps the largest among those with . The start value is the TPR of the cut , whose FPR is . By Claim 2 every has the TPR and FPR of a candidate, so the maximum over the candidates is the maximum over all .
Claim 5 (a model that ignores its data). Suppose the trained model is independent of the training set , and consists of independent draws from . Then every attacker has advantage .
Proof. Let be the challenge. If , is a uniform element of , so has the law , and since is independent of , it is independent of . If , is a fresh draw from , again independent of . So the pair has the same law in both cases, and so does the guess of any attacker, which is a function of and of its own coins. Then , and by Claim 1 the advantage is .
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 on 160 members and 160 nonmembers is sampling noise around the value .
Complexity
- Shadow models. trainings of steps of full batch gradient descent on points in dimension : .
- Scores and threshold. scores at each, then one sort: .
- One decision. for one query of the target.
- Space. scores and 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 on the shadows to 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 , the rule is the rule "loss ", 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 , but at FPR percent its TPR is , 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 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 and the TPR at FPR percent is ; with the penalty the advantage is ; and for models trained on other data, which ignore their members, it is , sampling noise around the value 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.
# 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
- 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)
- 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)
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 52KYBB Edit this page History Report an error Markdown