Algorithm Search⌘K

Algorithmcore

Geometric mechanism

Also called discrete Laplace mechanism, two-sided geometric mechanism.

Adds two-sided geometric noise to an integer count, and is universally utility-maximizing for count queries under differential privacy.

Time
O(1/(1 - a)) expected
Space
O(1) extra
Where
a = the noise parameter alpha = e^(-epsilon), so that 1/(1 - a) <= 1 + 1/epsilon
Properties
randomizedexactrandomized
Origin
Arpita Ghosh, Tim Roughgarden, Mukund Sundararajan, 2009

The geometric mechanism answers an integer query, such as a count, with integer noise from the two-sided geometric distribution. The noise ZZ has Pr⁡[Z=d]∝α∣d∣\Pr[Z = d] \propto \alpha^{|d|} with α=e−ε\alpha = e^{-\varepsilon}, and the output is ε\varepsilon-differentially private for a query of sensitivity 1. It is the discrete analog of the Laplace mechanism, and it needs no real numbers, so an exact sampler is simple. Ghosh, Roughgarden and Sundararajan (2009) proved that, for one count, it is optimal for every user at the same time, after a post-processing step that depends on the user.

In plain words

You want to publish a count. One person can change the count by at most one. So you add a random whole number to it. Zero is the most likely value of the noise, and each step away from zero is less likely by the same factor. The published value is a whole number, which is natural for a count.

You can make the noise with a coin that has a known bias. Count how many times in a row the coin comes up heads, then do it again, and subtract the two counts. The result has the right shape. If you know the count is between two limits, you can move any output that is outside them to the nearest limit, and this costs no privacy.

The problem

