Algorithm Search⌘K

Algorithmadvanced

SmallDB mechanism

Also called BLR mechanism, Blum-Ligett-Roth mechanism.

Picks a small synthetic database with the exponential mechanism. It answers a huge set of counting queries, with an error that grows only with the log of their number.

Time
O(U^(m+1) |Q|) worst
Space
O(U^m) extra
Where
Q = the query set; U = the size of the data universe; m = the size of the small databases
Origin
Avrim Blum, Katrina Ligett, Aaron Roth, 2008

The SmallDB mechanism answers a large set QQ of counting queries by releasing a synthetic database of only m=⌈ln⁡∣Q∣/α2⌉m = \lceil \ln|Q|/\alpha^2 \rceil records. A random sample of that size already answers every query in QQ within α\alpha. So the mechanism lists all databases of mm records and picks one with the exponential mechanism, with a score that rewards small error. The output is ε\varepsilon-differentially private, and its error grows as (log⁡∣X∣log⁡∣Q∣/(εn))1/3(\log|X| \log|Q|/(\varepsilon n))^{1/3}: only with the log of the number of queries. The listing takes time exponential in mm, so SmallDB is a proof that such accuracy is possible, not a tool for large data. MWEM reaches similar error with a practical algorithm.

In plain words

You want to publish a fake table of records that gives almost the same answers as the real table, for a very long list of questions of the form "what fraction of the records have this property?".

A few random records from the real table would already give good answers to all the questions, because a random sample is close to the whole for each question, and the list of questions grows the sample size only slowly. But a real sample would leak real records. So SmallDB looks at every possible fake table of that small size and scores each one by its worst answer. It then picks one at random, with a strong preference for good scores. The randomness in the pick hides each person.

The problem

The universe XX is a finite set of UU possible records. The data is a histogram xx over XX with nn records, and nn is public. A counting query is a vector f∈{0,1}Xf \in \{0,1\}^X, and its normalized answer is f(x)=1n∑jfjxjf(x) = \frac{1}{n}\sum_j f_j x_j, the fraction of records it counts. Given a set QQ of queries, the goal is a synthetic database yy with max⁡f∈Q∣f(x)−f(y)∣\max_{f \in Q} |f(x) - f(y)| small, under ε\varepsilon-DP. Two datasets are neighbors if one record is replaced by another (replace), so each f(x)f(x) moves by at most 1/n1/n. Dwork and Roth use histograms with ∥x−x′∥1≤1\|x - x'\|_1 \le 1 and the same sensitivity 1/∥x∥11/\|x\|_1.

The algorithm

This is Algorithm 4 of Dwork and Roth.

  1. SMALLDB(x, Q, ε, α)
  2. 1m ← ⌈ln|Q| / α²⌉ ▷ the size of the small databases
  3. 2R ← all histograms y of m records over X
  4. 3for each y ∈ R: u(y) ← −max_{f ∈ Q} |f(x) − f(y)| ▷ the score, sensitivity 1/n
  5. 4output y ∈ R with probability ∝ exp(ε n u(y) / 2) ▷ the exponential mechanism

Line L1 sets the size from Proposition 4.1: a sample of mm records has error at most α\alpha on all of QQ. Line L2 lists the candidates, which do not depend on the data. Line L3 scores each by its worst error. Line L4 is the exponential mechanism exp⁡(εu/(2Δu))\exp(\varepsilon u/(2\Delta u)) with Δu=1/n\Delta u = 1/n. The output is a set of mm records, and it answers any counting query, not only those in QQ.

Example

Take the universe X={1,2,3,4}X = \{1, 2, 3, 4\}, the data x=(40,30,20,10)x = (40, 30, 20, 10) with n=100n = 100, all 15 non-empty subset queries, ε=1\varepsilon = 1 and α=0.5\alpha = 0.5. Line L1 gives m=⌈ln⁡15/0.25⌉=11m = \lceil \ln 15 / 0.25 \rceil = 11, and line L2 lists (143)=364\binom{14}{3} = 364 databases. The exact output distribution, from the code, puts most of its mass on a few of them:

