Algorithm Search⌘K

Algorithmintro

Laplace mechanism

Also called Laplace noise mechanism.

Adds Laplace noise with scale equal to the l1 sensitivity over epsilon to a numeric query, which gives epsilon-differential privacy.

Time
O(k) worst
Space
O(k) extra
Where
k = the number of coordinates of the query
Properties
randomizedrandomized
Origin
Cynthia Dwork, Frank McSherry, Kobbi Nissim, Adam Smith, 2006

The Laplace mechanism answers a numeric query about a private dataset with noise from the Laplace distribution added to each coordinate. The scale of the noise is the global sensitivity Δ1f\Delta_1 f divided by ε\varepsilon, and then the output is ε\varepsilon-differentially private. The error of each coordinate is about Δ1f/ε\Delta_1 f / \varepsilon and does not grow with the size of the dataset. It is the first mechanism of differential privacy, and the geometric mechanism and the Gaussian mechanism are its discrete and its ℓ2\ell_2 versions.

In plain words

You want to publish a count, such as the number of people in a table who have a disease. One person can change that count by at most one. So you add random noise that is often of size about one, and sometimes larger. Then the published number looks almost the same whether or not a given person is in the table.

The noise comes from a fixed bell-like shape with a sharp peak at zero and two tails that fall at a steady rate. A smaller privacy budget gives wider noise. A query that one person can change more also gets wider noise. The noise does not depend on how many people are in the table, so a large table gives an accurate answer.

The problem

The input is a dataset x=(x1,…,xn)x = (x_1, \ldots, x_n) of records from a universe X\mathcal X, a query ff that maps datasets to Rk\mathbb R^k, a number Δ≥Δ1f\Delta \ge \Delta_1 f, and a privacy parameter ε>0\varepsilon > 0. Here

Δ1f=max⁡x∼x′∥f(x)−f(x′)∥1,\Delta_1 f = \max_{x \sim x'} \lVert f(x) - f(x') \rVert_1,

where x∼x′x \sim x' means that xx and x′x' are neighbors. The page uses add/remove neighbors unless it says otherwise: x′x' is xx with one record added or removed. Under replace neighbors, where one record changes and nn stays fixed, the same query can have a larger sensitivity. A histogram has Δ1=1\Delta_1 = 1 under add/remove and Δ1=2\Delta_1 = 2 under replace.

The output is a random vector y∈Rky \in \mathbb R^k. The map from xx to the distribution of yy must be ε\varepsilon-differentially private, and yy must be close to f(x)f(x).

The Laplace distribution Lap(b)\mathrm{Lap}(b) with scale b>0b > 0 has the density and the distribution function

