Algorithm Search⌘K

Algorithmresearch

Likelihood ratio membership attack

Also called LiRA.

Fits Gaussians to a record's logit-scaled confidence under models trained with and without it, and tests membership by their likelihood ratio.

Time
O(k s m d + k m d) worst
Space
O(k m + k d) extra
Where
d = the dimension; k = the number of shadow models; m = the number of records in the pool; s = the number of training steps per model
Properties
randomizednot exactofflineiterative
Origin
Nicholas Carlini, Steve Chien, Milad Nasr, Shuang Song, Andreas Terzis, Florian Tramer, 2022

The likelihood ratio attack (LiRA) of Carlini et al. (2022) decides whether one record (x,y)(x, y) was in the training set of a model by a statistical test made for that record. The attacker trains many shadow models, about half of them on data that includes the record and half on data that does not. It fits one Gaussian to the logit-scaled confidence ϕ\phi of the first group on the record and one to that of the second group, and computes the ratio of the two densities at the value of the target model. A membership inference attack with one threshold for all records treats easy and hard records alike; LiRA calibrates each record, which is what lets it find members at a low false positive rate. Its strength is a measurement; the Neyman-Pearson lemma explains why a likelihood ratio is the right statistic.

In plain words

Some records are easy: every model is sure about them, whether it trained on them or not. Others are odd ones that a model gets right only when it has seen them. One global cut on "how sure is the model" mixes these up.

So, for the one record you ask about, train many copies of the model. Half of the copies see the record and half do not. Look at how sure each group is about the record; each group gives a bell curve.

Now look at how sure the real model is. If that value fits the bell curve of the copies that saw the record much better than the other curve, say "member". The ratio of the two curves at that value is the score.

The problem

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

  • Goal of the attacker. Decide whether one chosen record was in the training set, with few false alarms.
  • Knowledge. Black box access to the output probabilities of the target, the training procedure, and a pool of data from the same distribution that contains the record.
  • Capability. Query the target on chosen records and train many models of its own. The attacker does not change the target or its training data.

The attack is judged in the membership game of Yeom et al. (see membership-inference-attack), by the advantage TPR−FPR\text{TPR} - \text{FPR} and, above all, by the TPR at a low FPR.

Input. A pool DD of mm records that contains the record (x,y)(x, y); the training procedure TT; an even number kk of shadow models; the target ff; a cut tt.

Output. MEMBER or NONMEMBER. With cc the probability that a model gives the true label yy, the score is the logit-scaled confidence

ϕ=ln⁡c1−c.\phi = \ln \frac{c}{1 - c}.

For a logistic model with z=⟨w,x⟩+bz = \langle w, x \rangle + b and s=2y−1s = 2y - 1, c=σ(sz)c = \sigma(s z), so ϕ=sz\phi = s z exactly.

The algorithm

  1. LIRA(D, T, k, f, x, y, t)
  2. 1for j = 1 to k/2 do: pick a random half H of D; train one shadow model on H and one on D minus H
  3. 2for each shadow g: phi_g <- phi(g, x, y); put it into IN if g trained on (x, y), else into OUT
  4. 3fit N(mu_in, v_in) to IN and N(mu_out, v_out) to OUT
  5. 4phi* <- phi(f, x, y)
  6. 5Lambda <- ln N(phi*; mu_in, v_in) - ln N(phi*; mu_out, v_out)
  7. 6return MEMBER if Lambda >= t, else NONMEMBER

Line L1 trains the models in pairs on complementary halves, so every record of the pool is IN for exactly k/2k/2 models. The same shadow models serve every record of the pool, so the cost of training is shared. With few shadow models the variances are noisy; Carlini et al. then use one IN variance and one OUT variance for all records, and the code does the same when asked (the branch at line L3; the means are fitted per record in line L5).

The offline attack. When the attacker cannot train models on the record (for example, the record arrives after the shadows are trained), it uses OUT models only and the one-sided test Pr⁡[Z≤ϕ∗]\Pr[Z \le \phi^*] for Z∼N(μout,vout)Z \sim N(\mu_{\text{out}}, v_{\text{out}}): a value of ϕ∗\phi^* far above what models without the record give means MEMBER.

Example