small database yy worst error probability
(5, 3, 2, 1) 0.055 0.383
(4, 4, 2, 1) 0.064 0.243
(4, 3, 3, 1) 0.073 0.154
(4, 3, 2, 2) 0.082 0.098
(5, 4, 2, 0) 0.118 0.016

The best database (5,3,2,1)(5, 3, 2, 1) is the closest shape to (40,30,20,10)(40, 30, 20, 10) with 11 records. With probability 0.878 the output has worst error at most 0.1, and the mean worst error is 0.072. The run with random.Random(1) outputs (5,3,2,1)(5, 3, 2, 1). The guarantee of Claim 3 with β=0.1\beta = 0.1 is 0.5+2(ln⁡364+ln⁡10)/100=0.660.5 + 2(\ln 364 + \ln 10)/100 = 0.66, much weaker than the real error: the term α\alpha is a worst case over all data, and here a much better small database exists.

Correctness

Privacy (Dwork-Roth Theorem 4.2, a theorem). The score uu changes by at most 1/n1/n between neighbors, and RR does not depend on the data. So line L4 is the exponential mechanism with the right sensitivity, and it is ε\varepsilon-DP.

A small database exists (Dwork-Roth Proposition 4.1, a theorem). For ∣Q∣≥3|Q| \ge 3, draw m≥ln⁡∣Q∣/α2m \ge \ln|Q|/\alpha^2 records at random from xx. By the Hoeffding inequality, each query has error above α\alpha with probability at most 2e−2mα2≤2/∣Q∣22e^{-2m\alpha^2} \le 2/|Q|^2. By the union bound, all queries are within α\alpha with positive probability, so such a database exists in RR.

Accuracy (Dwork-Roth Theorem 4.5, a theorem). By the accuracy of the exponential mechanism, with probability at least 1−β1 - \beta the output has worst error at most α+2(ln⁡∣R∣+ln⁡(1/β))/(εn)\alpha + 2(\ln|R| + \ln(1/\beta))/(\varepsilon n), and ln⁡∣R∣≤mln⁡U\ln|R| \le m \ln U. Choosing α\alpha to balance the two terms gives the error

(16log⁡∣X∣log⁡∣Q∣+4log⁡(1/β)εn)1/3.\left(\frac{16 \log|X| \log|Q| + 4\log(1/\beta)}{\varepsilon n}\right)^{1/3}.

The full proofs are in proofs/correctness.md.

Proof: SmallDB is epsilon-DP, a small database with error alpha exists, and the output is accuratefull

We use the pseudocode of the page. The universe XX has UU elements, the data is a histogram xx over XX with n≥1n \ge 1 records, and nn is public. For a query f∈{0,1}Xf \in \{0,1\}^X and a histogram hh with ∥h∥1>0\|h\|_1 > 0, f(h)=∑jfjhj/∥h∥1f(h) = \sum_j f_j h_j / \|h\|_1 is the fraction of records that ff counts. Two datasets are neighbors if one record is replaced by another, so nn stays the same. RR is the set of histograms with exactly mm records, and u(x,y)=−max⁡f∈Q∣f(x)−f(y)∣u(x, y) = -\max_{f \in Q} |f(x) - f(y)|.

Claim 1 (privacy). The output of line L4 is ε\varepsilon-DP.

Proof. For neighbors x,x′x, x' and each ff, the count ∑jfjxj\sum_j f_j x_j moves by at most 1 and nn is fixed, so ∣f(x)−f(x′)∣≤1/n|f(x) - f(x')| \le 1/n. Then for each yy, ∣f(x)−f(y)∣|f(x) - f(y)| moves by at most 1/n1/n, and so does the maximum over ff: ∣u(x,y)−u(x′,y)∣≤1/n|u(x, y) - u(x', y)| \le 1/n. Line L4 picks yy with probability Px(y)=eεnu(x,y)/2/Z(x)P_x(y) = e^{\varepsilon n u(x,y)/2} / Z(x), with Z(x)=∑r∈Reεnu(x,r)/2Z(x) = \sum_{r \in R} e^{\varepsilon n u(x,r)/2}. So eεnu(x,y)/2≤eε/2eεnu(x′,y)/2e^{\varepsilon n u(x,y)/2} \le e^{\varepsilon/2} e^{\varepsilon n u(x',y)/2} and Z(x′)≤eε/2Z(x)Z(x') \le e^{\varepsilon/2} Z(x), which give Px(y)≤eεPx′(y)P_x(y) \le e^{\varepsilon} P_{x'}(y). RR does not depend on xx, so this covers every output. □\square

