Algorithm Search⌘K

Algorithmadvanced

Smooth sensitivity framework

Also called Nissim-Raskhodnikova-Smith smooth sensitivity.

Adds noise scaled to a smooth upper bound on the local sensitivity at the actual dataset. For the median this is often far less noise than the global sensitivity needs.

Time
O(n^2) worst
Space
O(n) extra
Where
n = the number of values
Origin
Kobbi Nissim, Sofya Raskhodnikova, Adam Smith, 2007

The smooth sensitivity framework adds noise that fits the actual dataset and not the worst case. The global sensitivity of the median of values in [0,Λ][0, \Lambda] is Λ\Lambda, so the Laplace mechanism must add noise of scale Λ/ε\Lambda/\varepsilon, even when the data is dense near the median. The local sensitivity at xx is often tiny, but noise scaled to it leaks the data, because the scale itself then tells about xx. Nissim, Raskhodnikova and Smith fix this with the β\beta-smooth sensitivity S∗(x)=max⁡ye−βd(x,y)LS(y)S^*(x) = \max_y e^{-\beta d(x,y)} LS(y): the largest local sensitivity near xx, with a discount that falls with the distance. Noise of scale S∗(x)/εS^*(x)/\varepsilon from a suitable law is then private.

In plain words

You want to release the middle value of a list of numbers, and you must hide each number. The safe rule for any list adds noise as large as the whole range, because for some lists one change moves the middle value from one end to the other.

For most lists, one change moves the middle value only a little. But a list that is close to a risky list could still be a risk, so the method looks at the lists that are a few changes away. It takes the largest movement among them, made smaller the farther away the list is. This number changes only slowly from one list to the next. Noise of that size, from a law with heavy tails, hides each number.

The problem