Two records, each with three IN and three OUT shadow values, so all four variances are 2/32/3.

  • Record A: IN ={2,3,4}= \{2, 3, 4\}, OUT ={0,1,2}= \{0, 1, 2\}, so μin=3\mu_{\text{in}} = 3, μout=1\mu_{\text{out}} = 1. The target gives ϕ∗=2.5\phi^* = 2.5. With equal variances, Λ=((ϕ∗−μout)2−(ϕ∗−μin)2)/(2v)=(2.25−0.25)/(4/3)=1.5\Lambda = \big((\phi^* - \mu_{\text{out}})^2 - (\phi^* - \mu_{\text{in}})^2\big) / (2v) = (2.25 - 0.25) / (4/3) = 1.5, so with t=0t = 0 the answer is MEMBER.
  • Record B: IN ={5,6,7}= \{5, 6, 7\}, OUT ={3,4,5}= \{3, 4, 5\}. The target gives ϕ∗=4.5\phi^* = 4.5, so (ϕ∗−μout)2=0.25(\phi^* - \mu_{\text{out}})^2 = 0.25, (ϕ∗−μin)2=2.25(\phi^* - \mu_{\text{in}})^2 = 2.25, and Λ=(0.25−2.25)/(4/3)=−1.5\Lambda = (0.25 - 2.25) / (4/3) = -1.5: the answer is NONMEMBER.

The target is more sure of B (4.54.5) than of A (2.52.5), so any one global cut on ϕ\phi that calls A a member also calls B a member. LiRA sees that B is an easy record, for which 4.54.5 is a normal value even without training. The offline score of A is Pr⁡[Z≤2.5]≈0.967\Pr[Z \le 2.5] \approx 0.967 for Z∼N(1,2/3)Z \sim N(1, 2/3).

Correctness

The attack decides by a test and can be wrong; its error rates are measurements. The following hold.

Theorem (the most powerful test, Neyman-Pearson). If the distributions of ϕ∗\phi^* for members and nonmembers of one record were known, the test that says MEMBER when their density ratio is at least a cut has the largest TPR among all tests with the same FPR. See the Neyman-Pearson lemma and the likelihood ratio test.

Heuristic (the Gaussian fit). LiRA replaces the true distributions by Gaussians fitted to shadow models. Carlini et al. report that after the logit scaling the values of one record over many models are close to Gaussian, which they are not before it, since cc is crowded near 11. Both the fit and the stand-in of shadow models for the target are assumptions, not theorems.

Theorem (a per-record cut, proved on this page). With equal variances vv and μin>μout\mu_{\text{in}} > \mu_{\text{out}}, Λ=μin−μoutv(ϕ∗−μin+μout2)\Lambda = \frac{\mu_{\text{in}} - \mu_{\text{out}}}{v}\big(\phi^* - \frac{\mu_{\text{in}} + \mu_{\text{out}}}{2}\big), so LiRA is a threshold on ϕ∗\phi^* whose cut depends on the record. A global threshold is the special case where all records share their means.

Theorem (the balanced shadows and the logit, proved on this page). Line L1 makes every record IN for exactly k/2k/2 models, and for a logistic model ϕ=sz\phi = s z.

Theorem (no attack beats privacy, Yeom et al., Theorem 1). Against an ϵ\epsilon-differentially private training procedure every attacker, LiRA included, has advantage at most eϵ−1e^\epsilon - 1; and against a model that does not depend on its data, the expected advantage of LiRA at a fixed cut is 00 in the game of the tests (proved on this page).

Proof: The logit of a logistic model, the balanced shadow design, the per-record cut of the Gaussian likelihood ratio, and the zero advantage against a model that ignores its datafull

Setting. A shadow or target model gg gives a record (x,y)(x, y), y∈{0,1}y \in \{0, 1\}, the confidence c=Pr⁡g[y∣x]c = \Pr_g[y \mid x] and the score ϕ=ln⁡(c/(1−c))\phi = \ln(c / (1 - c)). The Gaussian log density is ℓ(u;μ,v)=−12ln⁡(2πv)−(u−μ)2/(2v)\ell(u; \mu, v) = -\tfrac{1}{2}\ln(2\pi v) - (u - \mu)^2/(2v) for v>0v > 0, and the online score is Λ=ℓ(ϕ∗;μin,vin)−ℓ(ϕ∗;μout,vout)\Lambda = \ell(\phi^*; \mu_{\text{in}}, v_{\text{in}}) - \ell(\phi^*; \mu_{\text{out}}, v_{\text{out}}), with the means of the IN and OUT values and the given or fitted variances, raised to the floor.