Claim 2 (a small database exists; Dwork-Roth Proposition 4.1). Let ∣Q∣≥3|Q| \ge 3, α>0\alpha > 0 and m≥ln⁡∣Q∣/α2m \ge \ln|Q|/\alpha^2. Then some y∈Ry \in R has max⁡f∈Q∣f(x)−f(y)∣≤α\max_{f \in Q} |f(x) - f(y)| \le \alpha.

Proof. Draw mm records independently from the empirical distribution x/nx/n, and let yy be their histogram. For a fixed ff, f(y)f(y) is the mean of mm independent 0-1 variables with mean f(x)f(x). By the Hoeffding inequality, P(∣f(y)−f(x)∣>α)≤2e−2mα2≤2∣Q∣−2P(|f(y) - f(x)| > \alpha) \le 2 e^{-2m\alpha^2} \le 2|Q|^{-2}. By the union bound over QQ, the probability that some query has error above α\alpha is at most 2∣Q∣−1<12|Q|^{-1} < 1. So some outcome yy has all errors at most α\alpha, and it lies in RR. □\square

Claim 3 (accuracy). Let OPT=max⁡y∈Ru(x,y)\mathrm{OPT} = \max_{y \in R} u(x, y) and β∈(0,1)\beta \in (0, 1). With probability at least 1−β1 - \beta the output has

max⁡f∈Q∣f(x)−f(y)∣≤−OPT+2(ln⁡∣R∣+ln⁡(1/β))εn.\max_{f \in Q} |f(x) - f(y)| \le -\mathrm{OPT} + \frac{2(\ln|R| + \ln(1/\beta))}{\varepsilon n}.

With m=⌈ln⁡∣Q∣/α2⌉m = \lceil \ln|Q|/\alpha^2 \rceil and ∣Q∣≥3|Q| \ge 3, Claim 2 gives −OPT≤α-\mathrm{OPT} \le \alpha.

Proof. Let t=ln⁡∣R∣+ln⁡(1/β)t = \ln|R| + \ln(1/\beta), and call yy bad if u(x,y)<OPT−2t/(εn)u(x, y) < \mathrm{OPT} - 2t/(\varepsilon n). Let y∗y^* reach OPT\mathrm{OPT}. For a bad yy, P(y)/P(y∗)=eεn(u(x,y)−OPT)/2<e−t=β/∣R∣P(y)/P(y^*) = e^{\varepsilon n (u(x,y) - \mathrm{OPT})/2} < e^{-t} = \beta/|R|. There are at most ∣R∣|R| bad yy, and P(y∗)≤1P(y^*) \le 1, so the total probability of a bad output is less than β\beta. □\square

Size of RR. ∣R∣=(m+U−1U−1)≤Um|R| = \binom{m + U - 1}{U - 1} \le U^m, so ln⁡∣R∣≤mln⁡U\ln|R| \le m \ln U. With m=⌈ln⁡∣Q∣/α2⌉m = \lceil \ln|Q|/\alpha^2 \rceil the error bound of Claim 3 is at most

α+2((ln⁡∣Q∣/α2+1)ln⁡U+ln⁡(1/β))εn.\alpha + \frac{2\big((\ln|Q|/\alpha^2 + 1)\ln U + \ln(1/\beta)\big)}{\varepsilon n}.

The first term falls with α\alpha and the second grows as 1/α21/\alpha^2. Choosing α\alpha of order (ln⁡Uln⁡∣Q∣/(εn))1/3(\ln U \ln|Q|/(\varepsilon n))^{1/3} makes the error of that order. Dwork and Roth state the result as Theorem 4.5 with explicit constants: error at most ((16log⁡∣X∣log⁡∣Q∣+4log⁡(1/β))/(ε∥x∥1))1/3\big((16 \log|X| \log|Q| + 4\log(1/\beta))/(\varepsilon \|x\|_1)\big)^{1/3} with probability at least 1−β1 - \beta.