A dataset is a list xx of nn values in [0,Λ][0, \Lambda], with nn odd and Λ\Lambda public. Two datasets are neighbors if one value is replaced by another (replace), so nn is fixed. The distance d(x,y)d(x, y) is the number of replacements from xx to yy. The median is f(x)=xmf(x) = x_m with m=(n+1)/2m = (n+1)/2 in sorted order. The local sensitivity is LS(y)=max⁡d(y,y′)=1∣f(y)−f(y′)∣LS(y) = \max_{d(y,y')=1} |f(y) - f(y')|, and the global sensitivity is max⁡yLS(y)=Λ\max_y LS(y) = \Lambda. The goal is an ε\varepsilon-DP estimate of xmx_m whose error follows the local shape of xx.

Notation: Lap(b)\mathrm{Lap}(b) has the density (1/(2b))e−∣z∣/b(1/(2b))e^{-|z|/b}, the variance 2b22b^2 and P(∣Z∣>t)=e−t/bP(|Z| > t) = e^{-t/b}. The standard Cauchy law has the density 1/(π(1+z2))1/(\pi(1+z^2)) and P(∣Z∣≤1)=1/2P(|Z| \le 1) = 1/2.

The algorithm

Sort xx, and set xi=0x_i = 0 for i≤0i \le 0 and xi=Λx_i = \Lambda for i>ni > n. Lines L1 to L3 are the closed form of NRS Proposition 3.4, and line L4 is the Cauchy release of NRS Corollary 2.4 with γ=2\gamma = 2.

  1. SMOOTH-MEDIAN(x₁ ≤ ... ≤ xₙ, Λ, ε)
  2. 1for k ← 0 to n do ▷ β = ε/6 and S = 0 at the start
  3. 2A_k ← max_{0 ≤ t ≤ k+1} (x_{m+t} − x_{m+t−k−1}) ▷ the largest local sensitivity within k changes
  4. 3S ← max(S, e^{−kβ} · A_k) ▷ the discount for the distance
  5. 4output x_m + (6S/ε) · Z, with Z standard Cauchy

Line L2 is A(k,x)=max⁡d(x,y)≤kLS(y)A(k, x) = \max_{d(x,y) \le k} LS(y). To move the median by a lot with kk changes, take a run of k+1k+1 consecutive gaps that contains the median and move the kk values inside it out of it. The padding with 0 and Λ\Lambda covers runs that reach an end of the range. Line L3 takes the maximum over kk of the discounted value, which is S∗(x)S^*(x). For k≥nk \ge n the value AkA_k is Λ\Lambda, so the loop can stop at nn. Line L4 adds noise of scale 6S∗/ε6S^*/\varepsilon. For (ε,δ)(\varepsilon, \delta)-DP, use β=ε/(2ln⁡(2/δ))\beta = \varepsilon/(2\ln(2/\delta)) and the noise (2S∗/ε)⋅Lap(1)(2S^*/\varepsilon) \cdot \mathrm{Lap}(1) in line L4.

Example

Take n=101n = 101 values 0,1,2,…,1000, 1, 2, \dots, 100, with Λ=100\Lambda = 100 and ε=1\varepsilon = 1, so β=1/6\beta = 1/6 and the median is 50. Each gap is 1, so Ak=k+1A_k = k + 1 until a run reaches an end. From the code:

kk AkA_k e−k/6Ake^{-k/6} A_k
0 1 1.000
1 2 1.693
2 3 2.150
3 4 2.426
4 5 2.567
5 6 2.608
6 7 2.575
8 9 2.372
50 51 0.012

So S∗=6e−5/6≈2.61S^* = 6e^{-5/6} \approx 2.61, and line L4 adds Cauchy noise of scale 15.6. The median absolute error of Cauchy noise is its scale, 15.6. The Laplace mechanism with the global sensitivity 100 needs Lap(100)\mathrm{Lap}(100), with the median absolute error 100ln⁡2≈69.3100 \ln 2 \approx 69.3. The (ε,δ)(\varepsilon, \delta) form with δ=10−6\delta = 10^{-6} has β≈0.0345\beta \approx 0.0345, S∗≈11.05S^* \approx 11.05 and Lap(22.1)\mathrm{Lap}(22.1) noise, with the median absolute error 15.3 and light tails. These are exact values of the noise laws (a theorem), not a measurement.

Correctness

The closed form (NRS Proposition 3.4, a theorem). Lines L1 to L3 compute S∗(x)S^*(x). One change moves the median by at most one position, so LS(y)=max⁡(ym−ym−1,ym+1−ym)LS(y) = \max(y_m - y_{m-1}, y_{m+1} - y_m). Within kk changes the widest gap that can sit at the median spans k+1k+1 consecutive gaps of xx, which is line L2. The test file checks lines L1 to L3 against the definition by brute force on every dataset of the grid {0,…,Λ}n\{0, \dots, \Lambda\}^n for n≤5n \le 5 and Λ≤4\Lambda \le 4.

A smooth bound (a theorem). S∗(x)≥LS(x)S^*(x) \ge LS(x), and S∗(x)≤eβS∗(x′)S^*(x) \le e^{\beta} S^*(x') for neighbors, by the triangle inequality for dd.

Privacy (NRS Lemma 2.3 and Corollary 2.4, a theorem). Between neighbors the center moves by at most LS(x)≤S∗(x)LS(x) \le S^*(x), which is ε/6\varepsilon/6 in units of the scale, and the scale changes by a factor at most eε/6e^{\varepsilon/6}. The Cauchy log density has slope at most 1, and a change of scale by eλe^{\lambda} changes it by at most 3∣λ∣3|\lambda|. So the log density ratio is at most ε/6+ε/2<ε\varepsilon/6 + \varepsilon/2 < \varepsilon at every output. Laplace noise does not have this property for a change of scale at large ∣z∣|z|, which is why it gives only (ε,δ)(\varepsilon, \delta)-DP.

The proofs are in proofs/correctness.md. The Laplace case there is a sketch with the locator in NRS.

Proof: The smooth sensitivity of the median has a closed form, and noise scaled to it gives differential privacypartial

We use the pseudocode of the page. A dataset is a list xx of nn values in [0,Λ][0, \Lambda], with nn odd and m=(n+1)/2m = (n+1)/2. We sort it as x1≤⋯≤xnx_1 \le \dots \le x_n and set xi=0x_i = 0 for i≤0i \le 0 and xi=Λx_i = \Lambda for i>ni > n. Two datasets are neighbors if one value is replaced by another, and d(x,y)d(x, y) is the number of replacements that turn xx into yy. The median is f(x)=xmf(x) = x_m. The local sensitivity is LS(y)=max⁡y′:d(y,y′)=1∣f(y)−f(y′)∣LS(y) = \max_{y' : d(y, y') = 1} |f(y) - f(y')|, and the β\beta-smooth sensitivity is S∗(x)=max⁡ye−βd(x,y)LS(y)S^*(x) = \max_y e^{-\beta d(x, y)} LS(y) (NRS Definition 2.2).

Claim 1 (local sensitivity). LS(x)=max⁡(xm−xm−1,xm+1−xm)LS(x) = \max(x_m - x_{m-1}, x_{m+1} - x_m).

Proof. One replacement moves at most one value across the median, so the new median is one of xm−1,xm,xm+1x_{m-1}, x_m, x_{m+1}. Replacing a value at or above position mm by 0 gives the median xm−1x_{m-1}, and replacing a value at or below position mm by Λ\Lambda gives xm+1x_{m+1}. □\square

Claim 2 (the ball, NRS Proposition 3.4). Let A(k,x)=max⁡y:d(x,y)≤kLS(y)A(k, x) = \max_{y : d(x, y) \le k} LS(y). Then A(k,x)=max⁡0≤t≤k+1(xm+t−xm+t−k−1)A(k, x) = \max_{0 \le t \le k+1} (x_{m+t} - x_{m+t-k-1}).

Proof. Upper bound. Let d(x,y)≤kd(x, y) \le k, so yy is xx with at most kk values removed and the same number added. Sort yy. By Claim 1, LS(y)LS(y) is ym+1−ymy_{m+1} - y_m or ym−ym−1y_m - y_{m-1}. Take g=ym+1−ym>0g = y_{m+1} - y_m > 0 (if g=0g = 0 there is nothing to prove). Let p=max⁡{i≥0:xi≤ym}p = \max\{i \ge 0 : x_i \le y_m\} and q=min⁡{i≤n+1:xi≥ym+1}q = \min\{i \le n+1 : x_i \ge y_{m+1}\}, with the padding. The values of xx with indices p+1,…,q−1p+1, \dots, q-1 lie strictly between ymy_m and ym+1y_{m+1}, and yy has no value there, so they were all removed: q−p≤k+1q - p \le k + 1. At least mm values of yy are at most ymy_m, and they are kept values of xx with index at most pp or added values, so m≤p+km \le p + k. At least n−mn - m values of yy are at least ym+1y_{m+1}, so in the same way n−m≤(n−q+1)+kn - m \le (n - q + 1) + k, that is q≤m+k+1q \le m + k + 1. The ranges [q−k−1,p][q - k - 1, p] and [m−k−1,m][m - k - 1, m] then meet, so pick p′p' in both and set q′=p′+k+1≥qq' = p' + k + 1 \ge q. Since xx is sorted, g≤xq−xp≤xq′−xp′g \le x_q - x_p \le x_{q'} - x_{p'}, which is the term t=p′−m+k+1∈[0,k+1]t = p' - m + k + 1 \in [0, k+1]. The case g=ym−ym−1g = y_m - y_{m-1} is the same with m−1m - 1 in place of mm in the counts, and it gives p≥m−k−1p \ge m - k - 1 and q≤m+kq \le m + k, so the ranges meet again.

Lower bound. Fix tt with 1≤t≤k+11 \le t \le k + 1. The real values with indices from m+t−km + t - k to m+t−1m + t - 1 are at most kk. Replace them: put just enough of them at 0 so that exactly mm values of yy are at most xm+t−k−1x_{m+t-k-1}, and put the rest at Λ\Lambda. Then ym=xm+t−k−1y_m = x_{m+t-k-1} and ym+1=xm+ty_{m+1} = x_{m+t}, with the padding, so LS(y)≥xm+t−xm+t−k−1LS(y) \ge x_{m+t} - x_{m+t-k-1}. For t=0t = 0, put the values with indices m−km - k to m−1m - 1 at 0. Then ym−1≤xm−k−1y_{m-1} \le x_{m-k-1} and ym=xmy_m = x_m. The count works in each case because the gap holds at most kk real values. The test file checks this formula against the definition on every dataset with n=5n = 5 and Λ=3\Lambda = 3. □\square

Claim 3 (the closed form). S∗(x)=max⁡0≤k≤ne−kβA(k,x)S^*(x) = \max_{0 \le k \le n} e^{-k\beta} A(k, x), which is lines L1 to L3.

Proof. Group the yy in the definition by k=d(x,y)k = d(x, y): S∗(x)=max⁡ke−kβmax⁡d(x,y)=kLS(y)S^*(x) = \max_k e^{-k\beta} \max_{d(x,y) = k} LS(y). Since e−kβe^{-k\beta} falls with kk, replacing "=k= k" by "≤k\le k" does not change the maximum, which gives max⁡ke−kβA(k,x)\max_k e^{-k\beta} A(k, x). For k≥nk \ge n, A(k,x)≤Λ=A(n,x)A(k, x) \le \Lambda = A(n, x), so the terms with k>nk > n are not larger than the term k=nk = n. The test file checks the result against the definition by brute force on all datasets of the grid {0,…,Λ}n\{0, \dots, \Lambda\}^n for n≤5n \le 5 and Λ≤4\Lambda \le 4. □\square

Claim 4 (a smooth bound). S∗(x)≥LS(x)S^*(x) \ge LS(x), and S∗(x)≤eβS∗(x′)S^*(x) \le e^{\beta} S^*(x') for neighbors x,x′x, x'.

Proof. The term y=xy = x gives the first part. For the second, d(x,y)≤d(x′,y)+1d(x, y) \le d(x', y) + 1 by the triangle inequality, so e−βd(x,y)LS(y)≤eβe−βd(x′,y)LS(y)e^{-\beta d(x, y)} LS(y) \le e^{\beta} e^{-\beta d(x', y)} LS(y) for each yy. □\square

Claim 5 (pure DP with Cauchy noise, NRS Lemma 2.3 and Corollary 2.4). Let ZZ have the density h(z)=1/(π(1+z2))h(z) = 1/(\pi(1 + z^2)), let β=ε/6\beta = \varepsilon/6 and let s(x)=6S∗(x)/εs(x) = 6 S^*(x)/\varepsilon. The output xm+s(x)Zx_m + s(x) Z of line L4 is ε\varepsilon-DP.

Proof. The output density is px(z)=h((z−f(x))/s(x))/s(x)p_x(z) = h((z - f(x))/s(x))/s(x). For neighbors, write Δ=f(x′)−f(x)\Delta = f(x') - f(x) and λ=ln⁡(s(x′)/s(x))\lambda = \ln(s(x')/s(x)). By Claim 4, ∣Δ∣≤LS(x)≤S∗(x)|\Delta| \le LS(x) \le S^*(x), so ∣Δ∣≤(ε/6)s(x)|\Delta| \le (\varepsilon/6) s(x), and ∣λ∣≤β=ε/6|\lambda| \le \beta = \varepsilon/6. Go from pxp_x to px′p_{x'} in two steps: first move the center from f(x)f(x) to f(x′)f(x') with the scale s(x)s(x), then change the scale from s(x)s(x) to s(x′)s(x') with the center f(x′)f(x').

Shift: ∣dln⁡h/du∣=2∣u∣/(1+u2)≤1|d \ln h/du| = 2|u|/(1 + u^2) \le 1, so moving the center by ∣Δ∣/s(x)≤ε/6|\Delta|/s(x) \le \varepsilon/6 scaled units changes the log density by at most ε/6\varepsilon/6.

Scaling: with uu the distance to the center in units of s(x)s(x), the log ratio of the two densities is λ+ln⁡((1+u2e−2λ)/(1+u2))\lambda + \ln((1 + u^2 e^{-2\lambda})/(1 + u^2)). The second term lies between −2∣λ∣-2|\lambda| and 2∣λ∣2|\lambda|, so the scaling changes the log density by at most 3∣λ∣≤ε/23|\lambda| \le \varepsilon/2.

The total is at most ε/6+ε/2=2ε/3≤ε\varepsilon/6 + \varepsilon/2 = 2\varepsilon/3 \le \varepsilon, in both directions. NRS state this with γ=2\gamma = 2: noise 2(γ+1)S∗/ε2(\gamma + 1) S^*/\varepsilon needs β≤ε/(2(γ+1))\beta \le \varepsilon/(2(\gamma+1)). The test file checks the log density ratio on a grid of outputs. □\square

Claim 6 (approximate DP with Laplace noise, NRS Corollary 2.4). With β=ε/(2ln⁡(2/δ))\beta = \varepsilon/(2 \ln(2/\delta)) and noise (2S∗(x)/ε)⋅Lap(1)(2 S^*(x)/\varepsilon) \cdot \mathrm{Lap}(1), the output is (ε,δ)(\varepsilon, \delta)-DP.

Proof sketch. This is a sketch. The full proof is NRS Lemma 2.3 with the Laplace case of Corollary 2.4, in Section 2 of the paper. The shift costs at most ε/2\varepsilon/2, because Lap(1)\mathrm{Lap}(1) has a log density with slope at most 1 and the shift is at most S∗(x)/s(x)=ε/2S^*(x)/s(x) = \varepsilon/2 in scaled units. The scale ratio is eλe^{\lambda} with ∣λ∣≤β|\lambda| \le \beta, and the scaling changes the log density at the scaled point zz by at most ∣λ∣+∣z∣(e∣λ∣−1)|\lambda| + |z|(e^{|\lambda|} - 1), which is about β(1+∣z∣)\beta(1 + |z|). With β=ε/(2ln⁡(2/δ))\beta = \varepsilon/(2\ln(2/\delta)) this is at most about ε/2\varepsilon/2 unless ∣z∣|z| is of order ln⁡(2/δ)\ln(2/\delta), an event of probability of order δ\delta under Lap(1)\mathrm{Lap}(1). NRS make the constants exact. The test file checks the hockey-stick divergence at eεe^{\varepsilon} by numerical integration. □\square

Cost. Sorting takes O(nlog⁡n)O(n \log n). Line L2 takes O(k)O(k) for each kk, so lines L1 to L3 take O(n2)O(n^2) as written. NRS give an O(nlog⁡n)O(n \log n) algorithm by a divide-and-conquer search for the best tt for each kk. Line L4 takes O(1)O(1).

Complexity

In the real-RAM model, sorting takes O(nlog⁡n)O(n \log n), and lines L1 to L3 as written take O(n2)O(n^2) time, because line L2 scans k+2k + 2 terms. The extra space is O(n)O(n) for the sorted copy. NRS give an O(nlog⁡n)O(n \log n) algorithm for the median. Line L4 takes O(1)O(1).

Properties

  • Instance-based noise. The noise follows the gaps of xx near the median, not the worst case over all datasets.
  • Pure DP with heavy tails. The Cauchy form is ε\varepsilon-DP, but its noise has no mean. A single release can be far off with a small probability.
  • Approximate DP with light tails. The Laplace form has exponential tails and is (ε,δ)(\varepsilon, \delta)-DP.
  • A general framework. Any function with a computable smooth bound on its local sensitivity can use line L4. Computing S∗S^* exactly is hard for some functions, and any smooth upper bound on LSLS is also enough (NRS Definition 2.1).

Variants and improvements

  • Other noise laws. NRS give a general condition for "admissible" noise. Bun and Steinke (NeurIPS 2019) give laws with lighter tails for pure DP and for concentrated DP.
  • Subsample and aggregate. When no smooth bound is easy to compute, split the data, run the function on each part, and combine with a private median. See subsample and aggregate.
  • Propose-test-release. Test privately that the dataset is far from any dataset with large local sensitivity, and only then add small noise. See propose-test-release.
  • Other statistics. The same scheme works for the trimmed mean and for other order statistics, with a different formula in line L2.

When to use it

Use smooth sensitivity for a statistic whose global sensitivity is huge but whose local sensitivity is small on typical data, such as a median or a quantile of a large, dense sample. Use the Laplace mechanism when the global sensitivity is already small, such as for counts. Use the exponential mechanism over a grid of candidates for a quantile when a discrete output is fine.

Pitfalls

  • Noise scaled to the local sensitivity. Replacing SS in line L4 by LS(x)=A0LS(x) = A_0 is not private, because the scale depends on the data. A dataset with LS=0LS = 0 releases its median with no noise, and a neighbor with large LSLS does not.
  • Too large a β\beta. Line L1 needs β≤ε/6\beta \le \varepsilon/6 for the Cauchy form and β≤ε/(2ln⁡(2/δ))\beta \le \varepsilon/(2\ln(2/\delta)) for the Laplace form. A larger β\beta gives a smaller SS but breaks the proof.
  • Laplace noise with the pure DP claim. Line L4 with Laplace noise and β=ε/6\beta = \varepsilon/6 is not ε\varepsilon-DP. Laplace noise needs δ>0\delta > 0.
  • The padding. Line L2 must use xi=0x_i = 0 below the data and xi=Λx_i = \Lambda above it. Without the padding, SS ignores the datasets whose median moves to an end of the range, and the bound is not smooth.
  • Float noise. The code uses random.Random and float noise, for tests only. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012; Canonne, Kamath and Steinke 2020).

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dpkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Checkers for differential privacy on small finite examples.

