Algorithmresearch
Matrix mechanism
Also called strategy matrix mechanism.
Answers a workload of linear queries by adding Laplace noise to a chosen strategy set of queries and then deriving the workload answers by least squares.
- Time
- O(p n^2 + n^3 + m n) worst
- Space
- O(p n + m n) extra
- Where
- m = the number of workload queries; n = the number of cells; p = the number of strategy queries
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chao Li, Michael Hay, Vibhor Rastogi, Gerome Miklau, Andrew McGregor, 2010
The matrix mechanism answers a set of linear queries on a histogram, such as all range counts, by a detour. It picks a second set of linear queries, the strategy, and answers those with the Laplace mechanism. Then it finds the least squares estimate of the histogram from the noisy strategy answers, and computes the wanted queries from that estimate. The choice of strategy changes the error, often by a large factor, and the privacy cost stays . The identity strategy, the binary tree of ranges and wavelets are all special cases, and the mechanism gives one formula to compare them.
In plain words
You must publish many totals from one table of counts, for example the number of people in every age range. Many of the totals overlap, so each person affects many of them, and noise on each total must be large.
The matrix mechanism asks a different set of questions first. It picks them so that each person affects few of them, and so that the wanted totals can be built from them. It adds noise to those answers. Then it finds the table of counts that best fits the noisy answers, and computes all the wanted totals from that table. A good choice of the first questions gives much less noise in the totals.
The problem
The data is a histogram : is the number of records in cell . The workload is an matrix , and the goal is to release an estimate of . Two histograms are neighbors if one is the other with one record added or removed: . The release must be -DP, and the goal is a small expected total squared error .
A strategy is a matrix of full column rank. Its sensitivity is the largest norm of a column of , because a change in cell moves by the column .
is the Laplace distribution with density . It has variance , and .
The algorithm
MATRIX-MECHANISM(W, A, x, ε)- 1
Δ_A ← max over columns j of Σᵢ |Aᵢⱼ| ▷ the l1 sensitivity of x ↦ Ax - 2
y ← A x + z, with zᵢ ~ Lap(Δ_A/ε) independent ▷ the Laplace mechanism on the strategy - 3
A⁺ ← (AᵀA)⁻¹ Aᵀ ▷ the pseudoinverse - 4
x̂ ← A⁺ y ▷ the least squares estimate of x - 5
output W x̂
Line L2 is the only step that reads the data. Lines L3 to L5 are post-processing, so they cost no privacy. Line L4 picks the that minimizes , which also makes the answers consistent: they all come from one histogram. The pseudoinverse in line L3 can be computed by the normal equations as written, or more stably by a QR decomposition.
Example
Take cells with and . The workload is all 10 range queries . The table compares three strategies by the error formula of the Correctness section. The values are exact and the test file checks them.
| strategy | rows | total squared error over the 10 ranges | |
|---|---|---|---|
| identity: one count per cell | 4 | 1 | 40 |
| hierarchical: the cells, the two halves and the total | 7 | 3 | |
| the workload itself | 10 | 6 | 288 |
Answering the 10 ranges directly is the worst choice, because a middle cell lies in 6 of them. At this small the identity is the best of the three. The run of the code with the hierarchical strategy and random.Random(1) draws the noisy strategy answers for the true answers . Least squares gives , and the 10 range answers follow from .
The hierarchical strategy wins for large : its error for one range grows as (a theorem, from the binary tree bound), and the error of the identity grows as . The crossover is late. At the code gives a total error of 91520 for the identity and about 264672 for the hierarchical strategy (a measurement).
Correctness
Privacy (a theorem). For neighbors , is the norm of column , at most . So line L2 is the Laplace mechanism with the right scale, and is -DP. Lines L3 to L5 do not read , so the output is -DP by post-processing.
Unbiased (a theorem). for a strategy of full column rank, so .
Error (a theorem, Li et al. 2010). The expected total squared error is
The key step is . For a fixed , least squares is the best linear reconstruction, by the Gauss-Markov argument. The full proofs are in proofs/correctness.md.
Proof: The matrix mechanism is epsilon-DP and unbiased, with error 2 (Delta_A/epsilon)^2 trace(W (A^T A)^(-1) W^T)full
We use the pseudocode of the page. The data is a histogram . Two histograms are neighbors if they differ by 1 in one cell: (add/remove one record). The workload is an matrix and the strategy is a matrix of full column rank . Let , , and . The noise has independent entries.
Claim 1 (privacy). The output is -DP.
Proof. For neighbors , , the -th column of up to sign. So , and is reached for the column with the largest norm. The density of at a point is . By the triangle inequality, for every ,
So is -DP. Lines L3 to L5 compute a fixed function of that does not look at , so the output is -DP by post-processing.
Claim 2 (unbiased). .
Proof. , and . So , and is linear.
Claim 3 (error). The expected total squared error is
Proof. The error is (Claim 2). The entries of are independent with mean 0 and variance , so . Then
and .
Claim 4 (least squares is the best linear reconstruction). Among all matrices with , the choice has the smallest expected total squared error .
Proof. Each such gives an unbiased estimate of , with error . Write . Then . So , and
The middle term is , and the last term is at least 0, with equality only for .
This is the Gauss-Markov theorem for independent noise of equal variance. It says that, for a fixed strategy , the only free choice left is itself.
Cost. Line L1 reads in . Line L2 costs and Laplace draws. Line L3 forms in , inverts it in and multiplies by in . Line L4 costs and line L5 costs . The space is for the matrices. Lines L1 and L3 do not depend on the data, so for a fixed strategy they can be done one time and reused.
Complexity
In the real-RAM model with one Laplace draw at unit cost:
- Line L2 costs and draws.
- Line L3 costs : it forms and inverts it.
- Line L5 costs .
- The space is for the matrices.
Lines L1 and L3 do not depend on the data. For a fixed strategy they can be done one time and reused. The hard part in practice is not the mechanism but the choice of : the search for the best strategy is an optimization over matrices, and it is much more costly than one run.
Properties
- Pure DP. With Laplace noise the output is -DP.
- Unbiased and consistent. The answers are unbiased, and they all come from one estimate , so overlapping answers agree.
- Data independent. The error depends on , and , not on . So the error can be computed and compared before any data is touched.
- Linear queries only. The workload must be linear in the histogram.
- Negative estimates. The estimate can have negative cells, as in the example. Rounding or clipping it is post-processing, so it is still private, but it breaks the unbiased property.
Variants and improvements
- Gaussian noise. For -DP, use the Gaussian mechanism in line L2. The sensitivity becomes the largest norm of a column, and the error has the same form with the Gaussian variance.
- Strategy search. Li et al. give methods to search for a good for a given . HDMM (McKenna, Miklau, Hay and Machanavajjhala 2018) searches over strategies with a product structure, which scales to data with many attributes.
- Known strategies. The identity, the hierarchical strategy of Hay, Rastogi, Miklau and Suciu (2010) and the wavelet strategy of Xiao, Wang and Gehrke (2010) are all instances. The binary tree mechanism for continual counting is the hierarchical strategy run online.
- Factorization mechanisms. In general any factorization gives the release . The matrix mechanism takes , the best for a given . Later work on prefix sums and on private training searches over such factorizations directly.
- Adaptive data methods. Methods that adapt the strategy to the data, such as MWEM, can do better on some data, but their error is no longer data independent.
When to use it
Use the matrix mechanism when the workload is a fixed, known set of linear queries on a histogram of moderate size, such as range queries, marginals of a few attributes, or the cells of a census table. It is best when many queries overlap, so that a good strategy shares the noise. For one query, or for queries on disjoint cells, the plain Laplace mechanism is already best. For a very large or unknown workload, see private query release.
Pitfalls
- Sensitivity of the wrong matrix. Line L1 must use the strategy , not the workload . The noise is added to , so its scale is set by the columns of . Using is wrong in both directions: it gives too much noise when , and a privacy failure when .
- Row norms in place of column norms. The sensitivity in line L1 is the largest column norm, because one record changes one cell. The largest row norm measures the size of one query, not the effect of one record. For the hierarchical strategy on cells it is , while , and for a strategy with one long column it is smaller than .
- A strategy without full column rank. Line L3 needs to be invertible. If does not have full column rank, some queries of cannot be built from . The code raises an error.
- Unstable algebra. For large or badly conditioned , the normal equations in line L3 lose precision. Use a QR or Cholesky solve. The privacy proof does not depend on how line L3 is computed, but the error formula does.
- Float noise. The code uses float Laplace noise from
random.Random, for tests only. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012; Canonne, Kamath and Steinke 2020); see the discrete Gaussian mechanism.
Implementations
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/.
"""Checkers for differential privacy on small finite examples.
A dataset is a tuple of records from a finite universe. A pmf is a dict from
outputs to probabilities; the probabilities may be fractions.Fraction (exact)
or float. A mechanism pmf is a function from a dataset to the pmf of the
output of the mechanism on that dataset.
This module holds the neighbor relations, the privacy loss, the hockey-stick
and Renyi divergences, the pure and approximate DP checks over a list of
neighbor pairs, an empirical pmf, the Hoeffding margin for Monte Carlo
checks, and a grid check of a log density ratio. It holds no mechanism, no
noise sampler and no accountant: those belong to the pages that define them.
Natural logarithms are used throughout, as in the DP literature.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import Callable, Hashable, Iterable, Mapping, Sequence, Union
Number = Union[int, float, Fraction]
Pmf = Mapping[Hashable, Number]
Dataset = tuple
Pair = tuple[Dataset, Dataset]
def neighbors_add_remove(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
"""All datasets at add/remove distance 1 from dataset.
A neighbor removes one record, or appends one record from the universe.
Datasets are treated as multisets: a removal keeps the order of the other
records, and equal results are listed once. Cost: O(n (n + |universe|)).
"""
x = tuple(dataset)
out: list[Dataset] = []
seen: set[Dataset] = set()
for i in range(len(x)):
y = x[:i] + x[i + 1:]
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
for v in universe:
y = x + (v,)
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
return out
def neighbors_replace(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
"""All datasets of the same size that differ from dataset in one record.
The record at index i is replaced by a different value of the universe.
Equal multisets are listed once. Cost: O(n^2 |universe|).
"""
x = tuple(dataset)
values = list(universe)
out: list[Dataset] = []
seen: set[Dataset] = set()
for i in range(len(x)):
for v in values:
if v == x[i]:
continue
y = x[:i] + (v,) + x[i + 1:]
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
return out
def _ratio(a: Number, b: Number) -> Number:
if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
return Fraction(a) / Fraction(b)
return float(a) / float(b)
def privacy_loss(p: Pmf, q: Pmf) -> dict[Hashable, float]:
"""The privacy loss ln(p(y) / q(y)) at each output y with p(y) > 0 or q(y) > 0.
The value is +inf where q(y) = 0 < p(y) and -inf where p(y) = 0 < q(y).
Outputs with p(y) = q(y) = 0 are left out. Cost: O(|support|).
"""
out: dict[Hashable, float] = {}
for y in set(p) | set(q):
a, b = p.get(y, 0), q.get(y, 0)
if a == 0 and b == 0:
continue
if b == 0:
out[y] = math.inf
elif a == 0:
out[y] = -math.inf
else:
out[y] = math.log(_ratio(a, b))
return out
def max_privacy_loss(p: Pmf, q: Pmf) -> float:
"""The largest privacy loss ln(p(y) / q(y)) over the outputs y with p(y) > 0.
Returns -inf when p has no output of positive probability. Cost: O(|support|).
"""
best = -math.inf
for y, v in privacy_loss(p, q).items():
if p.get(y, 0) > 0 and v > best:
best = v
return best
def hockey_stick(p: Pmf, q: Pmf, epsilon: float) -> float:
"""The hockey-stick divergence: the sum over y of max(0, p(y) - e^epsilon q(y)).
It is sup over sets S of P(S) - e^epsilon Q(S). Cost: O(|support|).
"""
a = math.exp(epsilon)
total = 0.0
for y in set(p) | set(q):
d = float(p.get(y, 0)) - a * float(q.get(y, 0))
if d > 0:
total += d
return total
def is_pure_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, tol: float = 1e-12) -> bool:
"""True if max privacy loss <= epsilon + tol for both orders of every pair.
Precondition: mech_pmf returns the exact output pmf of the mechanism.
Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
"""
for x, y in pairs:
p, q = mech_pmf(x), mech_pmf(y)
if max_privacy_loss(p, q) > epsilon + tol or max_privacy_loss(q, p) > epsilon + tol:
return False
return True
def is_approx_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, delta: float, tol: float = 1e-12) -> bool:
"""True if the hockey-stick divergence at e^epsilon is <= delta + tol for both orders of every pair.
Precondition: mech_pmf returns the exact output pmf of the mechanism.
Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
"""
for x, y in pairs:
p, q = mech_pmf(x), mech_pmf(y)
if hockey_stick(p, q, epsilon) > delta + tol or hockey_stick(q, p, epsilon) > delta + tol:
return False
return True
def renyi_divergence(p: Pmf, q: Pmf, alpha: float) -> float:
"""The Renyi divergence of order alpha > 1: ln(sum_y p(y)^alpha q(y)^(1 - alpha)) / (alpha - 1).
Returns +inf when q(y) = 0 < p(y) for some y. Cost: O(|support|).
"""
if alpha <= 1:
raise ValueError("alpha must be greater than 1")
s = 0.0
for y in set(p) | set(q):
a, b = float(p.get(y, 0)), float(q.get(y, 0))
if a == 0:
continue
if b == 0:
return math.inf
s += a * (a / b) ** (alpha - 1)
return math.log(s) / (alpha - 1)
def empirical_pmf(samples: Iterable[Hashable]) -> dict[Hashable, float]:
"""The fraction of the samples equal to each value. Cost: O(number of samples)."""
counts: dict[Hashable, int] = {}
n = 0
for s in samples:
counts[s] = counts.get(s, 0) + 1
n += 1
if n == 0:
return {}
return {k: c / n for k, c in counts.items()}
def hoeffding_margin(n: int, beta: float) -> float:
"""The margin t = sqrt(ln(2 / beta) / (2 n)).
For n independent samples of a [0, 1] variable, the empirical mean is
within t of the true mean with probability at least 1 - beta (Hoeffding).
"""
if n <= 0 or not 0 < beta < 1:
raise ValueError("need n >= 1 and 0 < beta < 1")
return math.sqrt(math.log(2 / beta) / (2 * n))
def log_ratio_grid(logpdf_x: Callable[[float], float], logpdf_y: Callable[[float], float], grid: Iterable[float]) -> float:
"""The largest |logpdf_x(z) - logpdf_y(z)| over the points z of the grid.
Use it to check the log density ratio of a continuous mechanism on two
neighbors. Cost: O(|grid|) calls of each function.
"""
best = 0.0
for z in grid:
d = abs(logpdf_x(z) - logpdf_y(z))
if d > best:
best = d
return best
matrix_mechanism.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/matrix-mechanism/. The authors are listed in prov/73DA32.jsonl.
"""The matrix mechanism for a workload of linear counting queries
(Li, Hay, Rastogi, Miklau and McGregor 2010), with Laplace noise.
The data is a histogram x in N^n (one count per cell). The workload is an
m x n matrix W; the true answers are W x. The analyst picks a strategy, a
p x n matrix A of full column rank. The mechanism answers A x with Laplace
noise, finds the least squares estimate of x, and outputs W times it.
Neighbors are add/remove: x' = x + e_j or x - e_j for one cell j. Then the
l1 sensitivity of x -> A x is the largest l1 norm of a column of A.
The linear algebra works over any field type: pass Fraction entries for
exact results, or floats. The code uses random.Random so that the tests can
be repeated, and float noise. A real release needs a cryptographic source
of randomness and an exact sampler (Mironov 2012; Canonne, Kamath and
Steinke 2020).
"""
from __future__ import annotations
import math
import random
from fractions import Fraction
from typing import Sequence
Matrix = list[list]
def laplace_noise(b: float, rng: random.Random) -> float:
"""One draw of Lap(b), the density (1/(2b)) exp(-|z|/b), by the inverse CDF.
Precondition: b > 0. Cost: one uniform draw and O(1) time.
"""
u = rng.random() - 0.5
while u == -0.5:
u = rng.random() - 0.5
s = (u > 0) - (u < 0)
return -b * s * math.log(1.0 - 2.0 * abs(u))
def transpose(A: Sequence[Sequence]) -> Matrix:
"""The transpose of A. Cost: O(pn)."""
return [list(col) for col in zip(*A)]
def matmul(A: Sequence[Sequence], B: Sequence[Sequence]) -> Matrix:
"""The product A B. Precondition: the inner sizes agree. Cost: O(m k n)."""
Bt = transpose(B)
return [[sum(a * b for a, b in zip(row, col)) for col in Bt] for row in A]
def matvec(A: Sequence[Sequence], x: Sequence) -> list:
"""The product A x. Cost: O(p n)."""
return [sum(a * v for a, v in zip(row, x)) for row in A]
def inverse(M: Sequence[Sequence]) -> Matrix:
"""The inverse of a square matrix by Gauss-Jordan elimination with partial pivoting.
Raises ValueError if M is singular (exactly for Fraction entries, to a
tolerance of 1e-12 times the largest entry for floats). Cost: O(n^3).
"""
n = len(M)
exact = not any(isinstance(v, float) for row in M for v in row)
one, zero = (Fraction(1), Fraction(0)) if exact else (1.0, 0.0)
aug = [
[Fraction(v) if exact else v for v in row] + [one if i == j else zero for j in range(n)]
for i, row in enumerate(M)
]
scale = max((abs(v) for row in M for v in row), default=0)
tol = 0 if exact else 1e-12 * scale
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aug[r][c]))
if abs(aug[p][c]) <= tol:
raise ValueError("matrix is singular")
aug[c], aug[p] = aug[p], aug[c]
piv = aug[c][c]
aug[c] = [v / piv for v in aug[c]]
for r in range(n):
if r != c and aug[r][c] != 0:
f = aug[r][c]
aug[r] = [a - f * b for a, b in zip(aug[r], aug[c])]
return [row[n:] for row in aug]
def pseudoinverse(A: Sequence[Sequence]) -> Matrix:
"""The left inverse A^+ = (A^T A)^(-1) A^T of a matrix of full column rank.
A^+ y is the least squares solution of A x = y. Raises ValueError if A
does not have full column rank. Cost: O(p n^2 + n^3).
"""
At = transpose(A)
return matmul(inverse(matmul(At, A)), At)
def sensitivity(A: Sequence[Sequence]) -> float:
"""The l1 sensitivity of x -> A x under add/remove: the largest column l1 norm. Cost: O(p n)."""
return max(sum(abs(v) for v in col) for col in zip(*A))
def matrix_mechanism(
W: Sequence[Sequence],
A: Sequence[Sequence],
x: Sequence[int],
epsilon: float,
rng: random.Random,
) -> list[float]:
"""Answer the workload W on the histogram x through the strategy A, with epsilon-DP.
Precondition: epsilon > 0, A has full column rank, and W and A have
len(x) columns. Cost: O(p n^2 + n^3 + m n) arithmetic and p Laplace draws.
"""
if epsilon <= 0:
raise ValueError("epsilon must be positive")
delta_a = sensitivity(A) # @line L1
b = delta_a / epsilon
y = [v + laplace_noise(b, rng) for v in matvec(A, x)] # @line L2
A_plus = pseudoinverse([[float(v) for v in row] for row in A]) # @line L3
x_hat = matvec(A_plus, y) # @line L4
return matvec(W, x_hat) # @line L5
def total_squared_error(W: Sequence[Sequence], A: Sequence[Sequence], epsilon: float):
"""The expected total squared error 2 (Delta_A / epsilon)^2 trace(W (A^T A)^(-1) W^T).
Exact if the entries are Fraction and epsilon is 1. Cost: O(p n^2 + n^3 + m n^2).
"""
At = transpose(A)
G = inverse(matmul(At, A))
WG = matmul(W, G)
tr = sum(sum(a * b for a, b in zip(WG[i], W[i])) for i in range(len(W)))
d = sensitivity(A)
return 2 * d * d * tr / (epsilon * epsilon)
def identity(n: int) -> Matrix:
"""The n x n identity strategy: one noisy count per cell."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
def all_range_queries(n: int) -> Matrix:
"""The workload of all n(n+1)/2 range queries x[i] + ... + x[j] over n cells."""
return [[1 if i <= k <= j else 0 for k in range(n)] for i in range(n) for j in range(i, n)]
def hierarchical_strategy(n: int) -> Matrix:
"""The binary hierarchical strategy: the sum over each dyadic block of cells.
Precondition: n is a power of two. It has 2n - 1 rows and each cell lies
in log2(n) + 1 of them, so its sensitivity is log2(n) + 1.
"""
if n < 1 or n & (n - 1):
raise ValueError("n must be a power of two")
rows = []
size = 1
while size <= n:
for start in range(0, n, size):
rows.append([1 if start <= k < start + size else 0 for k in range(n)])
size *= 2
return rows
test_matrix_mechanism.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/matrix-mechanism/. The authors are listed in prov/73DA32.jsonl.
import math
import random
from fractions import Fraction
import dpkit
from matrix_mechanism import (
all_range_queries,
hierarchical_strategy,
identity,
inverse,
laplace_noise,
matmul,
matrix_mechanism,
matvec,
pseudoinverse,
sensitivity,
total_squared_error,
transpose,
)
def _random_full_rank(rng: random.Random, p: int, n: int) -> list:
while True:
A = [[rng.randrange(-2, 3) for _ in range(n)] for _ in range(p)]
try:
inverse(matmul(transpose(A), A))
return A
except ValueError:
continue
def test_pseudoinverse_meets_penrose_conditions_exactly() -> None:
# The oracle is the four Penrose equations, checked in exact arithmetic.
rng = random.Random(1)
for _ in range(500):
n = rng.randrange(1, 4)
p = rng.randrange(n, n + 3)
A = _random_full_rank(rng, p, n)
P = pseudoinverse(A)
assert matmul(matmul(A, P), A) == [[Fraction(v) for v in row] for row in A]
assert matmul(matmul(P, A), P) == P
AP = matmul(A, P)
assert AP == transpose(AP)
PA = matmul(P, A)
assert PA == [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# Least squares: the residual of A^+ y is orthogonal to the columns of A.
y = [rng.randrange(-5, 6) for _ in range(p)]
r = [a - b for a, b in zip(matvec(A, matvec(P, y)), y)]
assert matvec(transpose(A), r) == [0] * n
def test_noise_free_answers_are_exact() -> None:
rng = random.Random(2)
for _ in range(200):
n = rng.randrange(1, 4)
A = _random_full_rank(rng, rng.randrange(n, n + 3), n)
W = [[rng.randrange(0, 2) for _ in range(n)] for _ in range(rng.randrange(1, 5))]
x = [rng.randrange(0, 10) for _ in range(n)]
assert matvec(W, matvec(pseudoinverse(A), matvec(A, x))) == matvec(W, x)
def test_rank_deficient_strategy_is_rejected() -> None:
try:
pseudoinverse([[1, 1], [2, 2]])
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
def test_sensitivity_is_the_largest_change_over_all_neighbors() -> None:
rng = random.Random(3)
for _ in range(100):
n = rng.randrange(1, 5)
A = [[rng.randrange(-3, 4) for _ in range(n)] for _ in range(rng.randrange(1, 6))]
x = [rng.randrange(0, 5) for _ in range(n)]
worst = 0
for j in range(n):
for sign in (1, -1):
x2 = list(x)
x2[j] += sign
worst = max(worst, sum(abs(a - b) for a, b in zip(matvec(A, x), matvec(A, x2))))
assert worst == sensitivity(A)
assert sensitivity(hierarchical_strategy(8)) == 4
def _logpdf(point, centers, b):
return sum(-abs(z - c) / b - math.log(2 * b) for z, c in zip(point, centers))
def test_noisy_strategy_answers_are_epsilon_dp() -> None:
rng = random.Random(4)
A, epsilon = hierarchical_strategy(4), 0.5
b = sensitivity(A) / epsilon
for _ in range(40):
x = [rng.randrange(0, 6) for _ in range(4)]
j = rng.randrange(4)
x2 = list(x)
x2[j] += 1
cx, cy = matvec(A, x), matvec(A, x2)
base = [rng.uniform(-10, 20) for _ in cx]
d = [rng.uniform(-1, 1) for _ in cx]
grid = [k / 4 for k in range(-300, 301)]
f = lambda z, c: _logpdf([p + z * e for p, e in zip(base, d)], c, b)
assert dpkit.log_ratio_grid(lambda z: f(z, cx), lambda z: f(z, cy), grid) <= epsilon + 1e-9
# Tight: far below all centers, the three rows that hold cell 0 each move the ratio by 1/b.
far = [-100.0] * 7
x = [1, 1, 1, 1]
assert math.isclose(_logpdf(far, matvec(A, [0, 1, 1, 1]), b) - _logpdf(far, matvec(A, x), b), epsilon)
def test_example_errors() -> None:
W = all_range_queries(4)
assert total_squared_error(W, identity(4), 1) == 40
assert total_squared_error(W, hierarchical_strategy(4), 1) == Fraction(876, 7)
assert total_squared_error(W, W, 1) == 288 # answering the workload itself
for n in (2, 4, 8):
# The identity strategy has total error 2 * (sum of range lengths) = n(n+1)(n+2)/3.
assert total_squared_error(all_range_queries(n), identity(n), 1) == n * (n + 1) * (n + 2) // 3
def test_monte_carlo_error_and_bias_match_formula() -> None:
rng = random.Random(5)
W, x, epsilon, runs = all_range_queries(4), [3, 0, 5, 2], 1.0, 1500
true = matvec(W, x)
for A in (identity(4), hierarchical_strategy(4)):
want = float(total_squared_error(W, A, epsilon))
sq, mean = 0.0, [0.0] * len(W)
for _ in range(runs):
out = matrix_mechanism(W, A, x, epsilon, rng)
sq += sum((o - t) ** 2 for o, t in zip(out, true))
mean = [m + o / runs for m, o in zip(mean, out)]
assert abs(sq / runs - want) <= 0.15 * want
# Unbiased: each mean is within 6 standard errors of the true answer.
assert all(abs(m - t) <= 6 * math.sqrt(want / runs) for m, t in zip(mean, true))
def test_laplace_tail_check_value() -> None:
rng = random.Random(6)
zs = [laplace_noise(2.0, rng) for _ in range(2000)]
frac = sum(1 for z in zs if abs(z) > 2 * math.log(10)) / len(zs)
assert abs(frac - 0.1) <= dpkit.hoeffding_margin(len(zs), 1e-6)
def test_bad_parameters() -> None:
rng = random.Random(7)
try:
matrix_mechanism(identity(2), identity(2), [1, 1], 0.0, rng)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
try:
hierarchical_strategy(6)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
In 2010 two groups gave strategies for range queries that beat noise on each cell: Hay, Rastogi, Miklau and Suciu with a hierarchy of intervals and a least squares step, and Xiao, Wang and Gehrke with wavelets. Li, Hay, Rastogi, Miklau and McGregor (PODS 2010) showed that both are instances of one mechanism, gave its error formula, and studied the search for the best strategy. The journal version appeared in The VLDB Journal in 2015. HDMM (2018) made the strategy search practical for data with many attributes.
References
- Chao Li, Michael Hay, Vibhor Rastogi, Gerome Miklau and Andrew McGregor, Optimizing linear counting queries under differential privacy, PODS 2010, the definition of the matrix mechanism, its error formula, and the search for good strategies
- Chao Li, Gerome Miklau, Michael Hay, Andrew McGregor and Vibhor Rastogi, The matrix mechanism, optimizing linear counting queries under differential privacy, The VLDB Journal, 2015, the journal version, with the (epsilon, delta) form
- Michael Hay, Vibhor Rastogi, Gerome Miklau and Dan Suciu, Boosting the accuracy of differentially private histograms through consistency, PVLDB 3(1), 2010, the hierarchical strategy for range queries and the least squares step
- Xiaokui Xiao, Guozhang Wang and Johannes Gehrke, Differential privacy via wavelet transforms, ICDE 2010, the wavelet strategy for range queries
- Ryan McKenna, Gerome Miklau, Michael Hay and Ashwin Machanavajjhala, Optimizing error of high-dimensional statistical queries under differential privacy, PVLDB 2018, HDMM, the search for strategies over data with many attributes
- Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point Laplace noise and the snapping defense
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 73DA32 Edit this page History Report an error Markdown