Claim 1 (the logit of a logistic model). For g=(w,b)g = (w, b), z=⟨w,x⟩+bz = \langle w, x \rangle + b and s=2y−1s = 2y - 1, ϕ=sz\phi = s z.

Proof. The model gives the label 11 with probability σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), and 1−σ(z)=σ(−z)1 - \sigma(z) = \sigma(-z), so c=σ(sz)c = \sigma(s z) for both labels. For any uu, σ(u)/(1−σ(u))=σ(u)/σ(−u)=eu\sigma(u)/(1 - \sigma(u)) = \sigma(u)/\sigma(-u) = e^{u}, because σ(u)=euσ(−u)\sigma(u) = e^u \sigma(-u). So ϕ=ln⁡esz=sz\phi = \ln e^{s z} = s z. □\square

Claim 2 (balanced shadows). train_shadows with pp pairs on a pool of even size mm returns 2p2p models, each trained on exactly m/2m/2 records, and every record is IN for exactly pp models.

Proof. In each pair the code draws a set HH of m/2m/2 distinct indices and builds the masks [i∈H][i \in H] and [i∉H][i \notin H]. Each mask has m/2m/2 true entries, and for each ii exactly one of the two masks is true. Each model is train_logistic on the records of its mask. Summing over the pp pairs, record ii is IN for pp models. □\square

So in the game of the tests, where a target uses the 2p−22p - 2 models of the other pairs as shadows, every record has exactly p−1p - 1 IN and p−1p - 1 OUT values; with p=16p = 16 both lists are nonempty, which is the precondition of lira_scores.

Claim 3 (the score is the log likelihood ratio). online_score returns ln⁡(N(ϕ∗;μin,vin)/N(ϕ∗;μout,vout))\ln\big(N(\phi^*; \mu_{\text{in}}, v_{\text{in}}) / N(\phi^*; \mu_{\text{out}}, v_{\text{out}})\big), where N(⋅;μ,v)N(\cdot; \mu, v) is the normal density.

Proof. gaussian_fit returns the mean and the population variance; the variance used is the given one if any, else the fitted one, and then at least the floor, so it is positive. log_normal returns ℓ(u;μ,v)=ln⁡N(u;μ,v)\ell(u; \mu, v) = \ln N(u; \mu, v), and the score is the difference of two such logarithms, which is the logarithm of the ratio. □\square

Claim 4 (a per-record cut). If vin=vout=vv_{\text{in}} = v_{\text{out}} = v, then

Λ=μin−μoutv(ϕ∗−μin+μout2).\Lambda = \frac{\mu_{\text{in}} - \mu_{\text{out}}}{v}\Big(\phi^* - \frac{\mu_{\text{in}} + \mu_{\text{out}}}{2}\Big).

So when μin>μout\mu_{\text{in}} > \mu_{\text{out}}, the rule Λ≥t\Lambda \ge t is the rule ϕ∗≥μin+μout2+tvμin−μout\phi^* \ge \frac{\mu_{\text{in}} + \mu_{\text{out}}}{2} + \frac{t v}{\mu_{\text{in}} - \mu_{\text{out}}}, a threshold on ϕ∗\phi^* whose cut depends on the record through its means.

Proof. The terms −12ln⁡(2πv)-\tfrac{1}{2}\ln(2\pi v) cancel, so Λ=((ϕ∗−μout)2−(ϕ∗−μin)2)/(2v)\Lambda = \big((\phi^* - \mu_{\text{out}})^2 - (\phi^* - \mu_{\text{in}})^2\big)/(2v). The difference of squares is (μin−μout)(2ϕ∗−μin−μout)(\mu_{\text{in}} - \mu_{\text{out}})(2\phi^* - \mu_{\text{in}} - \mu_{\text{out}}). Divide by 2v2v. For the rule, divide Λ≥t\Lambda \ge t by the positive number (μin−μout)/v(\mu_{\text{in}} - \mu_{\text{out}})/v. □\square