The input is a dataset xx, an integer query ff with ∣f(x)−f(x′)∣≤1|f(x) - f(x')| \le 1 for all neighbors x∼x′x \sim x', and a number α∈(0,1)\alpha \in (0, 1). The output is an integer yy such that the map from xx to yy is ln⁡(1/α)\ln(1/\alpha)-DP and yy is close to f(x)f(x). With α=e−ε\alpha = e^{-\varepsilon}, the output is ε\varepsilon-DP. A count has sensitivity 1 under both neighbor relations: add/remove (one record added or removed) and replace (one record changed). Ghosh, Roughgarden and Sundararajan use replace neighbors, with nn fixed and f(x)∈{0,…,n}f(x) \in \{0, \ldots, n\}.

The two-sided geometric distribution with parameter α\alpha has

Pr⁡[Z=d]=1−α1+α α∣d∣(d∈Z),Pr⁡[∣Z∣≥t]=2αt1+α(t≥1).\Pr[Z = d] = \frac{1 - \alpha}{1 + \alpha}\, \alpha^{|d|} \quad (d \in \mathbb Z), \qquad \Pr[|Z| \ge t] = \frac{2\alpha^t}{1 + \alpha} \quad (t \ge 1).

It is the distribution of G1−G2G_1 - G_2 for two independent geometric variables with Pr⁡[G=j]=(1−α)αj\Pr[G = j] = (1 - \alpha)\alpha^j for j≥0j \ge 0. Its mean is 0 and its variance is 2α/(1−α)22\alpha/(1-\alpha)^2.

The algorithm

α\alpha is an exact fraction a/qa/q, so that each coin of lines L3 and L5 is exact. The bounds lolo and hihi are optional, and are used when the true value is known to be in [lo,hi][lo, hi].

  1. GEOMETRIC-MECHANISM(x, f, alpha, lo, hi) ▷ f has sensitivity 1, alpha = e^(-epsilon)
  2. 1v <- f(x)
  3. 2g1 <- 0
  4. 3while a coin with Pr[heads] = alpha is heads do g1 <- g1 + 1
  5. 4g2 <- 0
  6. 5while a coin with Pr[heads] = alpha is heads do g2 <- g2 + 1
  7. 6z <- v + g1 - g2
  8. 7if lo is given and z < lo then z <- lo
  9. 8if hi is given and z > hi then z <- hi
  10. 9return z

Line L1 is the only line that reads the data. Lines L2 and L3 draw G1G_1: the number of heads before the first tail. Lines L4 and L5 draw G2G_2 in the same way. Line L6 adds the two-sided geometric noise G1−G2G_1 - G_2. Lines L7 and L8 clamp the output to the known range, which gives the truncated geometric mechanism. A coin with Pr⁡[heads]=a/q\Pr[\text{heads}] = a/q is one uniform integer in {0,…,q−1}\{0, \ldots, q-1\} compared with aa.

The code uses a seeded generator so that the tests can repeat each run. A deployment needs a cryptographic source of randomness and an exact sampler (Mironov 2012; Canonne, Kamath and Steinke 2020). Canonne, Kamath and Steinke also give an exact sampler for α=e−ε\alpha = e^{-\varepsilon} when this number is not rational.

Example

Take ε=ln⁡2\varepsilon = \ln 2, so α=1/2\alpha = 1/2, and a count v=f(x)=4v = f(x) = 4 that is known to be in [0,6][0, 6]. Assume that the coins of line L3 are heads, tail, and the coins of line L5 are heads, heads, heads, tail.

step coin g1g_1 g2g_2 zz
L1, L2 0
L3 heads 1
L3 tail (stop) 1
L4 1 0
L5 heads, heads, heads 1 3
L5 tail (stop) 1 3
L6 4+1−3=24 + 1 - 3 = 2
L7, L8 2∈[0,6]2 \in [0, 6] 2

The output is 2. The noise −2-2 has probability 1/23/2⋅14=112\frac{1/2}{3/2} \cdot \frac14 = \frac{1}{12}. Noise 0 has probability 1/31/3, and Pr⁡[∣Z∣≥1]=2/3\Pr[|Z| \ge 1] = 2/3. With the clamp to [0,6][0, 6] and v=4v = 4, the exact output distribution is

yy 0 1 2 3 4 5 6
Pr⁡\Pr 1/24 1/24 1/12 1/6 1/3 1/6 1/6

The value 6 collects the whole upper tail: Pr⁡[Z≥2]=α2/(1+α)=1/6\Pr[Z \ge 2] = \alpha^2/(1+\alpha) = 1/6.

Correctness

Theorem (Ghosh, Roughgarden and Sundararajan 2009, Example 2.1). If ff is integer valued with sensitivity 1 under a neighbor relation, then GEOMETRIC-MECHANISM is ln⁡(1/α)\ln(1/\alpha)-DP under that relation, with or without the clamp.

The key fact is that G1−G2G_1 - G_2 has the pmf 1−α1+αα∣d∣\frac{1-\alpha}{1+\alpha}\alpha^{|d|}. So for neighbors with ∣f(x)−f(x′)∣≤1|f(x) - f(x')| \le 1, the ratio of the output probabilities at each integer yy is α∣y−f(x)∣−∣y−f(x′)∣≤α−1\alpha^{|y - f(x)| - |y - f(x')|} \le \alpha^{-1}. The clamp of lines L7 and L8 is a function of zz alone, so it keeps the bound by the post-processing theorem. The full proof is in the correctness proof of this page.

Accuracy. For an integer t≥1t \ge 1, Pr⁡[∣z−f(x)∣≥t]≤2αt/(1+α)\Pr[|z - f(x)| \ge t] \le 2\alpha^t / (1 + \alpha) without the clamp. The clamp never moves zz away from f(x)f(x) when f(x)∈[lo,hi]f(x) \in [lo, hi], so the bound holds with it too.

Proof: The geometric mechanism samples two-sided geometric noise and is ln(1/alpha)-DPfull