pb(z)=12be−∣z∣/b,Fb(z)={12ez/bz<0,1−12e−z/bz≥0.p_b(z) = \frac{1}{2b} e^{-|z|/b}, \qquad F_b(z) = \begin{cases} \tfrac12 e^{z/b} & z < 0, \\ 1 - \tfrac12 e^{-z/b} & z \ge 0. \end{cases}

Its mean is 0, its variance is 2b22b^2, its mean absolute value is bb, and Pr⁡[∣Z∣>t]=e−t/b\Pr[|Z| > t] = e^{-t/b} for t≥0t \ge 0.

The algorithm

  1. LAPLACE-MECHANISM(x, f, Delta, epsilon) ▷ Delta >= the l1 sensitivity of f
  2. 1b <- Delta / epsilon
  3. 2v <- f(x) ▷ v = (v_1, ..., v_k)
  4. 3for i <- 1 to k do
  5. 4draw u uniform in (-1/2, 1/2) ▷ draw again if u = -1/2
  6. 5z <- -b sgn(u) ln(1 - 2|u|) ▷ the inverse of F_b at u + 1/2
  7. 6y_i <- v_i + z
  8. 7return y = (y_1, ..., y_k)

Line L1 sets the scale. Line L2 computes the true answer, and this is the only line that reads the data. Lines L4 and L5 draw one sample of Lap(b)\mathrm{Lap}(b) by inverse transform sampling: if uu is uniform, then Fb−1(u+1/2)F_b^{-1}(u + 1/2) has the distribution function FbF_b. Line L6 adds an independent sample to each coordinate. The output of line L7 is the only thing that is published. The noise of line L4 is never published, and it is never used again.

The code on this site uses floats and a seeded pseudorandom generator, so that the tests can repeat each run. A deployment needs a cryptographic source of randomness and an exact sampler, because float noise leaks through its low-order bits (Mironov 2012; Canonne, Kamath and Steinke 2020). The discrete Gaussian mechanism page shows the exact samplers.

Example

The universe is {0,1,2}\{0, 1, 2\} and the dataset is x=(0,0,1,2,2,2)x = (0, 0, 1, 2, 2, 2), with n=6n = 6. The query is the histogram f(x)=(2,1,3)f(x) = (2, 1, 3), with Δ1f=1\Delta_1 f = 1 under add/remove neighbors. With ε=1\varepsilon = 1, line L1 gives b=1b = 1. Assume that line L4 draws u=0.3u = 0.3, u=−0.1u = -0.1 and u=0.45u = 0.45.

step ii viv_i uu zz (line L5) yiy_i (line L6)
L1, L2 b=1b = 1, v=(2,1,3)v = (2, 1, 3)
L3 to L6 1 2 0.3 −ln⁡0.4=0.916291-\ln 0.4 = 0.916291 2.916291
L3 to L6 2 1 −0.1-0.1 ln⁡0.8=−0.223144\ln 0.8 = -0.223144 0.776856
L3 to L6 3 3 0.45 −ln⁡0.1=2.302585-\ln 0.1 = 2.302585 5.302585
L7 y=(2.916291,0.776856,5.302585)y = (2.916291, 0.776856, 5.302585)

The accuracy theorem below says that, with probability at least 1−β=0.91 - \beta = 0.9, each of the k=3k = 3 errors is at most bln⁡(k/β)=ln⁡30=3.401197b \ln(k / \beta) = \ln 30 = 3.401197. Here the largest error is 2.302585.

A second check: with Δ=1\Delta = 1 and ε=0.5\varepsilon = 0.5, the scale is b=2b = 2, the variance of the noise is 8, and Pr⁡[∣Z∣>2ln⁡10]=Pr⁡[∣Z∣>4.6052]=0.1\Pr[|Z| > 2 \ln 10] = \Pr[|Z| > 4.6052] = 0.1.

Correctness

Theorem (Dwork, McSherry, Nissim and Smith 2006; Dwork-Roth Theorem 3.6). If Δ≥Δ1f\Delta \ge \Delta_1 f under a neighbor relation, then LAPLACE-MECHANISM is ε\varepsilon-differentially private under that relation.

The key step is a bound on the ratio of the output densities. For neighbors x∼x′x \sim x' and every output yy, the triangle inequality ∣a∣−∣a′∣≤∣a−a′∣|a| - |a'| \le |a - a'| gives

px(y)px′(y)=∏i=1kexp⁡ ⁣(∣yi−f(x′)i∣−∣yi−f(x)i∣b)≤exp⁡ ⁣(∥f(x)−f(x′)∥1b)≤eε.\frac{p_{x}(y)}{p_{x'}(y)} = \prod_{i=1}^{k} \exp\!\Big(\frac{|y_i - f(x')_i| - |y_i - f(x)_i|}{b}\Big) \le \exp\!\Big(\frac{\lVert f(x) - f(x') \rVert_1}{b}\Big) \le e^{\varepsilon}.

The integral of this bound over a set SS of outputs gives the definition. The full proof, with the proof that lines L4 and L5 sample Lap(b)\mathrm{Lap}(b) and the proof of the accuracy bound, is in the correctness proof of this page.

Theorem (accuracy, Dwork-Roth Theorem 3.8). For 0<β<10 < \beta < 1, with probability at least 1−β1 - \beta, max⁡i∣yi−f(x)i∣≤(Δ/ε)ln⁡(k/β)\max_i |y_i - f(x)_i| \le (\Delta / \varepsilon) \ln(k / \beta). The proof is a union bound over the kk tails Pr⁡[∣Zi∣>t]=e−t/b\Pr[|Z_i| > t] = e^{-t/b}.

Proof: The Laplace mechanism samples the right noise, is epsilon-DP, and is accuratefull

We work in the real RAM. Fix a neighbor relation ∼\sim, a query ff with values in Rk\mathbb R^k, a number Δ≥Δ1f=max⁡x∼x′∥f(x)−f(x′)∥1\Delta \ge \Delta_1 f = \max_{x \sim x'} \lVert f(x) - f(x') \rVert_1, and ε>0\varepsilon > 0. Let b=Δ/εb = \Delta / \varepsilon (line L1). We write pb(z)=12be−∣z∣/bp_b(z) = \frac{1}{2b} e^{-|z|/b} for the density of Lap(b)\mathrm{Lap}(b) and FbF_b for its distribution function.

Lemma 1 (the sampler). If uu is uniform on (−1/2,1/2)(-1/2, 1/2), then z=−b sgn(u)ln⁡(1−2∣u∣)z = -b\,\mathrm{sgn}(u) \ln(1 - 2|u|) of line L5 has the distribution Lap(b)\mathrm{Lap}(b).

Proof. Let w=u+1/2w = u + 1/2, which is uniform on (0,1)(0, 1). We show that z=Fb−1(w)z = F_b^{-1}(w). If w<1/2w < 1/2, then u<0u < 0 and z=bln⁡(1−2∣u∣)=bln⁡(2w)z = b \ln(1 - 2|u|) = b \ln(2w). This is negative, and Fb(z)=12ez/b=12⋅2w=wF_b(z) = \frac12 e^{z/b} = \frac12 \cdot 2w = w. If w≥1/2w \ge 1/2, then u≥0u \ge 0 and z=−bln⁡(1−2u)=−bln⁡(2−2w)≥0z = -b \ln(1 - 2u) = -b \ln(2 - 2w) \ge 0, and Fb(z)=1−12e−z/b=1−(1−w)=wF_b(z) = 1 - \frac12 e^{-z/b} = 1 - (1 - w) = w. (u=0u = 0 gives z=0z = 0 with either sign.) FbF_b is continuous and strictly increasing, so Pr⁡[z≤t]=Pr⁡[w≤Fb(t)]=Fb(t)\Pr[z \le t] = \Pr[w \le F_b(t)] = F_b(t) for every tt. □\square

So, by Lemma 1 and because each pass of line L3 draws a fresh uu, the output of line L7 is y=f(x)+Zy = f(x) + Z with Z=(Z1,…,Zk)Z = (Z_1, \ldots, Z_k) and ZiZ_i independent Lap(b)\mathrm{Lap}(b). Its density at y∈Rky \in \mathbb R^k is

px(y)=∏i=1k12bexp⁡(−∣yi−f(x)i∣b).p_x(y) = \prod_{i=1}^{k} \frac{1}{2b} \exp\Big(-\frac{|y_i - f(x)_i|}{b}\Big).

Theorem 1 (privacy). For all x∼x′x \sim x' and every measurable set S⊆RkS \subseteq \mathbb R^k, Pr⁡[M(x)∈S]≤eεPr⁡[M(x′)∈S]\Pr[M(x) \in S] \le e^{\varepsilon} \Pr[M(x') \in S], where MM is LAPLACE-MECHANISM with the parameters above.

Proof. Fix x∼x′x \sim x' and y∈Rky \in \mathbb R^k. For each ii, the triangle inequality gives ∣yi−f(x′)i∣−∣yi−f(x)i∣≤∣f(x)i−f(x′)i∣|y_i - f(x')_i| - |y_i - f(x)_i| \le |f(x)_i - f(x')_i|. So

px(y)px′(y)=exp⁡(1b∑i=1k(∣yi−f(x′)i∣−∣yi−f(x)i∣))≤exp⁡(∥f(x)−f(x′)∥1b)≤exp⁡(Δ1fΔ/ε)≤eε.\frac{p_x(y)}{p_{x'}(y)} = \exp\Big(\frac{1}{b} \sum_{i=1}^{k} \big(|y_i - f(x')_i| - |y_i - f(x)_i|\big)\Big) \le \exp\Big(\frac{\lVert f(x) - f(x') \rVert_1}{b}\Big) \le \exp\Big(\frac{\Delta_1 f}{\Delta / \varepsilon}\Big) \le e^{\varepsilon}.

The last step uses Δ≥Δ1f\Delta \ge \Delta_1 f. Both densities are positive everywhere, so px(y)≤eεpx′(y)p_x(y) \le e^{\varepsilon} p_{x'}(y) for all yy. The integral over SS gives

Pr⁡[M(x)∈S]=∫Spx(y) dy≤eε∫Spx′(y) dy=eεPr⁡[M(x′)∈S].\Pr[M(x) \in S] = \int_S p_x(y)\,dy \le e^{\varepsilon} \int_S p_{x'}(y)\,dy = e^{\varepsilon} \Pr[M(x') \in S].

The relation ∼\sim is symmetric, so the same holds with xx and x′x' swapped. □\square

Theorem 2 (accuracy). For 0<β<10 < \beta < 1, Pr⁡[max⁡i∣yi−f(x)i∣>bln⁡(k/β)]≤β\Pr\big[\max_i |y_i - f(x)_i| > b \ln(k/\beta)\big] \le \beta.

Proof. For t≥0t \ge 0, Pr⁡[∣Zi∣>t]=2∫t∞12be−z/b dz=e−t/b\Pr[|Z_i| > t] = 2 \int_t^\infty \frac{1}{2b} e^{-z/b}\,dz = e^{-t/b}. Take t=bln⁡(k/β)t = b \ln(k/\beta), so that e−t/b=β/ke^{-t/b} = \beta / k. The union bound over the kk coordinates gives Pr⁡[∃i:∣Zi∣>t]≤k⋅β/k=β\Pr[\exists i : |Z_i| > t] \le k \cdot \beta / k = \beta. Since yi−f(x)i=Ziy_i - f(x)_i = Z_i, this is the claim. □\square

Termination. The loop of line L3 runs kk times. Line L4 draws again only on the event u=−1/2u = -1/2, which has probability 0 in the real RAM, so each pass ends with probability 1.

Lemma 1, Theorem 1 and Theorem 2 together show that the output has the stated distribution, is ε\varepsilon-differentially private under the relation for which Δ≥Δ1f\Delta \ge \Delta_1 f, and has error at most (Δ/ε)ln⁡(k/β)(\Delta/\varepsilon) \ln(k/\beta) in every coordinate with probability at least 1−β1 - \beta. ■\blacksquare

Complexity

The model is the real RAM: a uniform real number in (−1/2,1/2)(-1/2, 1/2), a logarithm and an addition each cost one step. The cost is counted per query, after the one evaluation of ff in line L2.

  • Time. The loop of line L3 runs kk times. Each pass draws one uniform number and does O(1)O(1) arithmetic. The event u=−1/2u = -1/2 of line L4 has probability 0 in this model. So the time is O(k)O(k) in the worst case.
  • Space. The output yy has kk numbers, and the loop keeps O(1)O(1) other numbers. So the extra space is O(k)O(k).

On real machines with 53-bit floats, line L4 draws again with probability 2−532^{-53}, so the expected number of draws is still k(1+O(2−53))k (1 + O(2^{-53})).

Properties

  • Pure privacy. The output is (ε,0)(\varepsilon, 0)-DP. The bound is tight: when f(x)−f(x′)f(x) - f(x') has one nonzero coordinate equal to Δ\Delta, the ratio of the densities is exactly eεe^{\varepsilon} on a half-line of outputs. The tests check this on a grid (a measurement on the test data: the largest log ratio is 0.5 for ε=0.5\varepsilon = 0.5).
  • Unbiased. E[y]=f(x)\mathbb E[y] = f(x), and each coordinate has variance 2(Δ/ε)22 (\Delta / \varepsilon)^2 and mean absolute error Δ/ε\Delta / \varepsilon.
  • No dependence on nn. The error is the same for 10 records and for 10910^9 records. The relative error of a count of size cc is about 1/(εc)1 / (\varepsilon c).
  • Closed under post-processing. Rounding, clamping or any other map of yy that does not read xx keeps ε\varepsilon-DP, by the post-processing theorem.
  • Composition. Two runs on the same data with ε1\varepsilon_1 and ε2\varepsilon_2 are (ε1+ε2)(\varepsilon_1 + \varepsilon_2)-DP together, by the sequential composition theorem.

Variants and improvements

  • Integer outputs. The geometric mechanism adds the discrete analog of Laplace noise to an integer query. It needs no floats.
  • The ℓ2\ell_2 version. The Gaussian mechanism calibrates to Δ2f\Delta_2 f and gives (ε,δ)(\varepsilon, \delta)-DP. For kk counts that one record can all change by one, Δ1=k\Delta_1 = k and Δ2=k\Delta_2 = \sqrt k, so the Gaussian error is much smaller for large kk.
  • Snapping. Mironov (2012) rounds and clamps the float output so that the low-order bits no longer depend on the data. This gives a slightly larger ε\varepsilon, which his paper bounds.
  • Data-dependent noise. Smooth sensitivity and propose-test-release add less noise when the dataset is far from the worst case, such as for a median.
  • Selection. To publish only the index of the largest of mm counts, report noisy max adds Laplace noise and releases only the index.
  • Release of a model. Output perturbation adds Laplace or Gaussian noise to the parameters of a trained model, with the sensitivity of the training map.

When to use it

Use the Laplace mechanism for a small number of numeric queries with a low ℓ1\ell_1 sensitivity, when you need pure ε\varepsilon-DP: counts, histograms, and sums or means of values that are clipped to a known range. If the answer is an integer and you want integer output with exact sampling, use the geometric mechanism. If you answer many queries, or the ℓ2\ell_2 sensitivity is much smaller than the ℓ1\ell_1 sensitivity, and a small δ\delta is acceptable, the Gaussian mechanism adds less noise. If you need the best item of a set and not a number, use the exponential mechanism or report noisy max.

Pitfalls

  • The sensitivity of the wrong neighbor relation. A histogram has Δ1=1\Delta_1 = 1 under add/remove and 2 under replace. Line L1 with b=1/εb = 1/\varepsilon is only 2ε2\varepsilon-DP under replace. The tests measure a log ratio of 1.0 for ε=0.5\varepsilon = 0.5 there. Under replace, line L1 must use Δ=2\Delta = 2, and then b=2/εb = 2/\varepsilon.
  • The scale of one coordinate. For kk queries that one record can each change by 1, line L1 with Δ=1\Delta = 1 gives only kεk\varepsilon-DP. Line L1 must use the ℓ1\ell_1 sensitivity of the whole vector, Δ=k\Delta = k.
  • Local sensitivity. Line L1 with the change of ff at the actual xx, in place of the maximum over all neighbor pairs, is not private, because the scale itself then depends on the data. Use the global Δ1f\Delta_1 f, or the methods of smooth sensitivity.
  • Float noise. Lines L4 and L5 on floats with a non-cryptographic generator are fine for study, but not for a release (Mironov 2012). Use an exact sampler from a cryptographic source, or the snapping mechanism.
  • Fresh noise for a repeated query. Each call of the mechanism draws fresh noise in line L4 and costs ε\varepsilon again. The average of rr answers to one query has rr times the cost. Store and reuse a published answer.

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
laplace_mechanism.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplace-mechanism/. The authors are listed in prov/ZJZCN9.jsonl.
"""The Laplace mechanism of Dwork, McSherry, Nissim and Smith (2006).

The code uses random.Random so that the tests are reproducible, and it adds
float noise. Both are fine for study and wrong for a deployment: a real
release needs a cryptographic source of randomness and an exact sampler,
because the float version leaks through its low-order bits (Mironov 2012).
"""

from __future__ import annotations

import math
import random
from typing import Callable, Sequence, TypeVar

D = TypeVar("D")


def laplace_scale(sensitivity: float, epsilon: float) -> float:
    """The noise scale b = sensitivity / epsilon. Precondition: both are positive."""
    if sensitivity <= 0 or epsilon <= 0:
        raise ValueError("sensitivity and epsilon must be positive")
    return sensitivity / epsilon


def laplace_from_uniform(u: float, b: float) -> float:
    """The Lap(b) quantile at u + 1/2, for u in the open interval (-1/2, 1/2).

    This is the inverse of the CDF F(z) = e^(z/b)/2 for z < 0 and
    1 - e^(-z/b)/2 for z >= 0. Cost: O(1).
    """
    if not -0.5 < u < 0.5:
        raise ValueError("u must be in (-1/2, 1/2)")
    s = (u > 0) - (u < 0)
    return -b * s * math.log(1.0 - 2.0 * abs(u))


def laplace_mechanism(
    x: D,
    f: Callable[[D], Sequence[float]],
    sensitivity: float,
    epsilon: float,
    rng: random.Random,
) -> list[float]:
    """Release f(x) plus independent Lap(sensitivity / epsilon) noise on each coordinate.

    Precondition: sensitivity is at least the l1 sensitivity of f under the
    neighbor relation that the caller uses, and epsilon > 0. Then the output
    is epsilon-differentially private for that relation.
    Cost: one evaluation of f, then O(k) time and k uniform draws for k coordinates.
    """
    b = laplace_scale(sensitivity, epsilon)  # @line L1
    v = list(f(x))  # @line L2
    y: list[float] = []
    for vi in v:  # @line L3
        u = rng.random() - 0.5  # @line L4
        while u == -0.5:  # the open interval excludes -1/2
            u = rng.random() - 0.5
        z = laplace_from_uniform(u, b)  # @line L5
        y.append(vi + z)  # @line L6
    return y  # @line L7


def laplace_log_density(y: Sequence[float], center: Sequence[float], b: float) -> float:
    """The log density at y of center plus k independent Lap(b) coordinates. Cost: O(k)."""
    return sum(-math.log(2.0 * b) - abs(yi - ci) / b for yi, ci in zip(y, center))


def laplace_tail(t: float, b: float) -> float:
    """P(|Z| > t) = e^(-t/b) for Z ~ Lap(b) and t >= 0."""
    return math.exp(-t / b)


def laplace_error_bound(k: int, b: float, beta: float) -> float:
    """The bound b ln(k / beta) on the largest error over k coordinates.

    With probability at least 1 - beta, every coordinate of the noise is at
    most this value in absolute value (a union bound over the k tails).
    """
    return b * math.log(k / beta)
test_laplace_mechanism.py 229 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplace-mechanism/. The authors are listed in prov/ZJZCN9.jsonl.

import itertools
import math
import random
from collections import Counter
from fractions import Fraction

import dpkit
from laplace_mechanism import (
    laplace_error_bound,
    laplace_from_uniform,
    laplace_log_density,
    laplace_mechanism,
    laplace_scale,
    laplace_tail,
)

UNIVERSE = (0, 1, 2)


def histogram(x):
    return [sum(1 for r in x if r == v) for v in UNIVERSE]


def all_datasets(max_n):
    for n in range(max_n + 1):
        for x in itertools.combinations_with_replacement(UNIVERSE, n):
            yield x


# ---------------------------------------------------------------- dpkit self-test


def test_dpkit_neighbors_match_multiset_distance():
    rng = random.Random(11)
    for _ in range(500):
        n = rng.randint(0, 4)
        x = tuple(rng.choice(UNIVERSE) for _ in range(n))
        cx = Counter(x)
        got = {tuple(sorted(y)) for y in dpkit.neighbors_add_remove(x, UNIVERSE)}
        assert len(got) == len(dpkit.neighbors_add_remove(x, UNIVERSE))
        want = set()
        for m in range(n - 1, n + 2):
            for y in itertools.combinations_with_replacement(UNIVERSE, max(m, 0)):
                if m < 0:
                    continue
                cy = Counter(y)
                diff = sum(abs(cx[v] - cy[v]) for v in UNIVERSE)
                if diff == 1:
                    want.add(tuple(sorted(y)))
        assert got == want
        got_r = {tuple(sorted(y)) for y in dpkit.neighbors_replace(x, UNIVERSE)}
        want_r = set()
        for y in itertools.combinations_with_replacement(UNIVERSE, n):
            cy = Counter(y)
            if sum(abs(cx[v] - cy[v]) for v in UNIVERSE) == 2:
                want_r.add(tuple(sorted(y)))
        assert got_r == want_r


def _rr_pmf(x):
    # randomized response with e^epsilon = 3 on a dataset of one bit
    v = x[0]
    return {v: Fraction(3, 4), 1 - v: Fraction(1, 4)}


def test_dpkit_randomized_response_is_exactly_ln3_dp():
    pairs = [((0,), (1,))]
    assert dpkit.max_privacy_loss(_rr_pmf((0,)), _rr_pmf((1,))) == math.log(3)
    assert dpkit.is_pure_dp(_rr_pmf, pairs, math.log(3))
    assert not dpkit.is_pure_dp(_rr_pmf, pairs, math.log(3) - 0.01)
    assert dpkit.is_approx_dp(_rr_pmf, pairs, math.log(3), 0.0)
    assert not dpkit.is_approx_dp(_rr_pmf, pairs, 0.0, 0.49)
    loss = dpkit.privacy_loss(_rr_pmf((0,)), _rr_pmf((1,)))
    assert math.isclose(loss[0], math.log(3)) and math.isclose(loss[1], -math.log(3))


def test_dpkit_hockey_stick():
    p = {0: Fraction(3, 4), 1: Fraction(1, 4)}
    q = {0: Fraction(1, 4), 1: Fraction(3, 4)}
    assert dpkit.hockey_stick(p, p, 0.0) == 0.0
    assert dpkit.hockey_stick(p, p, 1.0) == 0.0
    assert math.isclose(dpkit.hockey_stick(p, q, 0.0), 0.5)  # total variation distance
    assert dpkit.hockey_stick(p, q, math.log(3)) <= 1e-15
    assert math.isclose(dpkit.hockey_stick(p, q, math.log(2)), 0.75 - 2 * 0.25)
    assert math.isclose(dpkit.hockey_stick({0: 1.0}, {1: 1.0}, 5.0), 1.0)
    assert dpkit.max_privacy_loss({0: 1.0}, {1: 1.0}) == math.inf
    assert dpkit.max_privacy_loss({}, {1: 1.0}) == -math.inf


def test_dpkit_renyi_of_bernoulli():
    p = {0: Fraction(3, 4), 1: Fraction(1, 4)}
    q = {0: Fraction(1, 4), 1: Fraction(3, 4)}
    # order 2: ln(sum p^2 / q) = ln(9/4 + 1/12) = ln(7/3)
    assert math.isclose(dpkit.renyi_divergence(p, q, 2.0), math.log(7 / 3))
    rng = random.Random(12)
    for _ in range(500):
        a, b = rng.uniform(0.01, 0.99), rng.uniform(0.01, 0.99)
        alpha = rng.uniform(1.1, 8.0)
        closed = math.log(a**alpha * b ** (1 - alpha) + (1 - a) ** alpha * (1 - b) ** (1 - alpha)) / (alpha - 1)
        got = dpkit.renyi_divergence({1: a, 0: 1 - a}, {1: b, 0: 1 - b}, alpha)
        assert math.isclose(got, closed, rel_tol=1e-9, abs_tol=1e-12)
    # near alpha = 1 it tends to the KL divergence, which is ln(3)/2 here
    assert abs(dpkit.renyi_divergence(p, q, 1.0 + 1e-7) - math.log(3) / 2) < 1e-6
    assert dpkit.renyi_divergence({0: 1.0}, {1: 1.0}, 2.0) == math.inf


def test_dpkit_empirical_and_margin():
    assert dpkit.empirical_pmf([]) == {}
    assert dpkit.empirical_pmf([1, 1, 2, 3]) == {1: 0.5, 2: 0.25, 3: 0.25}
    assert math.isclose(dpkit.hoeffding_margin(2000, 0.01), math.sqrt(math.log(200) / 4000))
    assert dpkit.log_ratio_grid(lambda z: -abs(z), lambda z: -abs(z - 1), [-3, 0, 0.5, 4]) == 1.0


# ---------------------------------------------------------------- the Laplace mechanism


def test_check_values():
    b = laplace_scale(1.0, 0.5)
    assert b == 2.0
    assert math.isclose(2 * b * b, 8.0)
    assert math.isclose(laplace_tail(2 * math.log(10), b), 0.1)
    assert abs(2 * math.log(10) - 4.6052) < 5e-5


def test_quantile_against_cdf():
    rng = random.Random(21)

    def cdf(z, b):
        return 0.5 * math.exp(z / b) if z < 0 else 1 - 0.5 * math.exp(-z / b)

    assert laplace_from_uniform(0.0, 3.0) == 0.0
    for _ in range(500):
        b = rng.uniform(0.1, 10)
        u = rng.uniform(-0.499, 0.499)
        z = laplace_from_uniform(u, b)
        assert math.isclose(cdf(z, b), u + 0.5, rel_tol=1e-9, abs_tol=1e-12)


def _grid_check(relation, sensitivity, epsilon, n_max):
    b = laplace_scale(sensitivity, epsilon)
    grid = [(-2.0 + 0.5 * i, -2.0 + 0.5 * j, -2.0 + 0.5 * k) for i in range(0, 15, 2) for j in range(0, 15, 3) for k in range(0, 15, 3)]
    worst = 0.0
    for x in all_datasets(n_max):
        for y in relation(x, UNIVERSE):
            fx, fy = histogram(x), histogram(y)
            w = dpkit.log_ratio_grid(
                lambda z: laplace_log_density(z, fx, b),
                lambda z: laplace_log_density(z, fy, b),
                grid,
            )
            worst = max(worst, w)
    return worst


def test_privacy_on_a_grid_add_remove():
    # a histogram has l1 sensitivity 1 under add/remove
    worst = _grid_check(dpkit.neighbors_add_remove, 1.0, 0.5, 3)
    assert worst <= 0.5 + 1e-9
    assert worst >= 0.5 - 1e-9  # the bound is attained


def test_privacy_on_a_grid_replace():
    # under replace the sensitivity is 2; calibrating with 1 gives only 2 epsilon
    assert _grid_check(dpkit.neighbors_replace, 1.0, 0.5, 3) >= 1.0 - 1e-9
    assert _grid_check(dpkit.neighbors_replace, 2.0, 0.5, 3) <= 0.5 + 1e-9


def test_random_pairs_log_ratio():
    rng = random.Random(22)
    for _ in range(500):
        eps = rng.uniform(0.05, 3.0)
        b = laplace_scale(1.0, eps)
        x = tuple(rng.choice(UNIVERSE) for _ in range(rng.randint(0, 5)))
        ys = dpkit.neighbors_add_remove(x, UNIVERSE)
        y = rng.choice(ys)
        z = [rng.uniform(-6, 10) for _ in UNIVERSE]
        loss = laplace_log_density(z, histogram(x), b) - laplace_log_density(z, histogram(y), b)
        assert abs(loss) <= eps + 1e-9


def test_sampler_monte_carlo():
    rng = random.Random(23)
    n = 2000
    zs = [laplace_mechanism((), lambda x: [0.0], 1.0, 0.5, rng)[0] for _ in range(n)]
    m = dpkit.hoeffding_margin(n, 1e-3)
    tail = sum(1 for z in zs if abs(z) > 2 * math.log(10)) / n
    assert abs(tail - 0.1) <= m
    for t in (-3.0, -1.0, 0.0, 1.0, 3.0):
        cdf = 0.5 * math.exp(t / 2) if t < 0 else 1 - 0.5 * math.exp(-t / 2)
        assert abs(sum(1 for z in zs if z <= t) / n - cdf) <= m
    var = sum(z * z for z in zs) / n
    assert abs(var - 8.0) < 2.0


def test_accuracy_bound():
    rng = random.Random(24)
    x = (0, 0, 1, 2, 2, 2)
    fx = histogram(x)
    b = laplace_scale(1.0, 1.0)
    beta = 0.1
    bound = laplace_error_bound(3, b, beta)
    n = 2000
    bad = 0
    for _ in range(n):
        y = laplace_mechanism(x, histogram, 1.0, 1.0, rng)
        if max(abs(a - c) for a, c in zip(y, fx)) > bound:
            bad += 1
    assert bad / n <= beta + dpkit.hoeffding_margin(n, 1e-3)


def test_edges():
    rng = random.Random(25)
    assert laplace_mechanism((), lambda x: [], 1.0, 1.0, rng) == []
    for bad in ((0.0, 1.0), (1.0, 0.0), (-1.0, 1.0)):
        try:
            laplace_scale(*bad)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")
    try:
        laplace_from_uniform(-0.5, 1.0)
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")

History

Dwork, McSherry, Nissim and Smith (TCC 2006) defined the sensitivity of a query and proved that Laplace noise scaled to it gives what is now called ε\varepsilon-differential privacy. The same paper gives the privacy definition in its first form. Dwork and Roth (2014) give the mechanism in the form of this page, with the accuracy bound for kk coordinates. Mironov (2012) showed that the textbook float implementation is not private, and Canonne, Kamath and Steinke (2020) gave exact samplers for the discrete versions.

References

  1. Cynthia Dwork, Frank McSherry, Kobbi Nissim and Adam Smith, Calibrating noise to sensitivity in private data analysis, TCC 2006, LNCS 3876, pages 265 to 284, the definition of sensitivity and the mechanism that adds Laplace noise scaled to it
  2. Cynthia Dwork and Aaron Roth, The Algorithmic Foundations of Differential Privacy, Foundations and Trends in Theoretical Computer Science 9(3-4), 2014, pages 211 to 407, Section 3.3, Definition 3.1 (l1 sensitivity), Definition 3.2 (the Laplace distribution), Definition 3.3 (the Laplace mechanism), Theorem 3.6 (privacy), Fact 3.7 (the tail) and Theorem 3.8 (accuracy)
  3. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why floating-point Laplace noise is not private, and the snapping mechanism
  4. Clement L. Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, exact samplers for discrete Laplace and discrete Gaussian noise

Where this leads

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