In the example, record A has means 33 and 11 and v=2/3v = 2/3, so Λ=3(2.5−2)=1.5\Lambda = 3(2.5 - 2) = 1.5; record B has means 66 and 44, so Λ=3(4.5−5)=−1.5\Lambda = 3(4.5 - 5) = -1.5.

Claim 5 (a model that ignores its data). Consider the game of the tests: pp pairs with independent uniform halves H1,…,HpH_1, \ldots, H_p, and each model jj, in pair q(j)q(j), is the target once, with the models of the other p−1p - 1 pairs as shadows. Suppose every model is trained on data drawn independently of the halves (the control of the tests, which trains each model on fresh draws), and treat the seeded generator as a source of independent draws. Then for each fixed cut tt, the expected TPR of the rule Λ≥t\Lambda \ge t over all targets equals its expected FPR.

Proof. Let βij∈{0,1}\beta_{ij} \in \{0, 1\} be the mask of target jj on record ii; it is a function of Hq(j)H_{q(j)} alone, and Pr⁡[βij=1]=1/2\Pr[\beta_{ij} = 1] = 1/2 because Hq(j)H_{q(j)} is a uniform half. The score Λij\Lambda_{ij} is computed by lira_scores from the values ϕ\phi of the target and of the shadows, which are functions of the models, and from the masks of the shadows, which are functions of the halves Hq′H_{q'} with q′≠q(j)q' \ne q(j). The models and these halves are independent of Hq(j)H_{q(j)}, so Λij\Lambda_{ij} is independent of βij\beta_{ij}, and E[1[Λij≥t] βij]=12Pr⁡[Λij≥t]=E[1[Λij≥t] (1−βij)]\mathbb{E}\big[\mathbf{1}[\Lambda_{ij} \ge t]\, \beta_{ij}\big] = \tfrac{1}{2}\Pr[\Lambda_{ij} \ge t] = \mathbb{E}\big[\mathbf{1}[\Lambda_{ij} \ge t]\,(1 - \beta_{ij})\big]. By Claim 2 each target has exactly m/2m/2 members and m/2m/2 nonmembers, so with 2p2p targets both totals are pmp m, and

E[TPR]=1pm∑i,jE[1[Λij≥t] βij]=1pm∑i,jE[1[Λij≥t] (1−βij)]=E[FPR].□\mathbb{E}[\text{TPR}] = \frac{1}{p m}\sum_{i, j} \mathbb{E}\big[\mathbf{1}[\Lambda_{ij} \ge t]\, \beta_{ij}\big] = \frac{1}{p m}\sum_{i, j} \mathbb{E}\big[\mathbf{1}[\Lambda_{ij} \ge t]\,(1 - \beta_{ij})\big] = \mathbb{E}[\text{FPR}]. \qquad \square

The partner of the target is left out of the shadows on purpose: its mask is the complement of the target's, so with it the split of the shadow values would depend on βij\beta_{ij}, and the IN and OUT lists would have different lengths for members and nonmembers.

The algorithm. Line L1 is train_shadows (Claim 2); lines L2 to L5 are lira_scores, which computes ϕ\phi by Claim 1 and the score by Claim 3, with one variance for all records when asked; line L6 compares the score with the cut. The Neyman-Pearson lemma makes the exact likelihood ratio the most powerful test; the Gaussian fit is an approximation, so the power of the attack on the target is not claimed and is measured in the tests. In the control of Claim 5 with t=0t = 0, the measured TPR minus FPR, 0.06250.0625 over 512 members and 512 nonmembers that share records and models, is sampling noise around 00. ■\blacksquare

Complexity

  • Shadow models. kk trainings of ss steps of full batch gradient descent on m/2m/2 records in dimension dd: O(ksmd)O(k s m d). This dominates.
  • Scores. ϕ\phi of every shadow on every pool record, O(kmd)O(k m d), then O(k)O(k) per record for the fits and O(d)O(d) for the target.
  • Space. O(kd)O(k d) for the models and O(km)O(k m) for the values of ϕ\phi.
  • The cost in practice. Training many models is the price of the attack; Carlini et al. use far more models than a threshold attack needs. The offline attack trains the models once for all future records.

Properties

  • Per record. Each record gets its own null distribution, so easy records do not cause false alarms and odd records are found.
  • Strong at a low FPR. The gain over a global threshold shows most at a low FPR; the average advantage of the two attacks can be close (in the tests, 0.310.31 against 0.320.32).
  • Randomized. The random halves of line L1 make the scores random; the code takes the halves from a seeded generator.
  • A lower bound on risk. A strong attack shows that a model leaks; a failed attack does not show that it does not.

Variants and improvements

  • Offline LiRA. OUT models only, as above. It is weaker but needs no training per record.
  • Fixed variance. One IN and one OUT variance for all records, for when there are few shadow models.
  • Calibrated thresholds. Sablayrolles et al. (2019) calibrate a loss threshold per record, and Watson et al. (2022) subtract the score of the record under reference models; both are simpler forms of the same idea.
  • Defenses. DP-SGD bounds the advantage of every attack by the theorem above, and the TPR at a low FPR of LiRA is a common way to audit such training in practice. Removal of records after training is machine unlearning.

When to use it

Use it to measure the privacy risk of a model that you own or that you train on synthetic data, when you care whether any single record can be identified with confidence, which is the question that a privacy audit asks. Report the TPR at a low FPR, such as 1 percent or less. If training many models is too costly, use the offline variant or the threshold attack of membership-inference-attack, and say that the result is weaker. For a guarantee, train with differential privacy.

Pitfalls

  • Few shadow models. With a handful of IN and OUT values per record the fitted variances are noise, and a tiny variance gives a huge ratio. Use one variance for all records, or a floor on the variance (the code has both).
  • Raw confidence. Without the logit scaling, cc is near 11 for most records and the Gaussian fit is poor.
  • Selection of the cut on the test data. The best advantage over all cuts, read off the same scores, is biased upward: in the control of the tests, where the true advantage is 00, it is 0.090.09. The control test uses the fixed cut t=0t = 0.
  • The partner model. In a game with complementary halves, a target must not use its partner as a shadow: the partner's mask is the complement of the target's, so the IN and OUT lists would then depend on the answer.
  • Shadows unlike the target. Different training data, model size or training steps make the null distributions wrong.
  • The pool must hold the record. The online attack trains IN models on the record; without them only the offline test is possible.

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 scores against the normal distribution of the Python standard library on 500 random parameter sets, check ϕ\phi against the log odds on 500 random models, check the balanced halves and the example. They then measure the game with seed 7401: a pool of 32 records and 32 models in 16 pairs, each trained on 16 records and used once as the target, with the 30 models of the other pairs as shadows, so that every record has 15 IN and 15 OUT values. At FPR 1 percent LiRA with one variance finds 6.25 percent of the members, and one global threshold on ϕ\phi finds 0.59 percent; the best advantages are 0.310.31 and 0.320.32. When every model is trained on other data and so ignores the pool, the advantage at the cut 00 is 0.06250.0625 and the TPR at FPR 1 percent is 1.4 percent, 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.

likelihood_ratio_membership_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-membership-attack/. The authors are listed in prov/CGYJMS.jsonl.

"""The likelihood ratio membership attack (LiRA) of Carlini et al. (2022), 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. For each record the attack fits one
Gaussian to the logit-scaled confidence of the shadow models that trained on the
record and one to those that did not, and tests membership by the ratio of the two
densities at the target's value. Nothing here queries a real model or reads a real
data set. Labels are 0 and 1.
"""

import math
import random
from typing import Optional, Sequence

from mlkit import Data, dot, train_logistic

Model = tuple[list[float], float]


def logit_confidence(model: Model, x: Sequence[float], y: int) -> float:
    """phi = ln(c / (1 - c)) for the confidence c of the true label y of x.

    For a logistic model c = sigmoid(s z) with z = w.x + b and s = 2 y - 1, so phi = s z
    exactly, with no rounding of c near 0 or 1. Cost O(d).
    """
    w, b = model
    return (2 * y - 1) * (dot(w, x) + b)


def gaussian_fit(values: Sequence[float]) -> tuple[float, float]:
    """(mean, population variance) of the values. Precondition: at least one value. Cost O(r) for r values."""
    mu = math.fsum(values) / len(values)
    return mu, math.fsum((v - mu) ** 2 for v in values) / len(values)


def log_normal(t: float, mu: float, var: float) -> float:
    """ln of the density of N(mu, var) at t. Precondition: var > 0. Cost O(1)."""
    return -0.5 * math.log(2.0 * math.pi * var) - (t - mu) ** 2 / (2.0 * var)


def online_score(
    phi: float,
    in_vals: Sequence[float],
    out_vals: Sequence[float],
    var_in: Optional[float] = None,
    var_out: Optional[float] = None,
    floor: float = 1e-6,
) -> float:
    """Lambda = ln N(phi; mu_in, var_in) - ln N(phi; mu_out, var_out), the log likelihood ratio of membership.

    The means come from in_vals and out_vals. A variance that is not given is fitted
    from the same values; every variance is raised to at least floor. Precondition: both
    lists are nonempty and floor > 0. Cost O(r) for r values.
    """
    mu_in, v_in = gaussian_fit(in_vals)
    mu_out, v_out = gaussian_fit(out_vals)
    v_in = max(v_in if var_in is None else var_in, floor)
    v_out = max(v_out if var_out is None else var_out, floor)
    return log_normal(phi, mu_in, v_in) - log_normal(phi, mu_out, v_out)


def offline_score(phi: float, out_vals: Sequence[float], var_out: Optional[float] = None, floor: float = 1e-6) -> float:
    """Pr[Z <= phi] for Z ~ N(mu_out, var_out): the one-sided test of the offline attack, with no IN models.

    Precondition: out_vals is nonempty and floor > 0. Cost O(r) for r values.
    """
    mu, v = gaussian_fit(out_vals)
    v = max(v if var_out is None else var_out, floor)
    return 0.5 * (1.0 + math.erf((phi - mu) / math.sqrt(2.0 * v)))


def train_shadows(pool: Data, pairs: int, rng: random.Random, steps: int, lr: float, l2: float) -> tuple[list[Model], list[list[bool]]]:
    """Train 2 pairs shadow models; in each pair one model trains on a random half of the pool and the other on the rest.

    Returns the models and, for each model, the mask of the pool records it trained on.
    So every record is IN for exactly half of the models. Precondition: the pool has an
    even number m >= 2 of records. Cost O(pairs steps m d).
    """
    m = len(pool)
    models: list[Model] = []
    masks: list[list[bool]] = []
    for _ in range(pairs):  # @line L1
        half = set(rng.sample(range(m), m // 2))
        for side in (True, False):
            mask = [(i in half) == side for i in range(m)]
            models.append(train_logistic([pool[i] for i in range(m) if mask[i]], steps, lr, l2))
            masks.append(mask)
    return models, masks


def lira_scores(
    target: Model,
    shadows: Sequence[Model],
    masks: Sequence[Sequence[bool]],
    pool: Data,
    global_variance: bool,
    floor: float = 1e-6,
) -> list[float]:
    """The online score Lambda of the target on every pool record, with the given shadow models.

    With global_variance, one IN variance and one OUT variance are the means of the
    per-record variances over all records, as in the fixed variance variant of Carlini
    et al.; else each record has its own. Precondition: every record is IN for at least
    one shadow and OUT for at least one. Cost O(k m d) for k shadows and m records.
    """
    ins: list[list[float]] = []
    outs: list[list[float]] = []
    for i, (x, y) in enumerate(pool):
        phis = [logit_confidence(g, x, y) for g in shadows]  # @line L2
        ins.append([p for p, mk in zip(phis, masks) if mk[i]])
        outs.append([p for p, mk in zip(phis, masks) if not mk[i]])
    v_in: Optional[float] = None
    v_out: Optional[float] = None
    if global_variance:  # @line L3
        v_in = math.fsum(gaussian_fit(v)[1] for v in ins) / len(ins)
        v_out = math.fsum(gaussian_fit(v)[1] for v in outs) / len(outs)
    scores = []
    for i, (x, y) in enumerate(pool):
        phi = logit_confidence(target, x, y)  # @line L4
        scores.append(online_score(phi, ins[i], outs[i], v_in, v_out, floor))  # @line L5
    return scores


def decide(score: float, t: float) -> bool:
    """Member iff the log likelihood ratio is at least the cut t. Cost O(1)."""
    return score >= t  # @line L6


def tpr_at_fpr(scores_in: Sequence[float], scores_out: Sequence[float], alpha: float) -> float:
    """The largest TPR of a rule "member iff score >= t" whose FPR is at most alpha. Cost O(r log r) for r scores."""
    pts = sorted([(s, 1) for s in scores_in] + [(s, 0) for s in scores_out], reverse=True)
    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 / len(scores_out) <= alpha:
            best = max(best, tp / len(scores_in))
    return best


def best_advantage(scores_in: Sequence[float], scores_out: Sequence[float]) -> float:
    """max over cuts t of TPR - FPR for "member iff score >= t", and 0 for the cut above every score. Cost O(r log r)."""
    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
    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
        best = max(best, tp * n_out - fp * n_in)
    return best / (n_in * n_out)
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_likelihood_ratio_membership_attack.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-membership-attack/. The authors are listed in prov/CGYJMS.jsonl.

"""Tests of the likelihood ratio membership attack on logistic models trained on seeded synthetic blobs."""

import math
import random
import statistics

from mlkit import make_blobs, sigmoid, train_logistic
from likelihood_ratio_membership_attack import (
    best_advantage,
    decide,
    lira_scores,
    logit_confidence,
    offline_score,
    online_score,
    tpr_at_fpr,
    train_shadows,
)


def test_example_of_the_page() -> None:
    assert abs(online_score(2.5, [2.0, 3.0, 4.0], [0.0, 1.0, 2.0]) - 1.5) < 1e-12
    assert abs(online_score(4.5, [5.0, 6.0, 7.0], [3.0, 4.0, 5.0]) + 1.5) < 1e-12
    assert abs(offline_score(2.5, [0.0, 1.0, 2.0]) - 0.9669037101389033) < 1e-12
    assert decide(1.5, 0.0) and not decide(-1.5, 0.0)


def test_logit_confidence_is_the_log_odds() -> None:
    rng = random.Random(7405)
    for _ in range(500):
        d = rng.randint(1, 8)
        w = [rng.uniform(-2, 2) for _ in range(d)]
        b = rng.uniform(-1, 1)
        x = [rng.uniform(-2, 2) for _ in range(d)]
        y = rng.randint(0, 1)
        p = sigmoid(sum(a * c for a, c in zip(w, x)) + b)
        c = p if y == 1 else 1 - p
        assert abs(logit_confidence((w, b), x, y) - math.log(c / (1 - c))) < 1e-9


def test_scores_match_an_independent_normal_oracle() -> None:
    rng = random.Random(7406)
    checked = 0
    while checked < 500:
        ins = [rng.gauss(rng.uniform(-3, 3), rng.uniform(0.5, 2)) for _ in range(rng.randint(2, 9))]
        outs = [rng.gauss(rng.uniform(-3, 3), rng.uniform(0.5, 2)) for _ in range(rng.randint(2, 9))]
        if statistics.pvariance(ins) < 0.25 or statistics.pvariance(outs) < 0.25:
            continue  # so that no density underflows to 0 for |phi| <= 5
        checked += 1
        phi = rng.uniform(-5, 5)
        n_in = statistics.NormalDist(statistics.fmean(ins), math.sqrt(statistics.pvariance(ins)))
        n_out = statistics.NormalDist(statistics.fmean(outs), math.sqrt(statistics.pvariance(outs)))
        expect = math.log(n_in.pdf(phi)) - math.log(n_out.pdf(phi))
        assert abs(online_score(phi, ins, outs) - expect) < 1e-8 * max(1.0, abs(expect))
        assert abs(offline_score(phi, outs) - n_out.cdf(phi)) < 1e-9
        v = rng.uniform(0.1, 3)
        fixed = math.log(statistics.NormalDist(n_in.mean, math.sqrt(v)).pdf(phi)) - math.log(
            statistics.NormalDist(n_out.mean, math.sqrt(v)).pdf(phi)
        )
        assert abs(online_score(phi, ins, outs, v, v) - fixed) < 1e-8 * max(1.0, abs(fixed))


def test_shadow_models_are_balanced_and_trained_on_their_masks() -> None:
    rng = random.Random(7407)
    centers = [[0.3] * 3, [-0.3] * 3]
    pool = make_blobs(rng, 12, 3, centers, 1.5)
    models, masks = train_shadows(pool, 3, rng, 20, 1.0, 0.0)
    assert len(models) == 6
    for i in range(12):
        assert sum(mk[i] for mk in masks) == 3
    for g, mk in zip(models, masks):
        assert sum(mk) == 6
        assert g == train_logistic([pool[i] for i in range(12) if mk[i]], 20, 1.0, 0.0)


def run_game(seed: int, ignore_data: bool) -> tuple[list[float], list[float], list[float], list[float]]:
    """32 models in 16 pairs; each is the target once, with the 30 models of the other pairs as shadows.

    Returns the LiRA and the raw phi scores of members and nonmembers. Leaving out the
    partner of the target gives every record 15 IN and 15 OUT values.
    """
    rng = random.Random(seed)
    d, m = 8, 32
    centers = [[0.3] * d, [-0.3] * d]
    pool = make_blobs(rng, m, d, centers, 1.5)
    models, masks = train_shadows(pool, 16, rng, 200, 1.0, 0.0)
    if ignore_data:
        models = [train_logistic(make_blobs(rng, m // 2, d, centers, 1.5), 200, 1.0, 0.0) for _ in models]
    lin, lout, pin, pout = [], [], [], []
    for j, target in enumerate(models):
        others = [q for q in range(len(models)) if q // 2 != j // 2]
        s = lira_scores(target, [models[q] for q in others], [masks[q] for q in others], pool, True)
        for i, (x, y) in enumerate(pool):
            phi = logit_confidence(target, x, y)
            if masks[j][i]:
                lin.append(s[i])
                pin.append(phi)
            else:
                lout.append(s[i])
                pout.append(phi)
    return lin, lout, pin, pout


def test_lira_beats_a_global_threshold_at_low_fpr() -> None:
    """A measurement: the per-record ratio finds members at FPR 1 percent where one threshold on phi does not."""
    lin, lout, pin, pout = run_game(7401, False)
    lira_low, base_low = tpr_at_fpr(lin, lout, 0.01), tpr_at_fpr(pin, pout, 0.01)
    assert lira_low >= 0.04 and lira_low >= 4 * base_low
    assert best_advantage(lin, lout) >= 0.2 and best_advantage(pin, pout) >= 0.2


def test_a_model_that_ignores_its_data_gives_about_zero_advantage() -> None:
    lin, lout, _, _ = run_game(7401, True)
    tpr = sum(decide(s, 0.0) for s in lin) / len(lin)
    fpr = sum(decide(s, 0.0) for s in lout) / len(lout)
    assert abs(tpr - fpr) <= 0.1
    assert tpr_at_fpr(lin, lout, 0.01) <= 0.03

History

Shokri et al. (2017) introduced shadow models, and Yeom et al. (2018) defined the membership game. Sablayrolles et al. (2019) framed membership as a Bayes decision with a per-record calibration, and Watson et al. (2022) showed the value of calibration by the difficulty of a record. Carlini et al. (2022) gave the likelihood ratio attack with Gaussians on the logit-scaled confidence and argued that attacks must be judged by their TPR at a low FPR, which is now the common way to report them.

References

  1. 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 online attack (Gaussians fitted to the logit-scaled confidence of shadow models trained with and without the record, and their likelihood ratio), the offline attack (models without the record only, and a one-sided test), the variant with one variance for all records, and the evaluation by the true positive rate at a low false positive rate
  2. 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, shadow models trained like the target, whose membership the attacker knows
  3. 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 and Definition 4 (the membership game and its advantage), and Theorem 1 in Section 3.1 (the advantage against an epsilon-differentially private learner is at most e^epsilon - 1)
  4. Alexandre Sablayrolles, Matthijs Douze, Cordelia Schmid, Yann Ollivier and Herve Jegou, White-box vs black-box: Bayes optimal strategies for membership inference, Proceedings of the 36th International Conference on Machine Learning (ICML) 2019, membership inference as a Bayes decision on the loss, with a threshold calibrated per record
  5. Lauren Watson, Chuan Guo, Graham Cormode and Alexandre Sablayrolles, On the importance of difficulty calibration in membership inference attacks, International Conference on Learning Representations (ICLR) 2022, the score of a record minus its score under reference models that did not train on it
  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

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