Fix α=a/q∈(0,1)\alpha = a/q \in (0, 1), a neighbor relation ∼\sim, and an integer query ff with ∣f(x)−f(x′)∣≤1|f(x) - f(x')| \le 1 for all x∼x′x \sim x'. Write c=(1−α)/(1+α)c = (1 - \alpha)/(1 + \alpha).

Lemma 1 (one loop). The value g1g_1 after line L3 has Pr⁡[g1=j]=(1−α)αj\Pr[g_1 = j] = (1 - \alpha)\alpha^j for j≥0j \ge 0, and the loop ends with probability 1. The same holds for g2g_2 after line L5, and g1g_1 and g2g_2 are independent.

Proof. Each coin is heads with probability exactly a/q=αa/q = \alpha, because it compares a uniform integer of {0,…,q−1}\{0, \ldots, q-1\} with aa, and the coins are independent. The loop of line L3 ends with g1=jg_1 = j exactly when the first jj coins are heads and coin j+1j + 1 is a tail. This has probability αj(1−α)\alpha^j(1 - \alpha). These probabilities sum to (1−α)∑j≥0αj=1(1-\alpha) \sum_{j \ge 0} \alpha^j = 1, so the loop ends with probability 1. Line L5 uses fresh coins, so g2g_2 has the same law and is independent of g1g_1. □\square

Lemma 2 (the noise). Z=g1−g2Z = g_1 - g_2 has Pr⁡[Z=d]=c α∣d∣\Pr[Z = d] = c\,\alpha^{|d|} for every integer dd.

Proof. Let d≥0d \ge 0. By Lemma 1 and independence,

Pr⁡[Z=d]=∑j≥0Pr⁡[g2=j]Pr⁡[g1=j+d]=(1−α)2αd∑j≥0α2j=(1−α)2αd1−α2=c αd.\Pr[Z = d] = \sum_{j \ge 0} \Pr[g_2 = j] \Pr[g_1 = j + d] = (1-\alpha)^2 \alpha^d \sum_{j \ge 0} \alpha^{2j} = \frac{(1-\alpha)^2 \alpha^d}{1 - \alpha^2} = c\,\alpha^d.

For d<0d < 0, swap the roles of g1g_1 and g2g_2; the two have the same law, so Pr⁡[Z=d]=Pr⁡[Z=−d]=c α∣d∣\Pr[Z = d] = \Pr[Z = -d] = c\,\alpha^{|d|}. □\square

Theorem 1 (privacy without the clamp). Let M(x)=f(x)+ZM(x) = f(x) + Z be the output of line L6. For all x∼x′x \sim x' and every set S⊆ZS \subseteq \mathbb Z, Pr⁡[M(x)∈S]≤α−1Pr⁡[M(x′)∈S]\Pr[M(x) \in S] \le \alpha^{-1} \Pr[M(x') \in S].

Proof. By Lemma 2, Pr⁡[M(x)=y]=c α∣y−f(x)∣\Pr[M(x) = y] = c\,\alpha^{|y - f(x)|} for every integer yy. Let u=f(x)u = f(x) and u′=f(x′)u' = f(x'), with ∣u−u′∣≤1|u - u'| \le 1. By the triangle inequality, ∣y−u′∣≤∣y−u∣+∣u−u′∣≤∣y−u∣+1|y - u'| \le |y - u| + |u - u'| \le |y - u| + 1. So

Pr⁡[M(x)=y]Pr⁡[M(x′)=y]=α∣y−u∣−∣y−u′∣≤α−1,\frac{\Pr[M(x) = y]}{\Pr[M(x') = y]} = \alpha^{|y - u| - |y - u'|} \le \alpha^{-1},

where the inequality uses α<1\alpha < 1 and ∣y−u∣−∣y−u′∣≥−1|y - u| - |y - u'| \ge -1. Both probabilities are positive. Sum Pr⁡[M(x)=y]≤α−1Pr⁡[M(x′)=y]\Pr[M(x) = y] \le \alpha^{-1} \Pr[M(x') = y] over y∈Sy \in S. The relation is symmetric, so the same bound holds with xx and x′x' swapped. □\square