A dataset is a tuple of records from a finite universe. A pmf is a dict from
outputs to probabilities; the probabilities may be fractions.Fraction (exact)
or float. A mechanism pmf is a function from a dataset to the pmf of the
output of the mechanism on that dataset.

This module holds the neighbor relations, the privacy loss, the hockey-stick
and Renyi divergences, the pure and approximate DP checks over a list of
neighbor pairs, an empirical pmf, the Hoeffding margin for Monte Carlo
checks, and a grid check of a log density ratio. It holds no mechanism, no
noise sampler and no accountant: those belong to the pages that define them.

Natural logarithms are used throughout, as in the DP literature.
"""

from __future__ import annotations

import math
from fractions import Fraction
from typing import Callable, Hashable, Iterable, Mapping, Sequence, Union

Number = Union[int, float, Fraction]
Pmf = Mapping[Hashable, Number]
Dataset = tuple
Pair = tuple[Dataset, Dataset]


def neighbors_add_remove(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
    """All datasets at add/remove distance 1 from dataset.

    A neighbor removes one record, or appends one record from the universe.
    Datasets are treated as multisets: a removal keeps the order of the other
    records, and equal results are listed once. Cost: O(n (n + |universe|)).
    """
    x = tuple(dataset)
    out: list[Dataset] = []
    seen: set[Dataset] = set()
    for i in range(len(x)):
        y = x[:i] + x[i + 1:]
        key = tuple(sorted(y, key=repr))
        if key not in seen:
            seen.add(key)
            out.append(y)
    for v in universe:
        y = x + (v,)
        key = tuple(sorted(y, key=repr))
        if key not in seen:
            seen.add(key)
            out.append(y)
    return out


def neighbors_replace(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
    """All datasets of the same size that differ from dataset in one record.

    The record at index i is replaced by a different value of the universe.
    Equal multisets are listed once. Cost: O(n^2 |universe|).
    """
    x = tuple(dataset)
    values = list(universe)
    out: list[Dataset] = []
    seen: set[Dataset] = set()
    for i in range(len(x)):
        for v in values:
            if v == x[i]:
                continue
            y = x[:i] + (v,) + x[i + 1:]
            key = tuple(sorted(y, key=repr))
            if key not in seen:
                seen.add(key)
                out.append(y)
    return out


def _ratio(a: Number, b: Number) -> Number:
    if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
        return Fraction(a) / Fraction(b)
    return float(a) / float(b)


def privacy_loss(p: Pmf, q: Pmf) -> dict[Hashable, float]:
    """The privacy loss ln(p(y) / q(y)) at each output y with p(y) > 0 or q(y) > 0.

    The value is +inf where q(y) = 0 < p(y) and -inf where p(y) = 0 < q(y).
    Outputs with p(y) = q(y) = 0 are left out. Cost: O(|support|).
    """
    out: dict[Hashable, float] = {}
    for y in set(p) | set(q):
        a, b = p.get(y, 0), q.get(y, 0)
        if a == 0 and b == 0:
            continue
        if b == 0:
            out[y] = math.inf
        elif a == 0:
            out[y] = -math.inf
        else:
            out[y] = math.log(_ratio(a, b))
    return out


def max_privacy_loss(p: Pmf, q: Pmf) -> float:
    """The largest privacy loss ln(p(y) / q(y)) over the outputs y with p(y) > 0.

    Returns -inf when p has no output of positive probability. Cost: O(|support|).
    """
    best = -math.inf
    for y, v in privacy_loss(p, q).items():
        if p.get(y, 0) > 0 and v > best:
            best = v
    return best


def hockey_stick(p: Pmf, q: Pmf, epsilon: float) -> float:
    """The hockey-stick divergence: the sum over y of max(0, p(y) - e^epsilon q(y)).

    It is sup over sets S of P(S) - e^epsilon Q(S). Cost: O(|support|).
    """
    a = math.exp(epsilon)
    total = 0.0
    for y in set(p) | set(q):
        d = float(p.get(y, 0)) - a * float(q.get(y, 0))
        if d > 0:
            total += d
    return total


def is_pure_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, tol: float = 1e-12) -> bool:
    """True if max privacy loss <= epsilon + tol for both orders of every pair.

    Precondition: mech_pmf returns the exact output pmf of the mechanism.
    Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
    """
    for x, y in pairs:
        p, q = mech_pmf(x), mech_pmf(y)
        if max_privacy_loss(p, q) > epsilon + tol or max_privacy_loss(q, p) > epsilon + tol:
            return False
    return True


def is_approx_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, delta: float, tol: float = 1e-12) -> bool:
    """True if the hockey-stick divergence at e^epsilon is <= delta + tol for both orders of every pair.

    Precondition: mech_pmf returns the exact output pmf of the mechanism.
    Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
    """
    for x, y in pairs:
        p, q = mech_pmf(x), mech_pmf(y)
        if hockey_stick(p, q, epsilon) > delta + tol or hockey_stick(q, p, epsilon) > delta + tol:
            return False
    return True


def renyi_divergence(p: Pmf, q: Pmf, alpha: float) -> float:
    """The Renyi divergence of order alpha > 1: ln(sum_y p(y)^alpha q(y)^(1 - alpha)) / (alpha - 1).

    Returns +inf when q(y) = 0 < p(y) for some y. Cost: O(|support|).
    """
    if alpha <= 1:
        raise ValueError("alpha must be greater than 1")
    s = 0.0
    for y in set(p) | set(q):
        a, b = float(p.get(y, 0)), float(q.get(y, 0))
        if a == 0:
            continue
        if b == 0:
            return math.inf
        s += a * (a / b) ** (alpha - 1)
    return math.log(s) / (alpha - 1)


def empirical_pmf(samples: Iterable[Hashable]) -> dict[Hashable, float]:
    """The fraction of the samples equal to each value. Cost: O(number of samples)."""
    counts: dict[Hashable, int] = {}
    n = 0
    for s in samples:
        counts[s] = counts.get(s, 0) + 1
        n += 1
    if n == 0:
        return {}
    return {k: c / n for k, c in counts.items()}


def hoeffding_margin(n: int, beta: float) -> float:
    """The margin t = sqrt(ln(2 / beta) / (2 n)).

    For n independent samples of a [0, 1] variable, the empirical mean is
    within t of the true mean with probability at least 1 - beta (Hoeffding).
    """
    if n <= 0 or not 0 < beta < 1:
        raise ValueError("need n >= 1 and 0 < beta < 1")
    return math.sqrt(math.log(2 / beta) / (2 * n))


def log_ratio_grid(logpdf_x: Callable[[float], float], logpdf_y: Callable[[float], float], grid: Iterable[float]) -> float:
    """The largest |logpdf_x(z) - logpdf_y(z)| over the points z of the grid.

    Use it to check the log density ratio of a continuous mechanism on two
    neighbors. Cost: O(|grid|) calls of each function.
    """
    best = 0.0
    for z in grid:
        d = abs(logpdf_x(z) - logpdf_y(z))
        if d > best:
            best = d
    return best
smooth_sensitivity.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smooth-sensitivity/. The authors are listed in prov/0ZFFMP.jsonl.
"""The smooth sensitivity framework of Nissim, Raskhodnikova and Smith
(2007), for the median of values in a known range [0, lam].

