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
- Model
- Word RAM
- Properties
- randomizedexactrandomized
- Evidence
- Proof sketchCode in 1 languages
- 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 has with , and the output is -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 , an integer query with for all neighbors , and a number . The output is an integer such that the map from to is -DP and is close to . With , the output is -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 fixed and .
The two-sided geometric distribution with parameter has
It is the distribution of for two independent geometric variables with for . Its mean is 0 and its variance is .
The algorithm
is an exact fraction , so that each coin of lines L3 and L5 is exact. The bounds and are optional, and are used when the true value is known to be in .
GEOMETRIC-MECHANISM(x, f, alpha, lo, hi) ▷ f has sensitivity 1, alpha = e^(-epsilon)- 1
v <- f(x) - 2
g1 <- 0 - 3
while a coin with Pr[heads] = alpha is heads do g1 <- g1 + 1 - 4
g2 <- 0 - 5
while a coin with Pr[heads] = alpha is heads do g2 <- g2 + 1 - 6
z <- v + g1 - g2 - 7
if lo is given and z < lo then z <- lo - 8
if hi is given and z > hi then z <- hi - 9
return z
Line L1 is the only line that reads the data. Lines L2 and L3 draw : the number of heads before the first tail. Lines L4 and L5 draw in the same way. Line L6 adds the two-sided geometric noise . Lines L7 and L8 clamp the output to the known range, which gives the truncated geometric mechanism. A coin with is one uniform integer in compared with .
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 when this number is not rational.
Example
Take , so , and a count that is known to be in . Assume that the coins of line L3 are heads, tail, and the coins of line L5 are heads, heads, heads, tail.
| step | coin | |||
|---|---|---|---|---|
| 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 | ||||
| L7, L8 | 2 |
The output is 2. The noise has probability . Noise 0 has probability , and . With the clamp to and , the exact output distribution is
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| 1/24 | 1/24 | 1/12 | 1/6 | 1/3 | 1/6 | 1/6 |
The value 6 collects the whole upper tail: .
Correctness
Theorem (Ghosh, Roughgarden and Sundararajan 2009, Example 2.1). If is integer valued with sensitivity 1 under a neighbor relation, then GEOMETRIC-MECHANISM is -DP under that relation, with or without the clamp.
The key fact is that has the pmf . So for neighbors with , the ratio of the output probabilities at each integer is . The clamp of lines L7 and L8 is a function of 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 , without the clamp. The clamp never moves away from when , so the bound holds with it too.
Proof: The geometric mechanism samples two-sided geometric noise and is ln(1/alpha)-DPfull
Fix , a neighbor relation , and an integer query with for all . Write .
Lemma 1 (one loop). The value after line L3 has for , and the loop ends with probability 1. The same holds for after line L5, and and are independent.
Proof. Each coin is heads with probability exactly , because it compares a uniform integer of with , and the coins are independent. The loop of line L3 ends with exactly when the first coins are heads and coin is a tail. This has probability . These probabilities sum to , so the loop ends with probability 1. Line L5 uses fresh coins, so has the same law and is independent of .
Lemma 2 (the noise). has for every integer .
Proof. Let . By Lemma 1 and independence,
For , swap the roles of and ; the two have the same law, so .
Theorem 1 (privacy without the clamp). Let be the output of line L6. For all and every set , .
Proof. By Lemma 2, for every integer . Let and , with . By the triangle inequality, . So
where the inequality uses and . Both probabilities are positive. Sum over . The relation is symmetric, so the same bound holds with and swapped.
Theorem 2 (privacy with the clamp). The output of line L9 is -DP for fixed bounds that do not depend on the data.
Proof. Lines L7 and L8 compute , a fixed function of alone (with or when a bound is not given). For a set of outputs, . Theorem 1 with gives .
Lemma 3 (the truncated pmf). If and , the output of line L9 has , , and for .
Proof. For , only for , so Lemma 2 gives the value. The end point collects all , that is . For , . The same sum gives .
Accuracy. For an integer , by the sum in the proof of Lemma 3. If , then , 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.
Complexity
The model is the word RAM: a uniform integer in 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 , with expected value . With , , so the expected time is . 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: words.
Properties
- Pure privacy, exact. The output is exactly -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 fails.
- Integer output. No rounding of a real number is needed, and all probabilities are rational when is rational.
- Unbiased without the clamp. , and . 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 under replace neighbors, consider any user with a prior on the true count and a loss that is nondecreasing in . Among all -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 . Use . Then the output is -DP. The tests check that a sensitivity-2 query with is -DP and not -DP, so the parameter must change with .
- Several counts. Add independent geometric noise to each coordinate, with , where is the sensitivity of the vector. A histogram under add/remove has .
- Discrete Gaussian. The discrete Gaussian mechanism is the integer analog of the Gaussian mechanism, for -DP and better composition.
- Exact samplers for any . When is not rational, Canonne, Kamath and Steinke (2020) sample Bernoulli 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 is randomized response with .
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 -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 , 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 on a query of sensitivity 2 is only -DP. The coins of lines L3 and L5 must use for sensitivity .
- One-sided noise. Line L6 written as , with only one geometric variable, is not private at all: the output is never below , so for neighbors with the output has probability 0 under . Line L6 must subtract the second variable, .
- A clamp to a range that depends on the data. Lines L7 and L8 with or computed from , 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 for a count with public .
- A float coin. Lines L3 and L5 with "random float < alpha" make each coin slightly wrong. Use a uniform integer and the exact fraction , 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.
# 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
- 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)
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 12JV5Q Edit this page History Report an error Markdown