Theorem 2 (privacy with the clamp). The output of line L9 is ln⁡(1/α)\ln(1/\alpha)-DP for fixed bounds lo≤hilo \le hi that do not depend on the data.

Proof. Lines L7 and L8 compute h(z)=min⁡(max⁡(z,lo),hi)h(z) = \min(\max(z, lo), hi), a fixed function of zz alone (with lo=−∞lo = -\infty or hi=+∞hi = +\infty when a bound is not given). For a set TT of outputs, Pr⁡[h(M(x))∈T]=Pr⁡[M(x)∈h−1(T)]\Pr[h(M(x)) \in T] = \Pr[M(x) \in h^{-1}(T)]. Theorem 1 with S=h−1(T)S = h^{-1}(T) gives Pr⁡[h(M(x))∈T]≤α−1Pr⁡[M(x′)∈h−1(T)]=α−1Pr⁡[h(M(x′))∈T]\Pr[h(M(x)) \in T] \le \alpha^{-1} \Pr[M(x') \in h^{-1}(T)] = \alpha^{-1} \Pr[h(M(x')) \in T]. □\square

Lemma 3 (the truncated pmf). If lo<hilo < hi and lo≤v=f(x)≤hilo \le v = f(x) \le hi, the output of line L9 has Pr⁡[lo]=αv−lo/(1+α)\Pr[lo] = \alpha^{v - lo}/(1 + \alpha), Pr⁡[hi]=αhi−v/(1+α)\Pr[hi] = \alpha^{hi - v}/(1 + \alpha), and Pr⁡[y]=c α∣y−v∣\Pr[y] = c\,\alpha^{|y - v|} for lo<y<hilo < y < hi.

Proof. For lo<y<hilo < y < hi, h(z)=yh(z) = y only for z=yz = y, so Lemma 2 gives the value. The end point lolo collects all z≤loz \le lo, that is Z≤−(v−lo)Z \le -(v - lo). For t≥0t \ge 0, Pr⁡[Z≤−t]=c∑d≥tαd=c αt/(1−α)=αt/(1+α)\Pr[Z \le -t] = c \sum_{d \ge t} \alpha^d = c\,\alpha^t/(1-\alpha) = \alpha^t/(1+\alpha). The same sum gives Pr⁡[hi]\Pr[hi]. □\square

Accuracy. For an integer t≥1t \ge 1, Pr⁡[∣Z∣≥t]=2c αt/(1−α)=2αt/(1+α)\Pr[|Z| \ge t] = 2 c\,\alpha^t/(1 - \alpha) = 2\alpha^t/(1+\alpha) by the sum in the proof of Lemma 3. If lo≤v≤hilo \le v \le hi, then ∣h(z)−v∣≤∣z−v∣|h(z) - v| \le |z - v|, so the clamp keeps the bound.

Lemma 1 shows termination with probability 1, Lemma 2 the law of the noise, and Theorems 1 and 2 the privacy, with and without the clamp. ■\blacksquare

Complexity

The model is the word RAM: a uniform integer in {0,…,q−1}\{0, \ldots, q-1\} and each arithmetic step on words cost one unit.

  • Time. Lines L3 and L5 each run one coin more than the value they count. So the number of coins is G1+G2+2G_1 + G_2 + 2, with expected value 2α/(1−α)+2=2/(1−α)2\alpha/(1-\alpha) + 2 = 2/(1-\alpha). With α=e−ε\alpha = e^{-\varepsilon}, 1−α≥ε/(1+ε)1 - \alpha \ge \varepsilon/(1+\varepsilon), so the expected time is O(1+1/ε)O(1 + 1/\varepsilon). There is no worst-case bound: each loop can run for any number of steps, with a probability that falls geometrically.
  • Space. Two counters and the output: O(1)O(1) words.