Neighbors replace one value by another, so n is fixed. The local
sensitivity of the median at y is how far one change can move the median
of y. The beta-smooth sensitivity is S*(x) = max over k >= 0 of
exp(-k beta) A(k, x), where A(k, x) is the largest local sensitivity over
the datasets within k changes of x. Noise scaled to S*(x) gives privacy:
Cauchy noise for pure DP, and Laplace noise for (epsilon, delta)-DP.

The code uses random.Random so that the tests can be repeated, and float
noise. A real release needs a cryptographic source of randomness and exact
sampling (Mironov 2012; Canonne, Kamath and Steinke 2020).
"""

from __future__ import annotations

import math
import random
from typing import Sequence


def median(xs: Sequence[float]) -> float:
    """The median x_m of an odd number of values, m = (n + 1)/2 in 1-based order. Cost: O(n log n)."""
    if len(xs) % 2 == 0 or not xs:
        raise ValueError("n must be odd")
    return sorted(xs)[len(xs) // 2]


def _padded(xs: Sequence[float], lam: float):
    s = sorted(xs)
    n = len(s)

    def at(i: int) -> float:  # 1-based, with x_i = 0 for i <= 0 and x_i = lam for i > n
        if i <= 0:
            return 0.0
        if i > n:
            return float(lam)
        return float(s[i - 1])

    return at, n


def ball_sensitivity(xs: Sequence[float], k: int, lam: float) -> float:
    """A(k, x) = max over t = 0..k+1 of x_{m+t} - x_{m+t-k-1}: the largest local sensitivity within k changes.

    Precondition: n odd, values in [0, lam], k >= 0. Cost: O(n log n + k).
    """
    at, n = _padded(xs, lam)
    m = (n + 1) // 2
    return max(at(m + t) - at(m + t - k - 1) for t in range(k + 2))


def smooth_sensitivity_median(xs: Sequence[float], beta: float, lam: float) -> float:
    """The beta-smooth sensitivity of the median (NRS Proposition 3.4).

    S*(x) = max over k = 0..n of exp(-k beta) A(k, x). For k >= n, A(k, x) = lam.
    Precondition: n odd, values in [0, lam], beta > 0. Cost: O(n^2) with this direct
    formula; NRS give an O(n log n) algorithm.
    """
    if beta <= 0:
        raise ValueError("beta must be positive")
    at, n = _padded(xs, lam)
    m = (n + 1) // 2
    best = 0.0
    for k in range(n + 1):  # @line L1
        a_k = max(at(m + t) - at(m + t - k - 1) for t in range(k + 2))  # @line L2
        best = max(best, math.exp(-k * beta) * a_k)  # @line L3
    return best


def cauchy_noise(rng: random.Random) -> float:
    """One draw of the standard Cauchy law, density 1/(pi (1 + z^2)), by the inverse CDF. Cost: O(1)."""
    u = rng.random()
    while u == 0.0:
        u = rng.random()
    return math.tan(math.pi * (u - 0.5))


def laplace_noise(b: float, rng: random.Random) -> float:
    """One draw of Lap(b), the density (1/(2b)) exp(-|z|/b), by the inverse CDF. Cost: O(1)."""
    u = rng.random() - 0.5
    while u == -0.5:
        u = rng.random() - 0.5
    s = (u > 0) - (u < 0)
    return -b * s * math.log(1.0 - 2.0 * abs(u))


def private_median_cauchy(xs: Sequence[float], lam: float, epsilon: float, rng: random.Random) -> float:
    """An epsilon-DP median: x_m + (6 S*/epsilon) Z, with beta = epsilon/6 and Z standard Cauchy.

    This is NRS Corollary 2.4 (1) with gamma = 2: noise 2(gamma + 1) S*/epsilon = 6 S*/epsilon,
    which needs beta <= epsilon/(2(gamma + 1)) = epsilon/6.
    Precondition: epsilon > 0, n odd, values in [0, lam]. Cost: O(n^2).
    """
    if epsilon <= 0:
        raise ValueError("epsilon must be positive")
    beta = epsilon / 6.0
    s = smooth_sensitivity_median(xs, beta, lam)
    return median(xs) + (6.0 * s / epsilon) * cauchy_noise(rng)  # @line L4


def private_median_laplace(
    xs: Sequence[float], lam: float, epsilon: float, delta: float, rng: random.Random
) -> float:
    """An (epsilon, delta)-DP median: x_m + (2 S*/epsilon) Lap(1), with beta = epsilon/(2 ln(2/delta)).

    This is NRS Corollary 2.4 (2). Precondition: epsilon > 0, 0 < delta < 1. Cost: O(n^2).
    """
    if epsilon <= 0 or not 0 < delta < 1:
        raise ValueError("need epsilon > 0 and 0 < delta < 1")
    beta = epsilon / (2.0 * math.log(2.0 / delta))
    s = smooth_sensitivity_median(xs, beta, lam)
    return median(xs) + (2.0 * s / epsilon) * laplace_noise(1.0, rng)
test_smooth_sensitivity.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smooth-sensitivity/. The authors are listed in prov/0ZFFMP.jsonl.

import itertools
import math
import random

import dpkit
from smooth_sensitivity import (
    ball_sensitivity,
    cauchy_noise,
    laplace_noise,
    median,
    private_median_cauchy,
    private_median_laplace,
    smooth_sensitivity_median,
)


def _local_sensitivity(xs, lam):
    # Brute force: replace one value by 0 or lam (the extremes move the median the most).
    med = median(xs)
    best = 0.0
    for i in range(len(xs)):
        for v in (0, lam):
            ys = list(xs)
            ys[i] = v
            best = max(best, abs(median(ys) - med))
    return best


def _distance(a, b):
    # Replace distance between two multisets of the same size.
    ca, cb = {}, {}
    for v in a:
        ca[v] = ca.get(v, 0) + 1
    for v in b:
        cb[v] = cb.get(v, 0) + 1
    return len(a) - sum(min(c, cb.get(v, 0)) for v, c in ca.items())


def _brute_smooth(xs, beta, lam, everything):
    # Definition 2.2 of NRS: max over y of exp(-beta d(x, y)) LS(y), over all datasets on the grid.
    return max(math.exp(-beta * _distance(xs, y)) * ls for y, ls in everything)


def _all_datasets(n, lam):
    return [(y, _local_sensitivity(y, lam)) for y in itertools.combinations_with_replacement(range(lam + 1), n)]


def test_local_sensitivity_matches_brute_force() -> None:
    rng = random.Random(1)
    for _ in range(500):
        n = rng.choice([1, 3, 5, 7])
        lam = rng.randrange(1, 10)
        xs = [rng.randrange(lam + 1) for _ in range(n)]
        assert ball_sensitivity(xs, 0, lam) == _local_sensitivity(xs, lam)


def test_smooth_sensitivity_matches_definition() -> None:
    # The closed form of NRS Proposition 3.4 against the definition, on every dataset of the grid.
    grids = {(n, lam): _all_datasets(n, lam) for n in (1, 3, 5) for lam in (1, 2, 4)}
    rng = random.Random(2)
    count = 0
    for (n, lam), everything in grids.items():
        for xs, _ in everything:
            beta = rng.choice([0.05, 0.3, 1.0, 2.5])
            got = smooth_sensitivity_median(xs, beta, lam)
            assert math.isclose(got, _brute_smooth(xs, beta, lam, everything), rel_tol=1e-12)
            count += 1
    assert count >= 100


def test_ball_sensitivity_matches_brute_force() -> None:
    # A(k, x) is the largest local sensitivity over the datasets within distance k.
    everything = _all_datasets(5, 3)
    for xs, _ in everything:
        for k in range(6):
            brute = max(ls for y, ls in everything if _distance(xs, y) <= k)
            assert ball_sensitivity(xs, k, 3) == brute


def test_smooth_bound_properties() -> None:
    # S* >= LS, and S*(x) <= exp(beta) S*(y) for neighbors (Definition 2.1 of NRS).
    rng = random.Random(3)
    for _ in range(500):
        n = rng.choice([3, 5, 9, 15])
        lam = 20
        beta = rng.choice([0.1, 0.5, 1.0])
        xs = [rng.randrange(lam + 1) for _ in range(n)]
        ys = list(xs)
        ys[rng.randrange(n)] = rng.randrange(lam + 1)
        sx = smooth_sensitivity_median(xs, beta, lam)
        sy = smooth_sensitivity_median(ys, beta, lam)
        assert sx >= _local_sensitivity(xs, lam) - 1e-12
        assert sx <= math.exp(beta) * sy * (1 + 1e-12)
        assert sy <= math.exp(beta) * sx * (1 + 1e-12)


def _cauchy_logpdf(xs, lam, epsilon):
    s = 6.0 * smooth_sensitivity_median(xs, epsilon / 6.0, lam) / epsilon
    c = median(xs)
    return lambda z: -math.log(math.pi * s) - math.log1p(((z - c) / s) ** 2)


def test_cauchy_release_is_epsilon_dp_on_a_grid() -> None:
    # Pure DP: the log density ratio of neighbors stays within epsilon at every output.
    rng = random.Random(4)
    grid = [i / 4 for i in range(-400, 481)]
    worst = 0.0
    for _ in range(150):
        n, lam = rng.choice([3, 5, 7]), 10
        epsilon = rng.choice([0.5, 1.0, 2.0])
        xs = [rng.randrange(lam + 1) for _ in range(n)]
        ys = list(xs)
        ys[rng.randrange(n)] = rng.choice([0, lam, rng.randrange(lam + 1)])
        loss = dpkit.log_ratio_grid(_cauchy_logpdf(xs, lam, epsilon), _cauchy_logpdf(ys, lam, epsilon), grid)
        assert loss <= epsilon + 1e-9
        worst = max(worst, loss / epsilon)
    assert worst > 0.15  # the analysis has slack, but the loss is not trivial


def _laplace_pdf(xs, lam, epsilon, delta):
    beta = epsilon / (2.0 * math.log(2.0 / delta))
    b = 2.0 * smooth_sensitivity_median(xs, beta, lam) / epsilon
    c = median(xs)
    return lambda z: math.exp(-abs(z - c) / b) / (2 * b)


def test_laplace_release_is_approx_dp() -> None:
    # (epsilon, delta)-DP: the hockey-stick integral, by a fine Riemann sum, is at most delta.
    rng = random.Random(5)
    h = 0.02
    grid = [-60 + h * i for i in range(int(130 / h))]
    for _ in range(25):
        n, lam = 5, 10
        epsilon, delta = rng.choice([0.5, 1.0]), 0.05
        xs = [rng.randrange(lam + 1) for _ in range(n)]
        ys = list(xs)
        ys[rng.randrange(n)] = rng.choice([0, lam])
        p, q = _laplace_pdf(xs, lam, epsilon, delta), _laplace_pdf(ys, lam, epsilon, delta)
        for a, b in ((p, q), (q, p)):
            mass = h * sum(max(0.0, a(z) - math.exp(epsilon) * b(z)) for z in grid)
            assert mass <= delta + 1e-3


def test_example_values() -> None:
    xs = list(range(101))
    lam, epsilon = 100, 1.0
    assert median(xs) == 50
    assert _local_sensitivity(xs, lam) == 1
    assert [ball_sensitivity(xs, k, lam) for k in range(6)] == [1, 2, 3, 4, 5, 6]
    s = smooth_sensitivity_median(xs, epsilon / 6, lam)
    assert math.isclose(s, 6 * math.exp(-5 / 6), rel_tol=1e-12)
    assert 15.6 < 6 * s / epsilon < 15.7


def test_noise_samplers() -> None:
    rng = random.Random(6)
    n = 20000
    cauchy = [abs(cauchy_noise(rng)) <= 1.0 for _ in range(n)]
    lap = [abs(laplace_noise(2.0, rng)) > 3.0 for _ in range(n)]
    margin = dpkit.hoeffding_margin(n, 1e-6)
    assert abs(sum(cauchy) / n - 0.5) <= margin
    assert abs(sum(lap) / n - math.exp(-1.5)) <= margin


def test_release_centers_on_the_median() -> None:
    rng = random.Random(7)
    xs = [3, 5, 5, 6, 9]
    outs = [private_median_cauchy(xs, 10, 1.0, rng) for _ in range(4001)]
    assert abs(sorted(outs)[2000] - 5) < 1.0
    outs = [private_median_laplace(xs, 10, 1.0, 1e-3, rng) for _ in range(4001)]
    assert abs(sorted(outs)[2000] - 5) < 1.0


def test_bad_parameters() -> None:
    rng = random.Random(8)
    for call in (
        lambda: median([1, 2]),
        lambda: smooth_sensitivity_median([1], 0.0, 1),
        lambda: private_median_cauchy([1], 1, 0.0, rng),
        lambda: private_median_laplace([1], 1, 1.0, 0.0, rng),
    ):
        try:
            call()
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")

History

Dwork, McSherry, Nissim and Smith (2006) calibrated noise to the global sensitivity. Nissim, Raskhodnikova and Smith (STOC 2007) showed that the local sensitivity alone is not safe, and gave smooth sensitivity, its closed form for the median, its use for the cost of a minimum spanning tree, and the subsample and aggregate framework. Dwork and Lei (2009) gave the related propose-test-release framework. Bun and Steinke (2019) gave better noise laws for the framework.

References

  1. Kobbi Nissim, Sofya Raskhodnikova and Adam Smith, Smooth sensitivity and sampling in private data analysis, STOC 2007, Definition 2.1 (a smooth upper bound), Definition 2.2 (smooth sensitivity), Lemma 2.3 and Corollary 2.4 (Cauchy noise for epsilon-DP, Laplace noise for (epsilon, delta)-DP), Proposition 3.4 (the median)
  2. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point noise and the snapping defense
  3. Clement Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, exact sampling of discrete noise

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 correctness
  • 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