Algorithm Search⌘K

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
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 TT 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 ε\varepsilon-differentially private, and its error grows with log⁡∣Q∣\log |Q| and log⁡∣D∣\log |D|, 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 BB over a finite domain DD of size NN, with nn records. The number nn is public. A counting query is a vector q∈{0,1}Dq \in \{0, 1\}^D, and its answer on a histogram HH is q(H)=∑xq(x)H(x)q(H) = \sum_x q(x) H(x). Given a set QQ of queries, the goal is a synthetic histogram Aˉ\bar A with total nn that makes max⁡q∈Q∣q(Aˉ)−q(B)∣\max_{q \in Q} |q(\bar A) - q(B)| small, under ε\varepsilon-DP. Two datasets are neighbors if one record is replaced by another (replace, so nn stays the same); then each q(B)q(B) moves by at most 1. Hardt, Ligett and McSherry use add/remove neighbors and treat nn as known.

Lap(b)\mathrm{Lap}(b) is the Laplace distribution with density 12be−∣z∣/b\frac{1}{2b} e^{-|z|/b}. It has variance 2b22b^2, and P(∣Z∣>t)=e−t/bP(|Z| > t) = e^{-t/b}.

The algorithm

  1. MWEM(B, Q, T, ε)
  2. 1A₀ ← the uniform histogram over D with total n
  3. 2for i ← 1 to T do
  4. 3pick qᵢ ∈ Q with probability ∝ exp(ε |q(Aᵢ₋₁) − q(B)| / (4T)) ▷ exponential mechanism, ε/(2T)
  5. 4mᵢ ← qᵢ(B) + Lap(2T/ε) ▷ Laplace mechanism, ε/(2T)
  6. 5Aᵢ(x) ∝ Aᵢ₋₁(x) · exp(qᵢ(x) (mᵢ − qᵢ(Aᵢ₋₁)) / (2n)), scaled to total n
  7. 6output Ā ← (1/T) Σ_{i=0}^{T−1} Aᵢ

Line L3 is the exponential mechanism with budget ε/(2T)\varepsilon/(2T) and score ∣q(Ai−1)−q(B)∣|q(A_{i-1}) - q(B)|, which has sensitivity 1. Line L4 spends the other ε/(2T)\varepsilon/(2T) of the round on one noisy count. Line L5 raises the weight of each cell in qiq_i 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 ATA_T in place of the average; both are post-processing of the same run.

Example

Take the domain of 8 cells, the data B=(500,1200,3000,2600,1500,800,300,100)B = (500, 1200, 3000, 2600, 1500, 800, 300, 100) with n=10000n = 10000, the 36 range queries over the cells, ε=1\varepsilon = 1 and T=5T = 5. Each round spends 0.10.1 on the selection and 0.10.1 on the measurement, so the measurement noise is Lap(10)\mathrm{Lap}(10). 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 ii worst error of Ai−1A_{i-1} chosen range qi(Ai−1)q_i(A_{i-1}) qi(B)q_i(B) mim_i AiA_i
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 η=(mi−qi(Ai−1))/(2n)\eta = (m_i - q_i(A_{i-1}))/(2n) is at most about 0.170.17 here. The worst error of the average Aˉ\bar A is 2697 and that of the last histogram A5A_5 is 2004. More rounds help on this data (a measurement from the same code): with T=10,20,40T = 10, 20, 40 the worst error of ATA_T is 1332, 741 and 455, and that of the average is 2189, 1579 and 1085. Theorem 2.2 gives the bound 13077 for T=5T = 5, which is larger than nn. 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 ε/(2T)\varepsilon/(2T)-DP given the earlier ones: the selection in line L3, whose score has sensitivity 1 because Ai−1A_{i-1} depends only on earlier releases, and the noisy count in line L4. By adaptive sequential composition the 2T2T releases are ε\varepsilon-DP, and line L6 is post-processing.

Accuracy (Hardt-Ligett-McSherry Theorem 2.2, a theorem). With probability at least 1−2T/∣Q∣1 - 2T/|Q|,

max⁡q∈Q∣q(Aˉ)−q(B)∣≤2nln⁡NT+10 Tln⁡∣Q∣ε.\max_{q \in Q} |q(\bar A) - q(B)| \le 2n\sqrt{\frac{\ln N}{T}} + \frac{10\, T \ln |Q|}{\varepsilon}.