Properties

  • Pure privacy, exact. The output is exactly ln⁡(1/α)\ln(1/\alpha)-DP, and the bound is tight. The tests check this with exact fractions over all datasets of up to 5 records, under both neighbor relations, and check that ln⁡(1/α)−0.01\ln(1/\alpha) - 0.01 fails.
  • Integer output. No rounding of a real number is needed, and all probabilities are rational when α\alpha is rational.
  • Unbiased without the clamp. E[z]=f(x)\mathbb E[z] = f(x), Var[z]=2α/(1−α)2\mathrm{Var}[z] = 2\alpha/(1-\alpha)^2 and E∣z−f(x)∣=2α/(1−α2)\mathbb E|z - f(x)| = 2\alpha/(1 - \alpha^2). With the clamp, the output is biased near the ends of the range, but its error is never larger.
  • Universally utility maximizing. For one count query with f(x)∈{0,…,n}f(x) \in \{0, \ldots, n\} under replace neighbors, consider any user with a prior on the true count and a loss that is nondecreasing in ∣y−f(x)∣|y - f(x)|. Among all ε\varepsilon-DP mechanisms, the best one for this user is the truncated geometric mechanism followed by a remap of its output that depends only on the user (GRS Theorem 3.2 and Corollary 3.3). This is a theorem about one count. It does not hold for general query classes.

Variants and improvements

  • Sensitivity s>1s > 1. Use α=e−ε/s\alpha = e^{-\varepsilon/s}. Then the output is ε\varepsilon-DP. The tests check that a sensitivity-2 query with α=1/4\alpha = 1/4 is ln⁡16\ln 16-DP and not ln⁡4\ln 4-DP, so the parameter must change with ss.
  • Several counts. Add independent geometric noise to each coordinate, with α=e−ε/Δ1\alpha = e^{-\varepsilon/\Delta_1}, where Δ1\Delta_1 is the ℓ1\ell_1 sensitivity of the vector. A histogram under add/remove has Δ1=1\Delta_1 = 1.
  • Discrete Gaussian. The discrete Gaussian mechanism is the integer analog of the Gaussian mechanism, for (ε,δ)(\varepsilon, \delta)-DP and better composition.
  • Exact samplers for any ε\varepsilon. When e−εe^{-\varepsilon} is not rational, Canonne, Kamath and Steinke (2020) sample Bernoulli(e−γ)(e^{-\gamma}) exactly with rational coins, and from it the discrete Laplace distribution.
  • Bit flip on one bit. For a count of 0 or 1, the truncated mechanism on [0,1][0, 1] is randomized response with p=1/(1+α)p = 1/(1 + \alpha).

When to use it

Use the geometric mechanism for counts and other integer queries of low sensitivity, when you want integer output with exact sampling and pure ε\varepsilon-DP. It has the same accuracy as the Laplace mechanism up to rounding, and it avoids the float problems of continuous noise. If you answer many counts and can accept a small δ\delta, the discrete Gaussian mechanism adds less noise per count. If you know the range of the count, clamp the output, because the clamp is free.

