Algorithmadvanced
Multiplicative weights exponential mechanism
Also called MWEM.
Keeps a synthetic histogram, picks a badly answered query with the exponential mechanism, measures it with Laplace noise and corrects the histogram by multiplicative weights.
- Time
- O(T |Q| N) worst
- Space
- O(N + |Q|) extra
- Where
- N = the size of the data domain; Q = the query set; T = the number of rounds
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Moritz Hardt, Katrina Ligett, Frank McSherry, 2012
MWEM builds a private synthetic histogram that answers a set of counting queries. It starts from the uniform histogram and runs rounds. In each round it uses the exponential mechanism to pick a query on which the synthetic data is far from the real data, measures that one query with the Laplace mechanism, and moves the synthetic histogram toward the measurement by a multiplicative weights step. The result is -differentially private, and its error grows with and , not with the number of queries. It is the practical form of the multiplicative weights approach to private query release.
In plain words
You want a fake table of counts that gives nearly the same answers as the real table, for many questions at once. You start with a flat fake table. Then you repeat a few times: find a question where the fake table is badly wrong, ask the real table that one question with noise, and fix the fake table so that it agrees better with the noisy answer. The fix raises the counts that the question covers if the fake answer is too low, and lowers them if it is too high.
The search for a bad question and the noisy answer each use a small part of the privacy budget. Only a few questions are asked, so each can have little noise. All other questions are answered by the fake table for free.
The problem
The data is a histogram over a finite domain of size , with records. The number is public. A counting query is a vector , and its answer on a histogram is . Given a set of queries, the goal is a synthetic histogram with total that makes small, under -DP. Two datasets are neighbors if one record is replaced by another (replace, so stays the same); then each moves by at most 1. Hardt, Ligett and McSherry use add/remove neighbors and treat as known.
is the Laplace distribution with density . It has variance , and .
The algorithm
MWEM(B, Q, T, ε)- 1
A₀ ← the uniform histogram over D with total n - 2
for i ← 1 to T do - 3
pick qᵢ ∈ Q with probability ∝ exp(ε |q(Aᵢ₋₁) − q(B)| / (4T)) ▷ exponential mechanism, ε/(2T) - 4
mᵢ ← qᵢ(B) + Lap(2T/ε) ▷ Laplace mechanism, ε/(2T) - 5
Aᵢ(x) ∝ Aᵢ₋₁(x) · exp(qᵢ(x) (mᵢ − qᵢ(Aᵢ₋₁)) / (2n)), scaled to total n - 6
output Ā ← (1/T) Σ_{i=0}^{T−1} Aᵢ
Line L3 is the exponential mechanism with budget and score , which has sensitivity 1. Line L4 spends the other of the round on one noisy count. Line L5 raises the weight of each cell in if the measurement is above the synthetic answer, and lowers it if it is below. Line L6 averages the histograms that the rounds start from, as in Figure 1 of the paper. In their experiments the authors output the last histogram in place of the average; both are post-processing of the same run.
Example
Take the domain of 8 cells, the data with , the 36 range queries over the cells, and . Each round spends on the selection and on the measurement, so the measurement noise is . The uniform start puts 1250 in each cell, and its worst range error is 3350. The run of the code with random.Random(1), rounded:
| round | worst error of | chosen range | ||||
|---|---|---|---|---|---|---|
| 1 | 3350 | cells 3 to 5 | 3750 | 7100 | 7111.9 | (1170, 1170, 1384, 1384, 1384, 1170, 1170, 1170) |
| 2 | 2979 | cells 2 to 5 | 5321 | 8300 | 8293.3 | (1078, 1251, 1479, 1479, 1479, 1078, 1078, 1078) |
| 3 | 2662 | cells 3 to 5 | 4438 | 7100 | 7098.9 | (1014, 1176, 1590, 1590, 1590, 1014, 1014, 1014) |
| 4 | 2445 | cells 2 to 4 | 4355 | 6800 | 6808.6 | (959, 1258, 1700, 1700, 1504, 959, 959, 959) |
| 5 | 2199 | cells 3 to 4 | 3401 | 5600 | 5571.3 | (923, 1211, 1824, 1824, 1448, 923, 923, 923) |
In each round the chosen range is the worst one: here the exponential mechanism put between 0.52 and 0.92 of its mass on it. The step in line L5 is small, because is at most about here. The worst error of the average is 2697 and that of the last histogram is 2004. More rounds help on this data (a measurement from the same code): with the worst error of is 1332, 741 and 455, and that of the average is 2189, 1579 and 1085. Theorem 2.2 gives the bound 13077 for , which is larger than . The bound is for the worst case, and MWEM does much better on this data.
Correctness
Privacy (Hardt-Ligett-McSherry Theorem 2.1, a theorem). Each round makes two releases, each -DP given the earlier ones: the selection in line L3, whose score has sensitivity 1 because depends only on earlier releases, and the noisy count in line L4. By adaptive sequential composition the releases are -DP, and line L6 is post-processing.
Accuracy (Hardt-Ligett-McSherry Theorem 2.2, a theorem). With probability at least ,
The invariant is a potential: the relative entropy from to . It starts at most and stays at least 0. Each update lowers it by at least , where is the noise of line L4. So the errors of the chosen queries are small on average, and the exponential mechanism makes the chosen errors close to the worst errors. The full proofs are in proofs/correctness.md. Choosing to balance the two terms gives the error (Corollary 2.1).
Proof: MWEM is epsilon-DP, and its average has error 2n sqrt(ln N / T) + 10 T ln|Q| / epsilonfull
We use the pseudocode of the page. The domain has elements. The data is a histogram over with records, and is public. A query is a vector , with for any histogram . Two datasets are neighbors if one record is replaced by another, so is the same and for every query. The proof also works for , as in Hardt, Ligett and McSherry, with sensitivity 2 in place of 1 under replace.
Claim 1 (privacy). The run, and so the output, is -DP.
Proof. Let . Round makes two releases: the index of (line L3) and the value (line L4). The histogram is a fixed function of the earlier releases and of the public , not of .
Line L3. Given , the score moves by at most 1 between neighbors, by the triangle inequality. The selection has with . For neighbors, and , so .
Line L4. Given , the value is the Laplace mechanism for a function of sensitivity 1, so it is -DP.
The releases are each -DP given the earlier ones. By adaptive basic composition the sequence of all releases is -DP. The output of line L6 is a function of the releases and , so it is -DP by post-processing.
Lemma (one update). Let and be the normalized histograms, the relative entropy, , , and the update of line L5 with the measurement . If , then
Proof. Let , so , and . Line L5 sets . Then
For , . With and , , and because . So the drop is at least . Put with :
Claim 2 (accuracy). Let be the output of line L6, , and
If , then with probability at least ,
Proof. Write , , , and .
Good event. (a) For a Laplace draw, . (b) For the exponential mechanism with and scores of sensitivity 1, the chosen score is below with probability at most : each such has probability at most times that of the best one, and there are at most of them. With and , this is the event . By the union bound over the events, with probability at least , for all : and .
Potential. On this event , so the lemma applies in every round. and . Summing the lemma over the rounds,
Average. is the mean of over , so . By the Cauchy-Schwarz inequality and ,
With (which needs ), and , so the bound is with probability at least . This is Theorem 2.2 of Hardt, Ligett and McSherry. Our condition is mild: if it fails, the bound exceeds and holds anyway for counting queries with values in .
Cost. Line L1 costs . Each round evaluates all queries on in , samples in , and updates in . The true answers are computed one time in . So rounds cost , and the extra space is .
Complexity
In the real-RAM model, with one Laplace draw and one exponential at unit cost:
- Each round evaluates all queries on in time, samples in , and updates in .
- rounds cost , and the extra space is .
The paper states the time as , with for the true answers from the records. The cost is linear in the domain size , which is exponential in the number of attributes. This is the main limit of MWEM. Ullman and Vadhan show that some limit of this kind is needed for efficient private synthetic data, under hardness assumptions.
Properties
- Synthetic data. The output is a histogram, so it answers any query, also queries outside , and its answers are consistent.
- Pure DP. The run is -DP. With advanced composition it is -DP with a different choice of .
- Data dependent error. The error depends on the data. The bound of Theorem 2.2 is for the worst case, and on structured data the error is often much smaller.
- Randomized. The selection and the measurement are random, so two runs give different outputs, and each run costs .
Variants and improvements
- Last iterate. Output in place of the average. The authors use this in all their experiments (Section 2.3.3).
- Reuse of measurements. After each new measurement, apply the update of line L5 again for all earlier pairs . This uses no new privacy budget, because it only reads the releases, and it speeds up the fit a lot.
- Better start. Start from a noisy histogram of the frequent cells in place of the uniform one, at some cost in budget.
- Online form. Private multiplicative weights (Hardt and Rothblum 2010) answers queries as they come, and uses the sparse vector technique to find the queries on which the synthetic data is wrong.
- Larger domains. Later methods replace the explicit histogram over by a model with fewer parameters, so that the cost is no longer linear in .
When to use it
Use MWEM when you must release synthetic data or answer a large fixed set of counting queries, such as range queries or low-order marginals, and the domain is small enough to store a weight for each cell. It is easy to implement and it adapts to the data. For a small set of linear queries with a known structure, the matrix mechanism has a data independent error that you can compute in advance. For a very large domain, MWEM as written is too slow.
Pitfalls
- Score with the wrong sensitivity. Line L3 must use the budget in the form , here , because the score has sensitivity 1. Using spends twice the budget in each selection. For queries with values in under replace neighbors, the sensitivity is 2 and the exponent must be halved again.
- Noise of the wrong scale. Line L4 must use , not . Each of the measurements spends .
- Private . Line L5 divides by . If is private, as under add/remove neighbors, the update reads private data outside the budget. Treat as public, or spend part of the budget on a noisy .
- Selection that reads the true answers without noise. The search for the worst query must go through line L3. Picking the exact worst query, as non-private multiplicative weights does, is not private.
- Too many rounds. A large makes each measurement very noisy. The bound shows the trade-off: the first term falls as and the second grows as .
- Float noise. The code uses float 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
mwem.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mwem/. The authors are listed in prov/R361Z0.jsonl.
"""MWEM, the multiplicative weights exponential mechanism (Hardt, Ligett and
McSherry 2012), for counting queries over a small finite domain.
The data is a histogram B over a domain D of size N: B[x] is the number of
records equal to x, and n = sum(B) is public. A counting query is a 0-1
vector q over D, and q(B) = sum_x q[x] B[x]. Neighbors replace one record
by another, so n stays fixed and each q(B) moves by at most 1.
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 exact
sampling (Mironov 2012; Canonne, Kamath and Steinke 2020).
"""
from __future__ import annotations
import math
import random
from typing import Sequence
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 evaluate(q: Sequence[int], hist: Sequence[float]) -> float:
"""The answer q(hist) = sum_x q[x] hist[x]. Cost: O(N)."""
return sum(w * h for w, h in zip(q, hist))
def exponential_mechanism_pmf(scores: Sequence[float], epsilon0: float) -> list[float]:
"""The exponential mechanism for scores of sensitivity 1: P(r) is proportional to exp(epsilon0 * score_r / 2).
Precondition: at least one score, epsilon0 > 0. Cost: O(len(scores)).
"""
top = max(scores)
w = [math.exp(epsilon0 * (s - top) / 2.0) for s in scores]
z = sum(w)
return [v / z for v in w]
def sample_index(pmf: Sequence[float], rng: random.Random) -> int:
"""Draw an index from a pmf with one uniform draw by the inverse CDF. Cost: O(len(pmf))."""
u = rng.random()
acc = 0.0
for i, p in enumerate(pmf):
acc += p
if u < acc:
return i
return len(pmf) - 1
def mw_update(A: Sequence[float], q: Sequence[int], m: float, n: float) -> list[float]:
"""One multiplicative weights step: A(x) times exp(q[x] (m - q(A)) / (2n)), scaled back to total n.
Precondition: A has total n > 0 and positive entries. Cost: O(N).
"""
eta = (m - evaluate(q, A)) / (2.0 * n)
logs = [math.log(a) + eta * w for a, w in zip(A, q)]
top = max(logs)
w = [math.exp(v - top) for v in logs]
z = sum(w)
return [n * v / z for v in w]
def mwem(
B: Sequence[int],
queries: Sequence[Sequence[int]],
T: int,
epsilon: float,
rng: random.Random,
return_last: bool = False,
) -> list[float]:
"""Run MWEM for T rounds and return a synthetic histogram.
By default the output is the average of A_0, ..., A_{T-1}, the histograms
that the T rounds start from, as in Figure 1 of Hardt, Ligett and
McSherry; their error theorem is for this average. With return_last the
output is A_T, which they use in their experiments. Both are
post-processing of the same run. Each round spends epsilon/(2T) on the
selection and epsilon/(2T) on the measurement, so the run is epsilon-DP
for replace neighbors.
Precondition: T >= 1, epsilon > 0, n = sum(B) >= 1, at least one query.
Cost: O(T |Q| N) time and O(N + |Q|) extra space.
"""
if T < 1 or epsilon <= 0:
raise ValueError("need T >= 1 and epsilon > 0")
if not queries:
raise ValueError("need at least one query")
n = float(sum(B))
if n <= 0:
raise ValueError("the dataset must not be empty")
N = len(B)
true = [evaluate(q, B) for q in queries]
A = [n / N] * N # @line L1
total = [0.0] * N
for _ in range(T): # @line L2
total = [s + a for s, a in zip(total, A)]
scores = [abs(evaluate(q, A) - t) for q, t in zip(queries, true)]
i = sample_index(exponential_mechanism_pmf(scores, epsilon / (2.0 * T)), rng) # @line L3
m = true[i] + laplace_noise(2.0 * T / epsilon, rng) # @line L4
A = mw_update(A, queries[i], m, n) # @line L5
if return_last:
return A
return [s / T for s in total] # @line L6
def max_error(B: Sequence[int], A: Sequence[float], queries: Sequence[Sequence[int]]) -> float:
"""The largest error max_q |q(A) - q(B)| over the queries. Cost: O(|Q| N)."""
return max(abs(evaluate(q, A) - evaluate(q, B)) for q in queries)
test_mwem.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mwem/. The authors are listed in prov/R361Z0.jsonl.
import itertools
import math
import random
import dpkit
from mwem import (
evaluate,
exponential_mechanism_pmf,
laplace_noise,
max_error,
mw_update,
mwem,
sample_index,
)
DOMAIN = (0, 1, 2)
def _hist(records, N=len(DOMAIN)):
h = [0] * N
for r in records:
h[r] += 1
return h
def _all_subset_queries(N):
return [[1 if (mask >> x) & 1 else 0 for x in range(N)] for mask in range(1, 2 ** N)]
def _kl(p, q):
return sum(a * math.log(a / b) for a, b in zip(p, q) if a > 0)
def test_selection_step_is_epsilon0_dp_on_all_replace_pairs() -> None:
queries = _all_subset_queries(3)
A = [4 / 3] * 3 # the synthetic data does not depend on the private data in round 1
eps0 = 0.8
def mech_pmf(records):
B = _hist(records)
scores = [abs(evaluate(q, A) - evaluate(q, B)) for q in queries]
return dict(enumerate(exponential_mechanism_pmf(scores, eps0)))
datasets = list(itertools.combinations_with_replacement(DOMAIN, 4))
pairs = [(x, y) for x in datasets for y in dpkit.neighbors_replace(x, DOMAIN)]
assert len(pairs) > 40
assert dpkit.is_pure_dp(mech_pmf, pairs, eps0)
worst = max(dpkit.max_privacy_loss(mech_pmf(x), mech_pmf(y)) for x, y in pairs)
assert 0.2 < worst <= eps0 + 1e-12
def test_exponential_mechanism_pmf_against_direct_formula() -> None:
rng = random.Random(1)
for _ in range(500):
scores = [rng.uniform(0, 20) for _ in range(rng.randrange(1, 8))]
eps0 = rng.uniform(0.01, 3)
z = sum(math.exp(eps0 * s / 2) for s in scores)
want = [math.exp(eps0 * s / 2) / z for s in scores]
got = exponential_mechanism_pmf(scores, eps0)
assert all(math.isclose(a, b, rel_tol=1e-9) for a, b in zip(got, want))
def test_sampling_matches_pmf() -> None:
rng = random.Random(2)
pmf = exponential_mechanism_pmf([0.0, 1.0, 3.0, 2.0], 1.0)
n = 4000
emp = dpkit.empirical_pmf(sample_index(pmf, rng) for _ in range(n))
margin = dpkit.hoeffding_margin(n, 1e-6)
assert all(abs(emp.get(i, 0.0) - p) <= margin for i, p in enumerate(pmf))
def test_mw_update_matches_formula_and_keeps_total() -> None:
rng = random.Random(3)
for _ in range(500):
N = rng.randrange(1, 7)
A = [rng.uniform(0.1, 5) for _ in range(N)]
n = sum(A)
q = [rng.randrange(2) for _ in range(N)]
m = rng.uniform(-n, 2 * n)
got = mw_update(A, q, m, n)
qa = sum(w * a for w, a in zip(q, A))
raw = [a * math.exp(w * (m - qa) / (2 * n)) for a, w in zip(A, q)]
want = [n * r / sum(raw) for r in raw]
assert all(math.isclose(g, w, rel_tol=1e-9) for g, w in zip(got, want))
assert math.isclose(sum(got), n, rel_tol=1e-12)
def test_kl_drop_of_one_update() -> None:
# With b = B/n, a = A/n, u = q(A), v = q(B) and |m - u| <= 2n:
# KL(b||a) - KL(b||a') >= ((u - v)^2 - (m - v)^2) / (4 n^2), the lemma of the proof.
rng = random.Random(4)
for _ in range(500):
N = rng.randrange(2, 7)
B = [rng.randrange(0, 6) for _ in range(N)]
if sum(B) == 0:
B[0] = 1
n = sum(B)
A = [rng.uniform(0.1, 3) for _ in range(N)]
A = [n * a / sum(A) for a in A]
q = [rng.randrange(2) for _ in range(N)]
u, v = evaluate(q, A), evaluate(q, B)
for m in (v, v + rng.uniform(-n, n)):
m = max(u - 2 * n, min(u + 2 * n, m))
A2 = mw_update(A, q, m, n)
drop = _kl([b / n for b in B], [a / n for a in A]) - _kl([b / n for b in B], [a / n for a in A2])
bound = ((u - v) ** 2 - (m - v) ** 2) / (4 * n * n)
assert drop >= bound - 1e-12
def _oracle_mwem(B, queries, T, epsilon, rng):
"""An independent restatement in log space with explicit weights over the domain."""
n = sum(B)
N = len(B)
logw = [0.0] * N
avg = [0.0] * N
def synth():
top = max(logw)
e = [math.exp(v - top) for v in logw]
s = sum(e)
return [n * v / s for v in e]
for _ in range(T):
A = synth()
avg = [a + b / T for a, b in zip(avg, A)]
weights = [math.exp(epsilon / (4 * T) * abs(sum(q[x] * (A[x] - B[x]) for x in range(N)))) for q in queries]
u, acc, pick = rng.random() * sum(weights), 0.0, len(queries) - 1
for i, w in enumerate(weights):
acc += w
if u < acc:
pick = i
break
q = queries[pick]
m = sum(q[x] * B[x] for x in range(N)) + laplace_noise(2 * T / epsilon, rng)
qa = sum(q[x] * A[x] for x in range(N))
logw = [logw[x] + q[x] * (m - qa) / (2 * n) for x in range(N)]
return avg, synth()
def test_against_oracle_on_random_inputs() -> None:
gen = random.Random(5)
agree = 0
for trial in range(500):
N = gen.randrange(2, 6)
B = [gen.randrange(0, 8) for _ in range(N)]
B[gen.randrange(N)] += 1
queries = [[gen.randrange(2) for _ in range(N)] for _ in range(gen.randrange(1, 6))]
T = gen.randrange(1, 5)
epsilon = gen.choice([0.5, 1.0, 4.0])
got = mwem(B, queries, T, epsilon, random.Random(trial))
last = mwem(B, queries, T, epsilon, random.Random(trial), return_last=True)
want, want_last = _oracle_mwem(B, queries, T, epsilon, random.Random(trial))
# The two pick a query by the same uniform draw; a different pick can only come
# from a rounding tie at a boundary of the inverse CDF.
agree += all(math.isclose(a, b, rel_tol=1e-7, abs_tol=1e-9) for a, b in zip(got + last, want + want_last))
assert math.isclose(sum(got), sum(B), rel_tol=1e-9)
assert agree >= 498
def test_error_within_theorem_2_2() -> None:
rng = random.Random(6)
N = 16
queries = [[1 if i <= x <= j else 0 for x in range(N)] for i in range(N) for j in range(i, N)]
B = [rng.randrange(0, 4000) * (x % 3 == 0) for x in range(N)]
n = sum(B)
T, epsilon = 40, 1.0
bound = 2 * n * math.sqrt(math.log(N) / T) + 10 * T * math.log(len(queries)) / epsilon
start = max_error(B, [n / N] * N, queries)
errs = [max_error(B, mwem(B, queries, T, epsilon, rng), queries) for _ in range(5)]
assert all(e <= bound for e in errs)
assert max(errs) < start / 2 # and it is a real gain over the uniform start
def test_noise_free_limit_converges() -> None:
# With a huge epsilon, MWEM is plain multiplicative weights with exact
# measurements, and the averaged error is at most 2n sqrt(ln N / T).
rng = random.Random(7)
N = 8
queries = _all_subset_queries(N)
B = [rng.randrange(0, 50) for _ in range(N)]
n = sum(B)
for T in (10, 40, 160):
e = max_error(B, mwem(B, queries, T, 1e9, rng), queries)
assert e <= 2 * n * math.sqrt(math.log(N) / T)
def test_laplace_tail_check_value() -> None:
rng = random.Random(8)
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(9)
for args in [([1, 2], [[1, 0]], 0, 1.0), ([1, 2], [[1, 0]], 1, 0.0), ([0, 0], [[1, 0]], 1, 1.0), ([1], [], 1, 1.0)]:
try:
mwem(*args, rng)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
Blum, Ligett and Roth (2008) showed that a small synthetic database can answer exponentially many counting queries privately; see the SmallDB mechanism. Their method takes time exponential in the domain size. Hardt and Rothblum (FOCS 2010) gave private multiplicative weights, an online method with a relative entropy analysis and near optimal error. Hardt, Ligett and McSherry (NIPS 2012) gave MWEM, a simple offline form that combines the exponential mechanism, the Laplace mechanism and multiplicative weights, and showed that it works well on real data.
References
- Moritz Hardt, Katrina Ligett and Frank McSherry, A simple and practical algorithm for differentially private data release, NIPS 2012, Figure 1 (the algorithm), Theorem 2.1 (privacy), Theorem 2.2 (error), Corollary 2.1, Section 2.3.3 (improvements: output A_T and reuse past measurements)
- Moritz Hardt and Guy N. Rothblum, A multiplicative weights mechanism for privacy-preserving data analysis, FOCS 2010, pages 61 to 70, the private multiplicative weights mechanism and the relative entropy argument
- Cynthia Dwork and Aaron Roth, The Algorithmic Foundations of Differential Privacy, Foundations and Trends in Theoretical Computer Science 9(3-4), 2014, Section 4.2 (the online multiplicative weights mechanism)
- 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 R361Z0 Edit this page History Report an error Markdown