Algorithmadvanced
Model inversion attack
Also called model inversion.
Recovers a sensitive input feature, or an input typical of one class, from a trained model and its confidence scores; MI-FACE does gradient descent on one minus the confidence.
- Time
- O(a (k d + q)) worst
- Space
- O(a + d) extra
- Where
- a = the largest number of steps (alpha); d = the dimension; k = the number of classes; q = the window of the stopping rule (beta)
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matt Fredrikson, Eric Lantz, Somesh Jha, Simon Lin, David Page, Thomas Ristenpart, 2014
A model inversion attack uses a trained model to learn something about the data it was trained on: a sensitive feature of a person whose other features are known, or an input that the model links strongly to one class. Fredrikson et al. (2014) introduced it on a model that predicts the dose of the drug warfarin and showed that the model, with some demographic data of a patient, gives a good estimate of the patient's genetic marker. Fredrikson, Jha and Ristenpart (2015) showed that the confidence scores that many prediction services return make the attack much stronger. Their algorithm MI-FACE searches by gradient descent for the input with the highest confidence for a class; on a face recognition model whose classes are people, the result can look like the person. This page describes MI-FACE. The theorems on this page are about the optimization on small models; whether the result reveals a person is a measurement.
In plain words
A model that names the person in a photo has learned, for each name, what that person's face looks like. If the model also says how sure it is, you can use that number as a guide.
Start from a blank image. Change it a little in the direction that makes the model more sure that the image shows a given name. Repeat until the model stops getting more sure. What is left is the picture that the model connects most strongly with that name, and it can look like the real person.
The same idea works for a table of records: if you know all of a person's answers but one, try each value of the missing answer and keep the one that best fits what the model says.
The problem
The threat model, in the three parts of Biggio and Roli:
- Goal of the attacker. Learn private information about the training data. Two forms: a typical input of one class (a face, when each class is one person), or the value of one sensitive feature of a known person. This is a privacy goal.
- Knowledge. White box (the weights, so the attacker can compute the gradient) or black box with confidence scores. Fredrikson et al. also give the attacker auxiliary information, for example the marginal distribution of each feature. The attacker does not have the training data.
- Capability. Query the model on inputs of its choice, adaptively, at test time. The attacker does not change the model or its training data.
Input. A model that maps to class confidences that sum to ; a class ; a step size ; a step limit ; a window ; a cost target .
Output. A point with a low cost , that is, an input on which the model is very sure of class , and its cost.
The algorithm
MI-FACE(c, alpha, beta, gamma, lambda)- 1
x_0 <- 0 - 2
for i = 1 to alpha do - 3
x_i <- PROCESS(x_{i-1} - lambda grad c(x_{i-1})) - 4
if c(x_i) >= max(c(x_{i-1}), ..., c(x_{i-beta})) then break - 5
if c(x_i) <= gamma then break - 6
return the x_i of least cost c(x_i), and that cost
The cost is . Line L4 stops when the cost has not gone below the largest of the last costs, and line L5 stops when the cost is low enough. In Algorithm 1 of Fredrikson et al. the cost can have an extra term with auxiliary information, and PROCESS is an image filter (identity for two of their models; denoise and sharpen for the third). On this page PROCESS is the projection onto the box , that is, a clip of each coordinate, and there is no extra term. When fewer than costs exist, line L4 uses all of them, including .
The gradient of the cost comes from the model:
- binary logistic model : with and ;
- softmax regression : ;
- any network: , since for the cross-entropy loss CE;
- black box: queries per step for a central difference, as in Section 5.3 of Fredrikson et al.
Example
A binary logistic model with and , class , , , .
| 0 | |||
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
At the gradient is , so the step gives , and the clip gives . The second coordinate stays at because pushes it down. At step 3 the first coordinate passes and is clipped. At step 4 nothing moves, the cost does not go down, and line L4 stops. The result is , the corner of the box where is largest, with cost .
Correctness
The attack has no right answer in general: on a neural network it finds a local minimum of a nonconvex cost, and how much the result tells about a person is a measurement. What is proved, in the proof file, is the following.
Theorem (the gradients). The three gradient formulas above are the gradients of ; for the network, at every point where no hidden pre-activation is .
Theorem (binary logistic model). Let have no zero entry, let , and . The minimizer of on is the corner . With and , where , MI-FACE returns , in exact arithmetic, and with line L4 ends the run. The reason: every coordinate moves toward its end of by at least per step until it gets there, so the cost goes down at every step before , and line L4 cannot stop the run early.
Theorem (softmax regression). The function is concave. So a point that line L3 does not move is a global minimizer of on the box, and for every in the box the gap , which is a sum of easy terms, bounds from above.
Heuristic (networks). For a network with hidden layers the cost is not convex in , and MI-FACE can stop at a local minimum or at an input that no human would recognize. Fredrikson et al. report that their reconstructions from a multilayer network were much less clear than from softmax regression.
Proof: The gradients of the cost, the exact result of MI-FACE on a binary logistic model, and global optimality of its fixed points on a softmax regressionfull
Setting. A model gives class confidences on , the cost of the class is , and one step of line L3 is , where clip maps each coordinate to the nearest point of . All arithmetic is exact.
Claim 0 (what MI-FACE returns). For any cost, MI-FACE stops after at most steps and returns a point of with the least cost among , the points it visited, and the first one on ties.
Proof. The loop of line L2 runs at most times. is in the box, and each is a clip, so it is in the box. The code replaces the kept point only when the new cost is strictly lower, so it keeps the first point of least cost.
Claim 1 (the gradients). Write , so .
- For : with .
- For with : , where is row of .
- For with any logits differentiable at : , where . A tiny ReLU network is differentiable at every where no hidden pre-activation is , since there the pattern of active units is constant near and the logits are affine.
Proof. (1) is the chain rule. For (2), , so , and with we get . Then . For (3), , so .
Claim 2 (binary logistic model). Let with for all , let , , , and . Let if and if . Then is the unique minimizer of on the box. If and , MI-FACE returns and , and if , line L4 stops the run after at most steps.
Proof. The minimizer. and is strictly increasing, so is least where is largest. Each term with is largest only at , since .
A lower bound on the slope. For in the box, . The function is even and decreasing in , so .
The iterates. By Claim 1, coordinate of is . If , it is at most ; starting from , the clip keeps for all . If , it is at least , so : the coordinate grows by at least per step until it equals , and after that the clip keeps it at . So all coordinates with equal after at most steps. Let be the first index with ; then for all , because by the same two cases.
The costs. For , : some coordinate with was below at step and grows by a positive amount, and no coordinate moves the other way. So and , and line L4 does not stop the run. Line L5 never stops it, because . So the run reaches step when . The costs are strictly decreasing and every later cost equals , so the first visited point of least cost is , and by Claim 0 MI-FACE returns it. Finally, at step the last costs are all and , so line L4 stops the run there, or earlier, when .
Claim 3 (softmax regression). Let and . Then is concave. If , then minimizes on the box. For every in the box, with ,
where is any maximizer of on the box.
Proof. Concavity. with and . The Hessian of is , and for every vector , , the variance of under the distribution . So is convex, is convex in as a convex function of an affine map, and is an affine function minus a convex one, so it is concave.
The gap. By concavity, for every . Take , and bound by its maximum over the box. The maximum of the linear function on the box splits over the coordinates, and in coordinate it is attained at or , which gives .
Fixed points. By Claim 1, with . A coordinate of equals exactly when and , or and , or and . In each case both terms of the maximum in are at most and one of them is , so . Then , so maximizes , hence maximizes and minimizes .
What the tests check. The example and Claim 2 on random binary logistic models, with and a tolerance of for rounding; Claim 1 against central differences; and at the result on random softmax regressions, which by Claim 3 puts within of its largest value. Claim 3 does not say how many steps are needed to make small; that the tests reach it in at most steps of size is a measurement. For networks with a hidden layer need not be concave, and nothing beyond Claims 0 and 1 is claimed.
Complexity
- One step. One gradient and one cost: for softmax regression, for a network with hidden units, and queries for a black box gradient. Line L4 reads up to costs.
- Whole run. At most steps: for softmax regression.
- Space. The code keeps all costs, ; a ring buffer of the last costs gives .
Properties
- Needs only scores. With numeric gradients the attack needs only the confidence scores, at queries per step.
- A prototype, not a record. For a class with many training records the result is the input the model is most sure of. In the tests it is at distance more than from every training record of its class, while the records lie within of their class mean, at on average (a measurement).
- More sure than the data. In the tests the cost at the result is below , and the cost at the mean of the class is above (a measurement).
- Local. On a nonconvex model the result depends on and .
Variants and improvements
- Inversion of one feature. The attack of Fredrikson et al. (2014), as given in Section 3 of the 2015 paper, knows all features of a person but one sensitive feature with few values, and the label . It tries each value and returns the that maximizes , a maximum a posteriori estimate with the marginal priors and an error model err.
- Decision trees with counts. A white-box decision tree can report how many training records reach each leaf. Fredrikson et al. (2015, Section 4) use these counts in a better estimate and report no false positives on two survey models.
- A generative prior. Zhang et al. (2020) search in the input space of a generative model trained on public data, so that the result stays close to natural inputs.
- Inversion of gradients. In federated training a client sends gradients, not a model, and the gradients of one batch can be inverted to its inputs. See gradient-inversion-attack; secure aggregation by secure multiparty computation is a defense there.
- Defenses. Rounding of the reported confidence (Fredrikson et al. 2015, Section 6) breaks numeric gradients for small difference steps. Differential privacy in training, for example DP-SGD, bounds what one record can change in the model; Fredrikson et al. (2014) report that budgets small enough to stop their attack made the dosing model worse for patients in simulation.
When to use it
Use it to measure what a model that you own, or a model trained on synthetic data, leaks about its classes or about one sensitive feature, before you release it or put it behind an interface that returns scores. It is most meaningful when each class is one person or one small group, as in face recognition. For a test of whether a given record was in the training set, use a membership inference attack instead. For a guarantee about each record, use differential privacy, since a failed inversion does not show that a model is safe.
Pitfalls
- Inference is not always a leak. If a model learns that one feature predicts another in the whole population, an estimate of that feature for any person, in the training set or not, follows. Compare the attack on training members with the same attack on nonmembers; Fredrikson et al. (2015, Figure 5c) found members at higher risk on their tree models.
- Rounding is not a guarantee. In the tests, rounding the scores to multiples of stops a black box attack with difference step (it identifies class of , the rate of a guess), but a step of gets back of . Rounding hides small changes, not large ones. Rounding does nothing against a white-box attacker.
- Judge the result fairly. Success of a face reconstruction needs a human or a separate model to judge it. Fredrikson et al. asked workers to pick the person from a line up of five; a line up from a much larger set is harder.
- Step size and box. With a step that is too large the cost goes up and line L4 stops at once; without the clip, the result leaves the valid input range.
Implementations
The code runs only on models and data that the tests build from a fixed seed: binary logistic models, softmax regressions and tiny ReLU networks from the shared helper mlkit, in at most dimensions. It never queries a real model or reads a real data set. The tests check the example; check on random binary logistic models that MI-FACE returns the best corner within the step bound of the theorem; check the analytic gradients against central differences on points for each model type; and check on random softmax regressions that the concavity gap at the result is below . A measurement with seed 7604 trains a softmax regression on synthetic classes of records in dimensions. For each class, the white-box and the black-box result is nearest to the mean of the right class ( of both times), at distance to from every record of the class. With scores rounded to , black box differences of step identify class of , and of step , of .
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
# 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)
model_inversion_attack.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/model-inversion-attack/. The authors are listed in prov/PV1E6J.jsonl.
"""MI-FACE, the model inversion of Fredrikson, Jha and Ristenpart (2015), as an abstract model on synthetic data.
The attack looks for an input x in [0, 1]^d with a low cost c(x) = 1 - p_label(x), where
p_label is the confidence that a model gives to one class. The models here are a binary
logistic model, a softmax regression and a seeded tiny_relu_net from mlkit; the tests build
every model and every data point from a fixed seed. Nothing here reads a real data set or
queries a real model.
"""
import math
from typing import Callable, Sequence
from mlkit import Net, Vector, clip01, dot, forward, input_gradient, sigmoid, softmax
CostFn = Callable[[Sequence[float]], float]
GradFn = Callable[[Sequence[float]], Vector]
def logistic_cost(w: Sequence[float], b: float) -> tuple[CostFn, GradFn]:
"""The cost 1 - sigmoid(w.x + b) of the class 1 of a binary logistic model, and its gradient.
The gradient is -sigmoid'(z) w with sigmoid'(z) = sigmoid(z) (1 - sigmoid(z)). Cost O(d) per call.
"""
def cost(x: Sequence[float]) -> float:
return 1.0 - sigmoid(dot(w, x) + b)
def grad(x: Sequence[float]) -> Vector:
s = sigmoid(dot(w, x) + b)
return [-s * (1.0 - s) * wj for wj in w]
return cost, grad
def softmax_cost(weights: Sequence[Sequence[float]], biases: Sequence[float], label: int) -> tuple[CostFn, GradFn]:
"""The cost 1 - p_label(x) of a softmax regression p(x) = softmax(W x + b), and its gradient.
The gradient is -p_label (W_label - sum_k p_k W_k). Precondition: 0 <= label < k.
Cost O(k d) per call.
"""
def probs(x: Sequence[float]) -> Vector:
return softmax([dot(row, x) + bk for row, bk in zip(weights, biases, strict=True)])
def cost(x: Sequence[float]) -> float:
return 1.0 - probs(x)[label]
def grad(x: Sequence[float]) -> Vector:
p = probs(x)
d = len(x)
mean = [math.fsum(p[k] * weights[k][j] for k in range(len(p))) for j in range(d)]
return [-p[label] * (weights[label][j] - mean[j]) for j in range(d)]
return cost, grad
def net_cost(net: Net, label: int) -> tuple[CostFn, GradFn]:
"""The cost 1 - p_label(x) of a tiny_relu_net, and its gradient p_label(x) times the input gradient of the cross-entropy.
Since p_label = exp(-CE), the gradient of 1 - p_label is p_label times the gradient of CE.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0. Cost O(h d + k h) per call.
"""
def cost(x: Sequence[float]) -> float:
return 1.0 - softmax(forward(net, x))[label]
def grad(x: Sequence[float]) -> Vector:
p = softmax(forward(net, x))[label]
return [p * g for g in input_gradient(net, x, label)]
return cost, grad
def finite_difference_grad(cost: CostFn, h: float) -> GradFn:
"""A black box estimate of the gradient by central differences, 2 d queries of the cost per call.
Precondition: h > 0. Cost: 2 d calls of cost.
"""
def grad(x: Sequence[float]) -> Vector:
g = []
for j in range(len(x)):
up, dn = list(x), list(x)
up[j] += h
dn[j] -= h
g.append((cost(up) - cost(dn)) / (2.0 * h))
return g
return grad
def rounded_cost(cost: CostFn, r: float) -> CostFn:
"""The cost seen by a client when the service rounds each confidence to a multiple of r (a defense).
Precondition: r > 0. Cost: one call of cost.
"""
def out(x: Sequence[float]) -> float:
return 1.0 - r * round((1.0 - cost(x)) / r)
return out
def mi_face(cost: CostFn, grad: GradFn, d: int, alpha: int, beta: int, gamma: float, lam: float) -> tuple[Vector, float]:
"""MI-FACE (Algorithm 1 of Fredrikson et al. 2015) with PROCESS = the projection onto [0, 1]^d and no auxiliary term.
Gradient descent on the cost from x_0 = 0, for at most alpha steps of size lam. It stops when
the cost of x_i is at least the largest of the last beta costs (no progress), or when it is at
most gamma. Returns the visited point of least cost (the first one on ties) and its cost.
Precondition: d >= 1, alpha >= 0, beta >= 1, lam > 0.
Cost O(alpha (g + c + beta)), where g and c are the costs of one call of grad and of cost.
"""
x = [0.0] * d # @line L1
history = [cost(x)]
best_x, best_c = x, history[0]
for _ in range(alpha): # @line L2
g = grad(x)
x = clip01([xj - lam * gj for xj, gj in zip(x, g, strict=True)]) # @line L3
c = cost(x)
if c < best_c:
best_x, best_c = x, c
if c >= max(history[-beta:]): # @line L4
break
history.append(c)
if c <= gamma: # @line L5
break
return best_x, best_c # @line L6
test_model_inversion_attack.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/model-inversion-attack/. The authors are listed in prov/PV1E6J.jsonl.
"""Tests of MI-FACE on seeded synthetic models: binary logistic, softmax regression and a tiny ReLU network."""
import math
import random
from mlkit import Data, accuracy, argmax, clip01, dot, make_blobs, norm2, sigmoid, softmax, sub, tiny_relu_net
from model_inversion_attack import (
finite_difference_grad,
logistic_cost,
mi_face,
net_cost,
rounded_cost,
softmax_cost,
)
def central(f, x: list[float], e: float = 1e-6) -> list[float]:
"""An independent central difference gradient, the oracle for the analytic gradients."""
g = []
for j in range(len(x)):
up, dn = x[:], x[:]
up[j] += e
dn[j] -= e
g.append((f(up) - f(dn)) / (2 * e))
return g
def train_softmax(data: Data, k: int, steps: int, lr: float) -> tuple[list[list[float]], list[float]]:
"""Full-batch gradient descent on the mean cross-entropy of a softmax regression, from zero."""
d, n = len(data[0][0]), len(data)
w = [[0.0] * d for _ in range(k)]
b = [0.0] * k
for _ in range(steps):
gw = [[0.0] * d for _ in range(k)]
gb = [0.0] * k
for x, y in data:
p = softmax([dot(row, x) + bc for row, bc in zip(w, b)])
p[y] -= 1.0
for c in range(k):
gb[c] += p[c]
for j in range(d):
gw[c][j] += p[c] * x[j]
w = [[w[c][j] - lr * gw[c][j] / n for j in range(d)] for c in range(k)]
b = [b[c] - lr * gb[c] / n for c in range(k)]
return w, b
def test_example_of_the_page() -> None:
cost, grad = logistic_cost([2.0, -1.0], 0.0)
x1, c1 = mi_face(cost, grad, 2, 1, 1, 0.0, 1.0)
assert x1 == [0.5, 0.0] and abs(c1 - (1 - sigmoid(1.0))) < 1e-15
x2, _ = mi_face(cost, grad, 2, 2, 1, 0.0, 1.0)
s = sigmoid(1.0)
assert abs(x2[0] - (0.5 + 2 * s * (1 - s))) < 1e-15 and x2[1] == 0.0
x, c = mi_face(cost, grad, 2, 100, 1, 0.0, 1.0)
assert x == [1.0, 0.0] and abs(c - (1 - sigmoid(2.0))) < 1e-15
assert abs(x2[0] - 0.8932238664829637) < 1e-12 and abs(c - 0.11920292202211755) < 1e-15
def test_binary_logistic_reaches_the_best_corner() -> None:
rng = random.Random(7601)
done = 0
while done < 500:
d = rng.randint(1, 8)
w = [rng.gauss(0.0, 1.0 / math.sqrt(d)) for _ in range(d)]
if min(abs(v) for v in w) < 0.05:
continue
done += 1
b = rng.gauss(0.0, 0.3)
lam = rng.uniform(0.5, 2.0)
beta = rng.randint(1, 5)
m = sum(abs(v) for v in w) + abs(b)
q = sigmoid(m) * (1 - sigmoid(m)) # the least slope of the sigmoid on the box
n = math.ceil(1 / (lam * q * min(abs(v) for v in w))) # the step bound of the theorem
cost, grad = logistic_cost(w, b)
x, c = mi_face(cost, grad, d, n + beta + 1, beta, 0.0, lam)
corner = [1.0 if v > 0 else 0.0 for v in w]
assert max(abs(u - v) for u, v in zip(x, corner)) < 1e-9
assert abs(c - (1 - sigmoid(dot(w, corner) + b))) < 1e-9
def test_analytic_gradients_match_finite_differences() -> None:
rng = random.Random(7602)
for _ in range(500):
d, k = rng.randint(1, 8), rng.randint(2, 4)
x = [rng.random() for _ in range(d)]
w = [rng.gauss(0, 1) for _ in range(d)]
cost, grad = logistic_cost(w, 0.1)
assert max(abs(u - v) for u, v in zip(grad(x), central(cost, x))) < 1e-6
assert max(abs(u - v) for u, v in zip(finite_difference_grad(cost, 1e-5)(x), grad(x))) < 1e-6
ws = [[rng.gauss(0, 1) for _ in range(d)] for _ in range(k)]
bs = [rng.gauss(0, 0.3) for _ in range(k)]
cost, grad = softmax_cost(ws, bs, rng.randrange(k))
assert max(abs(u - v) for u, v in zip(grad(x), central(cost, x))) < 1e-6
checked = 0
while checked < 500:
d, h = rng.randint(1, 8), rng.randint(1, 16)
net = tiny_relu_net(rng, d, h, 3)
x = [rng.random() for _ in range(d)]
if any(abs(dot(row, x) + bi) < 1e-3 for row, bi in zip(net["W1"], net["b1"])):
continue # too close to a kink for a finite difference
checked += 1
cost, grad = net_cost(net, rng.randrange(3))
assert max(abs(u - v) for u, v in zip(grad(x), central(cost, x))) < 1e-6
def test_softmax_inversion_is_near_optimal() -> None:
"""ln p_label is concave, so the Frank-Wolfe gap max over the box of g.(z - x) bounds the distance to the optimum."""
rng = random.Random(7603)
for _ in range(500):
d, k = rng.randint(1, 8), rng.randint(2, 4)
ws = [[rng.gauss(0, 1 / math.sqrt(d)) for _ in range(d)] for _ in range(k)]
bs = [rng.gauss(0, 0.3) for _ in range(k)]
y = rng.randrange(k)
cost, grad = softmax_cost(ws, bs, y)
x, c = mi_face(cost, grad, d, 300, 1, 0.0, 4.0)
assert all(0.0 <= v <= 1.0 for v in x)
assert c == cost(x) and c <= cost([0.0] * d)
p = softmax([dot(row, x) + bc for row, bc in zip(ws, bs)])
g = [ws[y][j] - math.fsum(p[t] * ws[t][j] for t in range(k)) for j in range(d)]
gap = sum(max(gj * (0.0 - xj), gj * (1.0 - xj)) for gj, xj in zip(g, x))
assert gap < 1e-3 # so ln p_label(x) is within 1e-3 of its largest value on the box
def test_inversion_identifies_each_class_and_rounding_stops_a_fine_black_box() -> None:
"""A measurement: 6 synthetic classes in 8 dimensions, 10 records each, and a softmax regression."""
rng = random.Random(7604)
d, k = 8, 6
centers = [[rng.uniform(0.2, 0.8) for _ in range(d)] for _ in range(k)]
data = [(clip01(x), y) for x, y in make_blobs(rng, 60, d, centers, 0.1)]
w, b = train_softmax(data, k, 300, 1.0)
assert accuracy(lambda x: argmax([dot(row, x) + bc for row, bc in zip(w, b)]), data) == 1.0
means = [[sum(x[j] for x, y in data if y == c) / 10 for j in range(d)] for c in range(k)]
def nearest(x: list[float]) -> int:
return min(range(k), key=lambda q: norm2(sub(x, means[q])))
white = black = fine = coarse = 0
far = []
for c in range(k):
cost, grad = softmax_cost(w, b, c)
x, cx = mi_face(cost, grad, d, 500, 20, 0.0, 1.0)
assert cx < 0.01 < cost(means[c]) # more confident than on the mean of the class
white += nearest(x) == c
far.append(min(norm2(sub(x, r)) for r, y in data if y == c))
xb, _ = mi_face(cost, finite_difference_grad(cost, 1e-3), d, 500, 20, 0.0, 1.0)
black += nearest(xb) == c
rc = rounded_cost(cost, 0.05)
xf, _ = mi_face(rc, finite_difference_grad(rc, 1e-3), d, 500, 20, 0.0, 1.0)
fine += nearest(xf) == c
xc, _ = mi_face(rc, finite_difference_grad(rc, 0.1), d, 500, 20, 0.0, 1.0)
coarse += nearest(xc) == c
assert white == 6 and black == 6 # every class is identified, with or without the weights
assert min(far) > 0.5 # but the result is far from every training record of its class
assert max(norm2(sub(x, means[y])) for x, y in data) < 0.4 # while the records are close to their mean
assert fine <= 2 # rounding to 0.05 flattens a difference of step 0.001
assert coarse >= 4 # and a step of 0.1 gets most of the classes back
History
Fredrikson, Lantz, Jha, Lin, Page and Ristenpart (2014) introduced model inversion on a linear model for warfarin dosing and found that it estimates a patient's genetic marker about as well as a model trained to predict it. Fredrikson, Jha and Ristenpart (2015) turned to services that return confidence scores: they inverted decision trees on lifestyle surveys and recovered recognizable faces from face recognition models with MI-FACE, where human workers picked the right person from a line up in up to percent of the cases for softmax regression. They also tried rounding of the scores and a tree training method that places the sensitive feature carefully. Later work, for example Zhang et al. (2020), added priors from generative models to invert deep networks.
References
- Matt Fredrikson, Somesh Jha and Thomas Ristenpart, Model inversion attacks that exploit confidence information and basic countermeasures, ACM Conference on Computer and Communications Security (CCS) 2015, pages 1322-1333, doi:10.1145/2810103.2813677, Section 3 and Figure 2 (the estimator of Fredrikson et al. 2014), Section 4 and equation (1) (the white-box estimator with counts for decision trees), Algorithm 1 (MI-FACE) and Section 5.2 (the reconstruction attack, with alpha = 5000, beta = 100 and lambda = 0.1), Section 5.3 (black box with numeric gradients), Section 6 and Figure 12 (rounded confidence scores as a countermeasure)
- Matt Fredrikson, Eric Lantz, Somesh Jha, Simon Lin, David Page and Thomas Ristenpart, Privacy in pharmacogenetics: an end-to-end case study of personalized warfarin dosing, USENIX Security Symposium 2014, pages 17-32, the first model inversion attack, which estimates a genetic marker of a patient from a linear dosing model and other attributes of the patient, and the study of differential privacy as a defense
- Yuheng Zhang, Ruoxi Jia, Hengzhi Pei, Wenxiao Wang, Bo Li and Dawn Song, The secret revealer: generative model-inversion attacks against deep neural networks, IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) 2020, a generative model trained on public data as a prior that keeps the inversion close to natural inputs
- 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.
| 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 PV1E6J Edit this page History Report an error Markdown