The invariant is a potential: the relative entropy Ψi\Psi_i from B/nB/n to Ai/nA_i/n. It starts at most ln⁡N\ln N and stays at least 0. Each update lowers it by at least ((qi(Ai−1)−qi(B))2−νi2)/(4n2)((q_i(A_{i-1}) - q_i(B))^2 - \nu_i^2)/(4n^2), where νi\nu_i 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 TT to balance the two terms gives the error O(n2/3(log⁡Nlog⁡∣Q∣/ε)1/3)O(n^{2/3} (\log N \log |Q| / \varepsilon)^{1/3}) (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 DD has NN elements. The data is a histogram BB over DD with n=∑xB(x)≥1n = \sum_x B(x) \ge 1 records, and nn is public. A query is a vector q∈{0,1}Dq \in \{0,1\}^D, with q(H)=∑xq(x)H(x)q(H) = \sum_x q(x) H(x) for any histogram HH. Two datasets are neighbors if one record is replaced by another, so nn is the same and ∣q(B)−q(B′)∣≤1|q(B) - q(B')| \le 1 for every query. The proof also works for q∈[−1,1]Dq \in [-1, 1]^D, 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 ε\varepsilon-DP.

Proof. Let ε0=ε/(2T)\varepsilon_0 = \varepsilon/(2T). Round ii makes two releases: the index of qiq_i (line L3) and the value mim_i (line L4). The histogram Ai−1A_{i-1} is a fixed function of the earlier releases q1,m1,…,qi−1,mi−1q_1, m_1, \ldots, q_{i-1}, m_{i-1} and of the public nn, not of BB.

Line L3. Given Ai−1A_{i-1}, the score s(B,q)=∣q(Ai−1)−q(B)∣s(B, q) = |q(A_{i-1}) - q(B)| moves by at most 1 between neighbors, by the triangle inequality. The selection has P(q)=eε0s(B,q)/2/Z(B)P(q) = e^{\varepsilon_0 s(B,q)/2} / Z(B) with Z(B)=∑r∈Qeε0s(B,r)/2Z(B) = \sum_{r \in Q} e^{\varepsilon_0 s(B,r)/2}. For neighbors, eε0s(B,q)/2≤eε0/2eε0s(B′,q)/2e^{\varepsilon_0 s(B,q)/2} \le e^{\varepsilon_0/2} e^{\varepsilon_0 s(B',q)/2} and Z(B′)≤eε0/2Z(B)Z(B') \le e^{\varepsilon_0/2} Z(B), so PB(q)≤eε0PB′(q)P_B(q) \le e^{\varepsilon_0} P_{B'}(q).

Line L4. Given qiq_i, the value qi(B)+Lap(1/ε0)q_i(B) + \mathrm{Lap}(1/\varepsilon_0) is the Laplace mechanism for a function of sensitivity 1, so it is ε0\varepsilon_0-DP.

The 2T2T releases are each ε0\varepsilon_0-DP given the earlier ones. By adaptive basic composition the sequence of all releases is 2Tε0=ε2T\varepsilon_0 = \varepsilon-DP. The output of line L6 is a function of the releases and nn, so it is ε\varepsilon-DP by post-processing. □\square

Lemma (one update). Let a=A/na = A/n and b=B/nb = B/n be the normalized histograms, Ψ(A)=∑xb(x)ln⁡(b(x)/a(x))\Psi(A) = \sum_x b(x) \ln(b(x)/a(x)) the relative entropy, u=q(A)u = q(A), v=q(B)v = q(B), and A′A' the update of line L5 with the measurement mm. If ∣m−u∣≤2n|m - u| \le 2n, then

Ψ(A)−Ψ(A′)≥(u−v)2−(m−v)24n2.\Psi(A) - \Psi(A') \ge \frac{(u - v)^2 - (m - v)^2}{4n^2}.

Proof. Let η=(m−u)/(2n)\eta = (m - u)/(2n), so ∣η∣≤1|\eta| \le 1, and Z=∑xa(x)eηq(x)Z = \sum_x a(x) e^{\eta q(x)}. Line L5 sets a′(x)=a(x)eηq(x)/Za'(x) = a(x) e^{\eta q(x)}/Z. Then

Ψ(A)−Ψ(A′)=∑xb(x)ln⁡a′(x)a(x)=η∑xb(x)q(x)−ln⁡Z=ηvn−ln⁡Z.\Psi(A) - \Psi(A') = \sum_x b(x) \ln\frac{a'(x)}{a(x)} = \eta \sum_x b(x) q(x) - \ln Z = \frac{\eta v}{n} - \ln Z.

For ∣y∣≤1|y| \le 1, ey≤1+y+y2e^y \le 1 + y + y^2. With y=ηq(x)y = \eta q(x) and q(x)2≤1q(x)^2 \le 1, Z≤1+ηu/n+η2Z \le 1 + \eta u/n + \eta^2, and ln⁡Z≤ηu/n+η2\ln Z \le \eta u/n + \eta^2 because ln⁡(1+w)≤w\ln(1+w) \le w. So the drop is at least η(v−u)/n−η2\eta(v - u)/n - \eta^2. Put m−u=(v−u)+νm - u = (v - u) + \nu with ν=m−v\nu = m - v:

(m−u)(v−u)2n2−(m−u)24n2=2(v−u)2+2ν(v−u)−(v−u)2−2ν(v−u)−ν24n2=(v−u)2−ν24n2.□\frac{(m-u)(v-u)}{2n^2} - \frac{(m-u)^2}{4n^2} = \frac{2(v-u)^2 + 2\nu(v-u) - (v-u)^2 - 2\nu(v-u) - \nu^2}{4n^2} = \frac{(v-u)^2 - \nu^2}{4n^2}. \qquad \square

Claim 2 (accuracy). Let Aˉ=1T∑i=0T−1Ai\bar A = \frac{1}{T}\sum_{i=0}^{T-1} A_i be the output of line L6, β∈(0,1)\beta \in (0,1), and

γ=4Tεln⁡2T∣Q∣β,λ=2Tεln⁡2Tβ.\gamma = \frac{4T}{\varepsilon} \ln\frac{2T|Q|}{\beta}, \qquad \lambda = \frac{2T}{\varepsilon} \ln\frac{2T}{\beta}.

If λ≤n\lambda \le n, then with probability at least 1−β1 - \beta,

max⁡q∈Q∣q(Aˉ)−q(B)∣≤2nln⁡NT+λ+γ.\max_{q \in Q} |q(\bar A) - q(B)| \le 2n\sqrt{\frac{\ln N}{T}} + \lambda + \gamma.

Proof. Write ui=qi(Ai−1)u_i = q_i(A_{i-1}), vi=qi(B)v_i = q_i(B), νi=mi−vi\nu_i = m_i - v_i, and err(H)=max⁡q∣q(H)−q(B)∣\mathrm{err}(H) = \max_q |q(H) - q(B)|.

Good event. (a) For a Laplace draw, P(∣νi∣>λ)=e−λε/(2T)=β/(2T)P(|\nu_i| > \lambda) = e^{-\lambda\varepsilon/(2T)} = \beta/(2T). (b) For the exponential mechanism with ε0\varepsilon_0 and scores of sensitivity 1, the chosen score is below max⁡qs(B,q)−(2/ε0)ln⁡(∣Q∣/p)\max_q s(B,q) - (2/\varepsilon_0)\ln(|Q|/p) with probability at most pp: each such qq has probability at most e−ln⁡(∣Q∣/p)e^{-\ln(|Q|/p)} times that of the best one, and there are at most ∣Q∣|Q| of them. With p=β/(2T)p = \beta/(2T) and 2/ε0=4T/ε2/\varepsilon_0 = 4T/\varepsilon, this is the event ∣ui−vi∣<err(Ai−1)−γ|u_i - v_i| < \mathrm{err}(A_{i-1}) - \gamma. By the union bound over the 2T2T events, with probability at least 1−β1 - \beta, for all ii: ∣νi∣≤λ|\nu_i| \le \lambda and ∣ui−vi∣≥err(Ai−1)−γ|u_i - v_i| \ge \mathrm{err}(A_{i-1}) - \gamma.

Potential. On this event ∣mi−ui∣≤∣vi−ui∣+∣νi∣≤n+n|m_i - u_i| \le |v_i - u_i| + |\nu_i| \le n + n, so the lemma applies in every round. Ψ(A0)=ln⁡N−H(b)≤ln⁡N\Psi(A_0) = \ln N - H(b) \le \ln N and Ψ(AT)≥0\Psi(A_T) \ge 0. Summing the lemma over the TT rounds,

∑i=1T((ui−vi)2−νi2)≤4n2ln⁡N,so1T∑i=1T(ui−vi)2≤4n2ln⁡NT+λ2.\sum_{i=1}^{T} \big((u_i - v_i)^2 - \nu_i^2\big) \le 4n^2 \ln N, \quad\text{so}\quad \frac{1}{T}\sum_{i=1}^{T} (u_i - v_i)^2 \le \frac{4n^2 \ln N}{T} + \lambda^2.

Average. q(Aˉ)−q(B)q(\bar A) - q(B) is the mean of q(Ai−1)−q(B)q(A_{i-1}) - q(B) over ii, so err(Aˉ)≤1T∑ierr(Ai−1)≤1T∑i∣ui−vi∣+γ\mathrm{err}(\bar A) \le \frac{1}{T}\sum_i \mathrm{err}(A_{i-1}) \le \frac{1}{T}\sum_i |u_i - v_i| + \gamma. By the Cauchy-Schwarz inequality and s+t≤s+t\sqrt{s + t} \le \sqrt{s} + \sqrt{t},

1T∑i∣ui−vi∣≤1T∑i(ui−vi)2≤2nln⁡NT+λ.□\frac{1}{T}\sum_i |u_i - v_i| \le \sqrt{\frac{1}{T}\sum_i (u_i - v_i)^2} \le 2n\sqrt{\frac{\ln N}{T}} + \lambda. \qquad \square

With β=2T/∣Q∣\beta = 2T/|Q| (which needs ∣Q∣>2T|Q| > 2T), γ=(8T/ε)ln⁡∣Q∣\gamma = (8T/\varepsilon)\ln|Q| and λ=(2T/ε)ln⁡∣Q∣\lambda = (2T/\varepsilon)\ln|Q|, so the bound is 2nln⁡N/T+10Tln⁡∣Q∣/ε2n\sqrt{\ln N/T} + 10T\ln|Q|/\varepsilon with probability at least 1−2T/∣Q∣1 - 2T/|Q|. This is Theorem 2.2 of Hardt, Ligett and McSherry. Our condition λ≤n\lambda \le n is mild: if it fails, the bound exceeds nn and holds anyway for counting queries with values in [0,n][0, n].

Cost. Line L1 costs O(N)O(N). Each round evaluates all ∣Q∣|Q| queries on Ai−1A_{i-1} in O(∣Q∣N)O(|Q|N), samples in O(∣Q∣)O(|Q|), and updates in O(N)O(N). The true answers q(B)q(B) are computed one time in O(∣Q∣N)O(|Q|N). So TT rounds cost O(T∣Q∣N)O(T|Q|N), and the extra space is O(N+∣Q∣)O(N + |Q|).

Complexity

In the real-RAM model, with one Laplace draw and one exponential at unit cost:

  • Each round evaluates all ∣Q∣|Q| queries on Ai−1A_{i-1} in O(∣Q∣N)O(|Q| N) time, samples in O(∣Q∣)O(|Q|), and updates in O(N)O(N).
  • TT rounds cost O(T∣Q∣N)O(T |Q| N), and the extra space is O(N+∣Q∣)O(N + |Q|).

The paper states the time as O(n∣Q∣+T∣D∣∣Q∣)O(n|Q| + T|D||Q|), with O(n∣Q∣)O(n|Q|) for the true answers from the records. The cost is linear in the domain size N=∣D∣N = |D|, 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 QQ, and its answers are consistent.
  • Pure DP. The run is (ε,0)(\varepsilon, 0)-DP. With advanced composition it is (ε′,δ)(\varepsilon', \delta)-DP with a different choice of TT.
  • 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 ε\varepsilon.

Variants and improvements

  • Last iterate. Output ATA_T 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 (qj,mj)(q_j, m_j). 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 DD by a model with fewer parameters, so that the cost is no longer linear in NN.

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 ε/(2T)\varepsilon/(2T) in the form exp⁡(ε0s/2)\exp(\varepsilon_0 s/2), here exp⁡(εs/(4T))\exp(\varepsilon s/(4T)), because the score has sensitivity 1. Using exp⁡(εs/(2T))\exp(\varepsilon s/(2T)) spends twice the budget in each selection. For queries with values in [−1,1][-1, 1] under replace neighbors, the sensitivity is 2 and the exponent must be halved again.
  • Noise of the wrong scale. Line L4 must use Lap(2T/ε)\mathrm{Lap}(2T/\varepsilon), not Lap(1/ε)\mathrm{Lap}(1/\varepsilon). Each of the TT measurements spends ε/(2T)\varepsilon/(2T).
  • Private nn. Line L5 divides by nn. If nn is private, as under add/remove neighbors, the update reads private data outside the budget. Treat nn as public, or spend part of the budget on a noisy nn.
  • 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 TT makes each measurement very noisy. The bound shows the trade-off: the first term falls as 1/T1/\sqrt{T} and the second grows as TT.
  • 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.

dpkit.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example