Cost. Line L2 lists ∣R∣=(m+U−1U−1)|R| = \binom{m + U - 1}{U - 1} histograms. Line L3 computes the ∣Q∣|Q| answers of each in O(∣Q∣U)O(|Q| U), after the answers on xx are computed one time. Line L4 normalizes and samples in O(∣R∣)O(|R|). The total is O(∣R∣ ∣Q∣ U)O(|R|\,|Q|\,U) time and O(∣R∣)O(|R|) space, exponential in mm when U≥2U \ge 2.

Complexity

In the real-RAM model:

  • Line L2 lists ∣R∣=(m+U−1U−1)≤Um|R| = \binom{m + U - 1}{U - 1} \le U^m histograms.
  • Line L3 scores each in O(∣Q∣U)O(|Q| U) time.
  • Line L4 samples in O(∣R∣)O(|R|) time.

The total is O(Um+1∣Q∣)O(U^{m+1} |Q|) time and O(Um)O(U^m) space. With mm of order log⁡∣Q∣/α2\log|Q|/\alpha^2 this is exponential in log⁡U⋅log⁡∣Q∣/α2\log U \cdot \log|Q|/\alpha^2, and super-polynomial in the universe size. Dwork, Naor, Reingold, Rothblum and Vadhan, and later Ullman and Vadhan, show that under cryptographic assumptions no efficient mechanism can produce such synthetic data for all query classes, so some cost of this kind cannot be avoided in general.

Properties

  • Synthetic data. The output is a database, so it answers every counting query, and the answers are consistent.
  • Pure DP. The mechanism is (ε,0)(\varepsilon, 0)-DP.
  • Log dependence on ∣Q∣|Q|. The error grows with log⁡∣Q∣\log|Q|, so QQ can be exponential in the number of attributes, such as all conjunctions.
  • Error of order n−1/3n^{-1/3}. For a fixed QQ and universe, the error falls as n−1/3n^{-1/3}. For a small number of queries, the Laplace mechanism on each query is better.

Variants and improvements

  • VC dimension. Blum, Ligett and Roth state their bound with the VC dimension of the query class in place of log⁡∣Q∣\log|Q|, through a sample size from PAC learning theory.
  • (ε,δ)(\varepsilon, \delta) and better rates. Private multiplicative weights (Hardt and Rothblum 2010) is (ε,δ)(\varepsilon, \delta)-DP, runs in time linear in ∣X∣|X| for each query, and has error of order n−1/2n^{-1/2} up to factors in log⁡∣X∣\log|X|, log⁡∣Q∣\log|Q| and log⁡(1/δ)\log(1/\delta). For a large nn this beats the n−1/3n^{-1/3} rate.
  • MWEM. The offline, practical form of the multiplicative weights approach. See MWEM.
  • Lower bounds. The fingerprinting code lower bound shows that the dependence of private multiplicative weights on nn is close to the best possible for (ε,δ)(\varepsilon, \delta)-DP. The packing lower bound shows that pure DP needs error of order log⁡∣X∣/(εn)\log|X|/(\varepsilon n) for some query sets.

When to use it

Use SmallDB to understand what is possible: it is the simplest proof that a private synthetic database can answer exponentially many counting queries. It runs only on toy universes, as in the test file. For real data, use MWEM or other methods with time polynomial in the universe size. For a few queries, answer them directly with the Laplace mechanism.