Pitfalls

  • The wrong parameter for a larger sensitivity. Line L3 with α=e−ε\alpha = e^{-\varepsilon} on a query of sensitivity 2 is only 2ε2\varepsilon-DP. The coins of lines L3 and L5 must use α=e−ε/s\alpha = e^{-\varepsilon/s} for sensitivity ss.
  • One-sided noise. Line L6 written as z←v+g1z \leftarrow v + g_1, with only one geometric variable, is not private at all: the output is never below vv, so for neighbors with f(x′)=f(x)+1f(x') = f(x) + 1 the output f(x)f(x) has probability 0 under x′x'. Line L6 must subtract the second variable, z←v+g1−g2z \leftarrow v + g_1 - g_2.
  • A clamp to a range that depends on the data. Lines L7 and L8 with lolo or hihi computed from xx, such as the true minimum of a column, are not post-processing, and they leak. The bounds must be fixed before the data is seen, for example [0,n][0, n] for a count with public nn.
  • A float coin. Lines L3 and L5 with "random float < alpha" make each coin slightly wrong. Use a uniform integer and the exact fraction a/qa/q, or the exact samplers of Canonne, Kamath and Steinke.

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
geometric_mechanism.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometric-mechanism/. The authors are listed in prov/12JV5Q.jsonl.
"""The two-sided geometric mechanism of Ghosh, Roughgarden and Sundararajan.

The noise Z = G1 - G2 is the difference of two independent geometric
variables with P(G = k) = (1 - alpha) alpha^k, so that
P(Z = d) = (1 - alpha) / (1 + alpha) alpha^|d|. With alpha = e^(-epsilon)
and an integer query of sensitivity 1, the output is epsilon-DP.

alpha is an exact rational in (0, 1), so every coin is exact and no float
is used on the sampling path. random.Random is used only so that the tests
are reproducible; a deployment needs a cryptographic source of randomness.
"""

from __future__ import annotations

import random
from fractions import Fraction
from typing import Callable, Optional, TypeVar, Union

Rational = Union[int, Fraction]
X = TypeVar("X")


def _check_alpha(alpha: Rational) -> Fraction:
    a = Fraction(alpha)
    if not 0 < a < 1:
        raise ValueError("alpha must be in (0, 1)")
    return a


def bernoulli(alpha: Fraction, rng: random.Random) -> bool:
    """True with probability exactly alpha. Cost: one uniform draw from {0, ..., den - 1}."""
    return rng.randrange(alpha.denominator) < alpha.numerator


def geometric_mechanism(
    x: X,
    f: Callable[[X], int],
    alpha: Rational,
    rng: random.Random,
    lo: Optional[int] = None,
    hi: Optional[int] = None,
) -> int:
    """Return f(x) + G1 - G2, clamped to [lo, hi] when the bounds are given.

    Precondition: f is integer valued with sensitivity 1 under the chosen
    neighbor relation, 0 < alpha < 1, and lo <= hi when both are given.
    The output is ln(1 / alpha)-DP; for sensitivity s, pass alpha = e^(-epsilon / s).
    Cost: expected 2 / (1 - alpha) Bernoulli draws and O(1) other word operations.
    """
    a = _check_alpha(alpha)
    if lo is not None and hi is not None and lo > hi:
        raise ValueError("need lo <= hi")
    v = f(x)  # @line L1
    g1 = 0  # @line L2
    while bernoulli(a, rng):  # @line L3
        g1 += 1
    g2 = 0  # @line L4
    while bernoulli(a, rng):  # @line L5
        g2 += 1
    z = v + g1 - g2  # @line L6
    if lo is not None and z < lo:  # @line L7
        z = lo
    if hi is not None and z > hi:  # @line L8
        z = hi
    return z  # @line L9


def noise_pmf(d: int, alpha: Rational) -> Fraction:
    """P(Z = d) = (1 - alpha) / (1 + alpha) alpha^|d| for the untruncated noise."""
    a = _check_alpha(alpha)
    return (1 - a) / (1 + a) * a ** abs(d)


def noise_tail(t: int, alpha: Rational) -> Fraction:
    """P(|Z| >= t) = 2 alpha^t / (1 + alpha) for an integer t >= 1."""
    a = _check_alpha(alpha)
    if t < 1:
        raise ValueError("need t >= 1")
    return 2 * a ** t / (1 + a)


def truncated_pmf(v: int, alpha: Rational, lo: int, hi: int) -> dict[int, Fraction]:
    """The exact pmf of the clamped output on {lo, ..., hi} when the true value is v.

    Precondition: lo <= v <= hi. The end points collect the tails:
    P(lo) = alpha^(v - lo) / (1 + alpha) and P(hi) = alpha^(hi - v) / (1 + alpha).
    If lo = hi, the output is lo with probability 1. Cost: O(hi - lo) exact operations.
    """
    a = _check_alpha(alpha)
    if not lo <= v <= hi:
        raise ValueError("need lo <= v <= hi")
    if lo == hi:
        return {lo: Fraction(1)}
    out = {z: (1 - a) / (1 + a) * a ** abs(z - v) for z in range(lo + 1, hi)}
    out[lo] = a ** (v - lo) / (1 + a)
    out[hi] = a ** (hi - v) / (1 + a)
    return out
test_geometric_mechanism.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometric-mechanism/. The authors are listed in prov/12JV5Q.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

import dpkit
from geometric_mechanism import geometric_mechanism, noise_pmf, noise_tail, truncated_pmf

UNIVERSE = (0, 1)


def count_ones(x):
    return sum(x)


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


def convolution_pmf(d, alpha, terms=400):
    """P(G1 - G2 = d) by a direct sum over G2 = k, with G1 = k + d. Float oracle."""
    a = float(alpha)
    total = 0.0
    for k in range(terms):
        j = k + d
        if j >= 0:
            total += (1 - a) * a ** j * (1 - a) * a ** k
    return total


def test_check_values():
    alpha = Fraction(1, 2)  # epsilon = ln 2
    assert noise_pmf(0, alpha) == Fraction(1, 3)
    assert noise_pmf(1, alpha) == Fraction(1, 6)
    assert noise_pmf(-2, alpha) == Fraction(1, 12)
    assert noise_tail(1, alpha) == Fraction(2, 3)
    assert abs(math.log(1 / alpha) - math.log(2)) < 1e-15


def test_closed_form_matches_convolution():
    rng = random.Random(5)
    for _ in range(500):
        alpha = Fraction(rng.randint(1, 9), 10)
        d = rng.randint(-8, 8)
        assert abs(float(noise_pmf(d, alpha)) - convolution_pmf(d, alpha)) < 1e-12


def test_noise_pmf_and_tail_are_consistent():
    rng = random.Random(6)
    for _ in range(500):
        alpha = Fraction(rng.randint(1, 30), 31)
        t = rng.randint(1, 10)
        inside = sum(noise_pmf(d, alpha) for d in range(-(t - 1), t))
        assert inside + noise_tail(t, alpha) == 1


def test_truncated_pmf_matches_clamp_of_noise():
    rng = random.Random(8)
    for _ in range(500):
        alpha = Fraction(rng.randint(1, 9), 10)
        lo = rng.randint(-3, 3)
        hi = lo + rng.randint(0, 6)
        v = rng.randint(lo, hi)
        got = truncated_pmf(v, alpha, lo, hi)
        assert sum(got.values()) == 1
        # Oracle: clamp the untruncated noise; the tails are geometric series.
        want = {}
        for z in range(lo, hi + 1):
            want[z] = noise_pmf(z - v, alpha)
        if lo < hi:
            a = alpha
            want[lo] += (1 - a) / (1 + a) * a ** (v - lo + 1) / (1 - a)
            want[hi] += (1 - a) / (1 + a) * a ** (hi - v + 1) / (1 - a)
        else:
            want = {lo: Fraction(1)}
        assert got == want


def test_counting_query_is_exactly_ln_inverse_alpha_dp():
    for alpha in (Fraction(1, 2), Fraction(1, 3), Fraction(4, 5)):
        eps = math.log(1 / alpha)
        lo, hi = 0, 6
        mech = lambda x: truncated_pmf(count_ones(x), alpha, lo, hi)
        add_remove = [(x, y) for x in all_datasets(5) for y in dpkit.neighbors_add_remove(x, UNIVERSE)]
        replace = [(x, y) for x in all_datasets(5) for y in dpkit.neighbors_replace(x, UNIVERSE)]
        for pairs in (add_remove, replace):
            assert dpkit.is_pure_dp(mech, pairs, eps)
            assert not dpkit.is_pure_dp(mech, pairs, eps - 0.01)


def test_sensitivity_two_needs_square_root_of_alpha():
    # A query of sensitivity 2 with alpha = 1/4 costs 2 ln 4 = ln 16, not ln 4.
    lo, hi = -2, 12
    double = lambda x: truncated_pmf(2 * count_ones(x), Fraction(1, 4), lo, hi)
    pairs = [(x, y) for x in all_datasets(5) for y in dpkit.neighbors_add_remove(x, UNIVERSE)]
    assert dpkit.is_pure_dp(double, pairs, math.log(16))
    assert not dpkit.is_pure_dp(double, pairs, math.log(4))


def test_sampler_matches_pmf():
    rng = random.Random(77)
    n = 2000
    beta = 1e-6
    for alpha in (Fraction(1, 2), Fraction(9, 10)):
        x = (1, 0, 1, 1)
        samples = [geometric_mechanism(x, count_ones, alpha, rng) for _ in range(n)]
        emp = dpkit.empirical_pmf(samples)
        t = dpkit.hoeffding_margin(n, beta / 41)
        for z in range(3 - 20, 3 + 21):
            assert abs(emp.get(z, 0.0) - float(noise_pmf(z - 3, alpha))) <= t
        clamped = [geometric_mechanism(x, count_ones, alpha, rng, 0, 4) for _ in range(n)]
        emp = dpkit.empirical_pmf(clamped)
        want = truncated_pmf(3, alpha, 0, 4)
        t = dpkit.hoeffding_margin(n, beta / 5)
        assert set(emp) <= set(want)
        for z, pr in want.items():
            assert abs(emp.get(z, 0.0) - float(pr)) <= t


def test_mean_absolute_error_matches_closed_form():
    # E|Z| = 2 alpha / (1 - alpha^2), from the sum over d of |d| P(Z = d).
    for alpha in (Fraction(1, 2), Fraction(2, 3)):
        partial = sum(abs(d) * noise_pmf(d, alpha) for d in range(-200, 201))
        assert abs(float(partial) - float(2 * alpha / (1 - alpha ** 2))) < 1e-12


def test_edge_cases():
    rng = random.Random(1)
    with pytest.raises(ValueError):
        geometric_mechanism((), count_ones, 1, rng)
    with pytest.raises(ValueError):
        geometric_mechanism((), count_ones, 0, rng)
    with pytest.raises(ValueError):
        geometric_mechanism((), count_ones, Fraction(1, 2), rng, 3, 2)
    with pytest.raises(ValueError):
        truncated_pmf(5, Fraction(1, 2), 0, 4)
    with pytest.raises(ValueError):
        noise_tail(0, Fraction(1, 2))
    assert truncated_pmf(0, Fraction(1, 2), 0, 0) == {0: 1}
    assert geometric_mechanism((), count_ones, Fraction(1, 2), rng, 0, 0) == 0
    assert all(0 <= geometric_mechanism((1, 1), count_ones, Fraction(1, 2), rng, 0, 2) <= 2 for _ in range(200))

History

Ghosh, Roughgarden and Sundararajan introduced the geometric mechanism and its truncated form at STOC 2009, with the journal version in SIAM Journal on Computing in 2012. Their main result is that one mechanism is optimal for all users of a count, each with its own prior and loss, after a remap by the user. The discrete Laplace distribution itself is older, and the discrete Gaussian of Canonne, Kamath and Steinke (2020) is its Gaussian counterpart.

References

  1. Arpita Ghosh, Tim Roughgarden and Mukund Sundararajan, Universally utility-maximizing privacy mechanisms, SIAM Journal on Computing 41(6), 2012, pages 1673 to 1693, Example 2.1 (the geometric mechanism), Example 2.2 (the truncated geometric mechanism), Theorem 3.2 (the main characterization) and Corollary 3.3 (universal utility maximization)
  2. Arpita Ghosh, Tim Roughgarden and Mukund Sundararajan, Universally utility-maximizing privacy mechanisms, STOC 2009, pages 351 to 360, the conference version of the same results
  3. 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, the Laplace mechanism, of which this is the discrete analog
  4. Clement L. Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, the exact samplers for discrete Laplace noise with an irrational parameter
  5. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why a deployment needs exact samplers

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.expected
  • 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