Pitfalls

  • Sensitivity of the unnormalized score. Line L4 uses exp⁡(εnu/2)\exp(\varepsilon n u/2) because the normalized score has sensitivity 1/n1/n. If the queries are counts and not fractions, the score has sensitivity 1 and the exponent must be εu/2\varepsilon u/2. Mixing the two scales gives either no privacy or no accuracy.
  • Private nn. The sensitivity 1/n1/n in line L4 uses nn. Under add/remove neighbors nn is private. Treat nn as public, or spend part of the budget on a noisy nn and use a lower bound for it.
  • A data dependent candidate set. Line L2 must list all databases of size mm from the universe XX. Building RR from the records of xx, for example from sub-samples of the real data, makes the support depend on the data and breaks the proof.
  • Too few candidates. If mm in line L1 is too small, no candidate is within α\alpha, and the error is large even with no noise. If mm is too large, ∣R∣|R| explodes and the term ln⁡∣R∣/(εn)\ln|R|/(\varepsilon n) grows.
  • Float sampling. The code samples with random.Random and float weights, for tests only. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012; Canonne, Kamath and Steinke 2020).

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
smalldb_mechanism.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smalldb-mechanism/. The authors are listed in prov/3V0287.jsonl.
"""The SmallDB mechanism of Blum, Ligett and Roth (2008), in the form of
Dwork and Roth (2014, Algorithm 4), for a tiny universe.

The data is a histogram x over a universe X of size U, with n records, and
n is public. A query is a 0-1 vector f over X, and its normalized answer is
f(x) = (1/n) sum_j f[j] x[j], the fraction of records it counts. The
mechanism picks, with the exponential mechanism, a database y of only
m = ceil(ln |Q| / alpha^2) records whose answers are close to those of x.
Neighbors replace one record by another, so each f(x) moves by at most 1/n.

The mechanism lists every database of m records, so its cost is about
U^m. That is the point of the method for theory and the reason it is not
used at scale. The code uses random.Random so that the tests can be
repeated. 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 small_size(alpha: float, num_queries: int) -> int:
    """The size m = ceil(ln |Q| / alpha^2) of the small databases, at least 1. Precondition: alpha > 0."""
    if alpha <= 0:
        raise ValueError("alpha must be positive")
    return max(1, math.ceil(math.log(max(num_queries, 1)) / (alpha * alpha)))


def compositions(m: int, U: int) -> list[tuple[int, ...]]:
    """All histograms of m records over U cells, that is all U-tuples of non-negative integers with sum m.

    There are C(m + U - 1, U - 1) of them. Cost: linear in that number times U.
    """
    if U == 1:
        return [(m,)]
    out = []
    for first in range(m, -1, -1):
        for rest in compositions(m - first, U - 1):
            out.append((first,) + rest)
    return out


def answer(f: Sequence[int], hist: Sequence[int]) -> float:
    """The normalized answer of the counting query f on a histogram: the fraction of records it counts."""
    total = sum(hist)
    return sum(w * h for w, h in zip(f, hist)) / total


def utility(x: Sequence[int], y: Sequence[int], queries: Sequence[Sequence[int]]) -> float:
    """u(x, y) = -max over f of |f(x) - f(y)|. Its sensitivity in x is 1/n under replace. Cost: O(|Q| U)."""
    return -max(abs(answer(f, x) - answer(f, y)) for f in queries)


def smalldb_pmf(
    x: Sequence[int],
    queries: Sequence[Sequence[int]],
    epsilon: float,
    m: int,
) -> dict[tuple[int, ...], float]:
    """The exact output distribution of SmallDB over the databases of m records.

    P(y) is proportional to exp(epsilon * u(x, y) / (2 * (1/n))).
    Precondition: epsilon > 0, n = sum(x) >= 1, at least one query.
    Cost: O(|R| |Q| U) with |R| = C(m + U - 1, U - 1).
    """
    n = sum(x)
    R = compositions(m, len(x))  # @line L2
    u = [utility(x, y, queries) for y in R]  # @line L3
    top = max(u)
    w = [math.exp(epsilon * n * (v - top) / 2.0) for v in u]  # @line L4
    z = sum(w)
    return {y: v / z for y, v in zip(R, w)}


def smalldb(
    x: Sequence[int],
    queries: Sequence[Sequence[int]],
    epsilon: float,
    alpha: float,
    rng: random.Random,
) -> tuple[int, ...]:
    """Release a small synthetic database with SmallDB; it is epsilon-DP for replace neighbors.

    Precondition: epsilon > 0, alpha > 0, n = sum(x) >= 1, at least one query.
    Cost: O(|R| |Q| U) time and O(|R|) space, with |R| about U^m / m!.
    """
    if epsilon <= 0:
        raise ValueError("epsilon must be positive")
    if sum(x) < 1 or not queries:
        raise ValueError("need a non-empty dataset and at least one query")
    m = small_size(alpha, len(queries))  # @line L1
    pmf = smalldb_pmf(x, queries, epsilon, m)
    u = rng.random()
    acc = 0.0
    last = None
    for y, p in pmf.items():
        acc += p
        last = y
        if u < acc:
            return y
    return last


def max_error(x: Sequence[int], y: Sequence[int], queries: Sequence[Sequence[int]]) -> float:
    """The largest error max over f of |f(x) - f(y)| of normalized answers."""
    return -utility(x, y, queries)
test_smalldb_mechanism.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smalldb-mechanism/. The authors are listed in prov/3V0287.jsonl.

import itertools
import math
import random

import dpkit
from smalldb_mechanism import (
    compositions,
    max_error,
    small_size,
    smalldb,
    smalldb_pmf,
    utility,
)

UNIVERSE = (0, 1, 2)


def _subset_queries(U):
    return [[1 if (mask >> j) & 1 else 0 for j in range(U)] for mask in range(1, 2 ** U)]


def _hist(records, U=len(UNIVERSE)):
    h = [0] * U
    for r in records:
        h[r] += 1
    return tuple(h)


def test_compositions_are_all_small_databases() -> None:
    for U in range(1, 5):
        for m in range(0, 6):
            got = compositions(m, U)
            brute = sorted({_hist(c, U) for c in itertools.combinations_with_replacement(range(U), m)})
            assert sorted(got) == brute
            assert len(got) == math.comb(m + U - 1, U - 1)


def test_smalldb_is_epsilon_dp_on_all_replace_pairs() -> None:
    queries = _subset_queries(3)
    epsilon, m = 0.7, 2

    def mech_pmf(records):
        return smalldb_pmf(_hist(records), queries, epsilon, m)

    datasets = list(itertools.combinations_with_replacement(UNIVERSE, 3))
    pairs = [(x, y) for x in datasets for y in dpkit.neighbors_replace(x, UNIVERSE)]
    assert len(pairs) > 30
    assert dpkit.is_pure_dp(mech_pmf, pairs, epsilon)
    worst = max(dpkit.max_privacy_loss(mech_pmf(x), mech_pmf(y)) for x, y in pairs)
    assert 0.2 < worst <= epsilon + 1e-12


def test_pmf_against_direct_formula() -> None:
    # The oracle builds the candidates from multisets and the weights from the definition.
    rng = random.Random(1)
    for _ in range(500):
        U = rng.randrange(1, 4)
        x = [rng.randrange(0, 6) for _ in range(U)]
        x[rng.randrange(U)] += 1
        n = sum(x)
        queries = [[rng.randrange(2) for _ in range(U)] for _ in range(rng.randrange(1, 5))]
        m = rng.randrange(1, 4)
        epsilon = rng.choice([0.3, 1.0, 3.0])
        weights = {}
        for c in itertools.combinations_with_replacement(range(U), m):
            y = _hist(c, U)
            err = max(abs(sum(f[j] * x[j] for j in range(U)) / n - sum(f[j] for j in c) / m) for f in queries)
            weights[y] = math.exp(-epsilon * n * err / 2)
        z = sum(weights.values())
        got = smalldb_pmf(x, queries, epsilon, m)
        assert set(got) == set(weights)
        assert all(math.isclose(got[y], w / z, rel_tol=1e-9, abs_tol=1e-15) for y, w in weights.items())


def test_a_small_database_with_error_alpha_exists() -> None:
    # Dwork-Roth Proposition 4.1, checked by brute force over all databases of size m.
    rng = random.Random(2)
    queries = _subset_queries(3)
    cands = {}
    for alpha in (0.35, 0.5, 0.7):
        m = small_size(alpha, len(queries))
        cands[alpha] = [[sum(f[j] * y[j] for j in range(3)) / m for f in queries] for y in compositions(m, 3)]
    for _ in range(500):
        x = [rng.randrange(0, 20) for _ in range(3)]
        x[rng.randrange(3)] += 1
        n = sum(x)
        fx = [sum(f[j] * x[j] for j in range(3)) / n for f in queries]
        alpha = rng.choice([0.35, 0.5, 0.7])
        best = min(max(abs(a - b) for a, b in zip(fx, fy)) for fy in cands[alpha])
        assert best <= alpha


def test_accuracy_bound_holds_exactly() -> None:
    # The exponential mechanism bound: error <= alpha + 2 (ln|R| + ln(1/beta)) / (epsilon n)
    # with probability at least 1 - beta. We sum the exact pmf.
    rng = random.Random(3)
    queries = _subset_queries(3)
    for _ in range(60):
        x = [rng.randrange(0, 30) for _ in range(3)]
        x[rng.randrange(3)] += 1
        n = sum(x)
        alpha, epsilon, beta = 0.5, rng.choice([0.5, 1.0, 2.0]), 0.1
        m = small_size(alpha, len(queries))
        pmf = smalldb_pmf(x, queries, epsilon, m)
        bound = alpha + 2 * (math.log(len(pmf)) + math.log(1 / beta)) / (epsilon * n)
        assert sum(p for y, p in pmf.items() if max_error(x, y, queries) > bound) <= beta


def test_sampling_matches_pmf() -> None:
    rng = random.Random(4)
    queries = _subset_queries(3)
    x, epsilon, alpha = (5, 2, 1), 1.0, 1.0
    pmf = smalldb_pmf(x, queries, epsilon, small_size(alpha, len(queries)))
    n = 1500
    emp = dpkit.empirical_pmf(smalldb(x, queries, epsilon, alpha, rng) for _ in range(n))
    margin = dpkit.hoeffding_margin(n, 1e-6)
    assert all(abs(emp.get(y, 0.0) - p) <= margin for y, p in pmf.items())


def test_example_values() -> None:
    U = 4
    queries = _subset_queries(U)
    x = (40, 30, 20, 10)
    m = small_size(0.5, len(queries))
    assert m == 11 and len(compositions(m, U)) == 364
    pmf = smalldb_pmf(x, queries, 1.0, m)
    best = max(pmf, key=pmf.get)
    assert best == (5, 3, 2, 1)
    assert math.isclose(max_error(x, best, queries), 0.6 / 11)
    assert 0.87 < sum(p for y, p in pmf.items() if max_error(x, y, queries) <= 0.1) < 0.89


def test_utility_sensitivity_is_one_over_n() -> None:
    rng = random.Random(5)
    queries = _subset_queries(3)
    for _ in range(200):
        records = tuple(rng.randrange(3) for _ in range(rng.randrange(1, 6)))
        y = _hist([rng.randrange(3) for _ in range(3)])
        for other in dpkit.neighbors_replace(records, UNIVERSE):
            d = abs(utility(_hist(records), y, queries) - utility(_hist(other), y, queries))
            assert d <= 1 / len(records) + 1e-12


def test_bad_parameters() -> None:
    rng = random.Random(6)
    q = _subset_queries(2)
    for args in [((1, 1), q, 0.0, 0.5), ((0, 0), q, 1.0, 0.5), ((1, 1), [], 1.0, 0.5), ((1, 1), q, 1.0, 0.0)]:
        try:
            smalldb(*args, rng)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")

History

Dinur and Nissim (2003) showed that answering too many queries too accurately reveals the data, and in the early private mechanisms the noise grew with the number of queries. Blum, Ligett and Roth (STOC 2008) showed that with a synthetic database the number of queries can be exponential in nn, with error depending on the VC dimension of the query class. Dwork and Roth (2014) gave the form used here, with a finite query set and the exponential mechanism over small databases. Hardt and Rothblum (2010) and Hardt, Ligett and McSherry (2012) then gave faster methods with multiplicative weights.

References

  1. Cynthia Dwork and Aaron Roth, The Algorithmic Foundations of Differential Privacy, Foundations and Trends in Theoretical Computer Science 9(3-4), 2014, Section 4.1: Algorithm 4 (SmallDB), Proposition 4.1 (a small database exists), Theorem 4.2 (privacy), Proposition 4.4 and Theorem 4.5 (accuracy)
  2. Salil Vadhan, The complexity of differential privacy, in Tutorials on the Foundations of Cryptography, Springer, 2017, pages 347 to 450, Section 4.1 (SmallDB) and Theorem 4.1
  3. Avrim Blum, Katrina Ligett and Aaron Roth, A learning theory approach to non-interactive database privacy, STOC 2008; journal version in Journal of the ACM, 2013, the original mechanism and its bound in terms of the VC dimension of the query class
  4. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point 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