Algorithm Search⌘K

Algorithmadvanced

Propose-test-release

Also called PTR.

Proposes a bound on the local sensitivity, tests with noise that the data is far from any dataset that breaks it, and only then releases the answer with noise for that bound.

Time
O(n^2) worst
Space
O(n) extra
Where
n = the number of values
Origin
Cynthia Dwork, Jing Lei, 2009

Propose-test-release (PTR) is a way to add noise for the typical case and not the worst case. The analyst proposes a bound bb on the local sensitivity of a function ff. The mechanism computes how many records of xx must change before the local sensitivity is above bb, adds Laplace noise to that distance, and compares it with ln⁡(1/δ)/ε\ln(1/\delta)/\varepsilon. If the noisy distance is too small it outputs ⊥\bot, "no answer". Otherwise it releases f(x)+Lap(b/ε)f(x) + \mathrm{Lap}(b/\varepsilon). The result is (2ε,δ)(2\varepsilon, \delta)-differentially private for every ff and bb. For the median of dense data the noise is far smaller than the global sensitivity requires.

In plain words

You want to publish the middle value of a list and you guess that one change can move it by at most bb. The guess may be wrong for this list, or for a list close to it.

So first count how many values you must change to make the guess wrong. If that count is large, the guess is safe here and also for all lists close to this one. Add noise to the count and compare it with a safety margin. If the noisy count is too small, say nothing. If it is large, publish the middle value with noise for the guess bb. The noise on the count hides each value, and the margin makes a wrong answer very unlikely.

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, and 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, its 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 its global sensitivity is Λ\Lambda. The distance to instability is γ(x)=min⁡{d(x,y):LS(y)>b}\gamma(x) = \min\{d(x, y) : LS(y) > b\}. The goal is an (ε,δ)(\varepsilon, \delta)-DP estimate of xmx_m, or ⊥\bot.

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 algorithm

This is the form of Vadhan (2017, Proposition 3.2), with the median as ff. Sort xx and set xi=0x_i = 0 for i≤0i \le 0 and xi=Λx_i = \Lambda for i>ni > n.

  1. PTR-MEDIAN(x₁ ≤ ... ≤ xₙ, Λ, b, ε, δ)
  2. 1γ ← min{k ≥ 0 : max_{0≤t≤k+1} (x_{m+t} − x_{m+t−k−1}) > b} ▷ ∞ if no k works
  3. 2γ̂ ← γ + Lap(1/ε) ▷ γ has sensitivity 1
  4. 3if γ̂ ≤ ln(1/δ)/ε then output ⊥ and halt
  5. 4output x_m + Lap(b/ε)

Line L1 is the distance to instability. The inner maximum is the largest local sensitivity of the median within kk replacements, from the closed form of Nissim, Raskhodnikova and Smith (2007, Proposition 3.4). It grows with kk, so the first kk above bb is the distance. Line L2 is the Laplace mechanism on γ\gamma. Line L3 is the test. Line L4 is the release with the proposed bound.

Example

Take n=101n = 101 values 0,1,…,1000, 1, \dots, 100, with Λ=100\Lambda = 100, ε=1\varepsilon = 1 and δ=10−6\delta = 10^{-6}, so the threshold in line L3 is ln⁡106≈13.8\ln 10^6 \approx 13.8. Each gap is 1, so kk changes move the median by at most k+1k + 1, and γ=b\gamma = b for whole numbers bb. From the code:

bb γ\gamma P(the test passes) noise in line L4 median absolute error
5 5 0.00007 Lap(5) 3.5
10 10 0.011 Lap(10) 6.9
15 15 0.847 Lap(15) 10.4
20 20 0.999 Lap(20) 13.9
30 30 1.000 Lap(30) 20.8

A small bb gives small noise but the test fails, and a large bb always passes but adds more noise. With b=20b = 20 the release is (2,10−6)(2, 10^{-6})-DP with the median absolute error 13.9. The Laplace mechanism with the global sensitivity 100 at ε=2\varepsilon = 2 needs Lap(50)\mathrm{Lap}(50), with the median absolute error 34.7. These values are exact for the noise laws (a theorem), not a measurement.

Correctness

Line L1 is the distance (a theorem). By NRS Proposition 3.4, the inner maximum is max⁡d(x,y)≤kLS(y)\max_{d(x,y) \le k} LS(y), so the least kk with a value above bb is γ(x)\gamma(x). The test file checks line L1 against a breadth-first search over all small datasets.

γ\gamma has sensitivity 1 (a theorem). dd is a metric, so ∣γ(x)−γ(x′)∣≤1|\gamma(x) - \gamma(x')| \le 1 for neighbors.

Privacy (Vadhan Proposition 3.2, a theorem). The test of lines L2 and L3 is ε\varepsilon-DP. If γ(x)≥1\gamma(x) \ge 1, then LS(x)≤bLS(x) \le b, so line L4 is ε\varepsilon-DP for this pair, and the total is 2ε2\varepsilon. If γ(x)=0\gamma(x) = 0, the test passes with probability P(Lap(1/ε)>ln⁡(1/δ)/ε)=δ/2P(\mathrm{Lap}(1/\varepsilon) > \ln(1/\delta)/\varepsilon) = \delta/2. So the output is (2ε,δ/2)(2\varepsilon, \delta/2)-DP. Vadhan states δ\delta; the same proof gives δ/2\delta/2.

Utility (a theorem). If γ(x)≥ln⁡(1/δ)/ε+t/ε\gamma(x) \ge \ln(1/\delta)/\varepsilon + t/\varepsilon, the test passes with probability at least 1−12e−t1 - \frac{1}{2}e^{-t}.

The full proofs are in proofs/correctness.md.

Proof: Propose-test-release for the median computes the distance to instability and is (2 epsilon, delta)-DPfull

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 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 from xx to yy. The median is f(x)=xmf(x) = x_m, and LS(y)=max⁡d(y,y′)=1∣f(y)−f(y′)∣LS(y) = \max_{d(y,y')=1} |f(y) - f(y')| is its local sensitivity. The proposed bound is b>0b > 0, the threshold is T=ln⁡(1/δ)/εT = \ln(1/\delta)/\varepsilon, and the output ⊥\bot means "no answer".

Claim 1 (line L1). Let γ(x)=min⁡{d(x,y):LS(y)>b}\gamma(x) = \min\{d(x, y) : LS(y) > b\}, with γ(x)=∞\gamma(x) = \infty if no yy has LS(y)>bLS(y) > b. Then γ(x)=min⁡{k≥0:A(k,x)>b}\gamma(x) = \min\{k \ge 0 : A(k, x) > b\}, with 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. By Nissim, Raskhodnikova and Smith (2007, Proposition 3.4), A(k,x)=max⁡d(x,y)≤kLS(y)A(k, x) = \max_{d(x,y) \le k} LS(y). The proof is on the smooth sensitivity page. So A(k,x)>bA(k, x) > b exactly when some yy with d(x,y)≤kd(x, y) \le k has LS(y)>bLS(y) > b, and the least such kk is γ(x)\gamma(x). For k≥nk \ge n every dataset is within kk replacements and A(k,x)=ΛA(k, x) = \Lambda, so γ(x)=∞\gamma(x) = \infty exactly when b≥Λb \ge \Lambda, and the loop can stop at k=nk = n. The test file checks line L1 against a breadth-first search over the grid {0,…,Λ}n\{0, \dots, \Lambda\}^n for n≤5n \le 5 and Λ≤4\Lambda \le 4. □\square

Claim 2 (sensitivity of γ\gamma). For neighbors x,x′x, x', ∣γ(x)−γ(x′)∣≤1|\gamma(x) - \gamma(x')| \le 1, and γ(x)=∞\gamma(x) = \infty exactly when γ(x′)=∞\gamma(x') = \infty.

Proof. dd is a metric, so d(x,y)≤1+d(x′,y)d(x, y) \le 1 + d(x', y) for every yy. Take the minimum over the yy with LS(y)>bLS(y) > b: γ(x)≤1+γ(x′)\gamma(x) \le 1 + \gamma(x'), and the same with xx and x′x' swapped. The set {y:LS(y)>b}\{y : LS(y) > b\} does not depend on xx, so it is empty for both or for neither. □\square

Claim 3 (privacy; Vadhan Proposition 3.2). The output is (2ε,δ/2)(2\varepsilon, \delta/2)-DP, so it is (2ε,δ)(2\varepsilon, \delta)-DP.

Proof. Fix neighbors x,x′x, x' and a set SS of outputs. Write Px(⊥)=P(γ(x)+Z≤T)P_x(\bot) = P(\gamma(x) + Z \le T) with Z∼Lap(1/ε)Z \sim \mathrm{Lap}(1/\varepsilon), and px=1−Px(⊥)p_x = 1 - P_x(\bot). Lines L2 and L3 are the Laplace mechanism on γ\gamma, which has sensitivity 1 by Claim 2, followed by a test. So by post-processing, Px(⊥)≤eεPx′(⊥)P_x(\bot) \le e^{\varepsilon} P_{x'}(\bot) and px≤eεpx′p_x \le e^{\varepsilon} p_{x'}. If both γ\gamma are infinite, the test passes for both, and the case below with γ(x)≥1\gamma(x) \ge 1 applies.

Case γ(x)≥1\gamma(x) \ge 1. Then LS(x)≤bLS(x) \le b, so ∣f(x)−f(x′)∣≤b|f(x) - f(x')| \le b. Let S0=S∖{⊥}S_0 = S \setminus \{\bot\} and let LcL_c be the law of c+Lap(b/ε)c + \mathrm{Lap}(b/\varepsilon). Then Lf(x)(S0)≤eεLf(x′)(S0)L_{f(x)}(S_0) \le e^{\varepsilon} L_{f(x')}(S_0), and

Px(S)=[⊥∈S]Px(⊥)+pxLf(x)(S0)≤eε[⊥∈S]Px′(⊥)+e2εpx′Lf(x′)(S0)≤e2εPx′(S).P_x(S) = [\bot \in S] P_x(\bot) + p_x L_{f(x)}(S_0) \le e^{\varepsilon}[\bot \in S] P_{x'}(\bot) + e^{2\varepsilon} p_{x'} L_{f(x')}(S_0) \le e^{2\varepsilon} P_{x'}(S).

Case γ(x)=0\gamma(x) = 0. Then px=P(Z>T)=12e−εT=δ/2p_x = P(Z > T) = \frac{1}{2} e^{-\varepsilon T} = \delta/2, and

Px(S)≤[⊥∈S]Px(⊥)+px≤eεPx′(S)+δ/2.P_x(S) \le [\bot \in S] P_x(\bot) + p_x \le e^{\varepsilon} P_{x'}(S) + \delta/2.

In both cases Px(S)≤e2εPx′(S)+δ/2P_x(S) \le e^{2\varepsilon} P_{x'}(S) + \delta/2. □\square

Vadhan states the result with δ\delta. The proof gives δ/2\delta/2 because P(Z>T)=δ/2P(Z > T) = \delta/2 for the Laplace law. The test file computes the exact output law for every pair of neighbors with n=3n = 3 and Λ=4\Lambda = 4, and checks the hockey-stick divergence at e2εe^{2\varepsilon} against δ/2\delta/2 by a fine numerical integration.

Claim 4 (utility). If γ(x)≥T+t/ε\gamma(x) \ge T + t/\varepsilon with t≥0t \ge 0, the test passes with probability at least 1−12e−t1 - \frac{1}{2} e^{-t}, and then the output is f(x)+Lap(b/ε)f(x) + \mathrm{Lap}(b/\varepsilon), whose error is above ss with probability e−sε/be^{-s\varepsilon/b}.

Proof. The test fails when Z≤T−γ(x)≤−t/εZ \le T - \gamma(x) \le -t/\varepsilon, which has probability 12e−t\frac{1}{2} e^{-t}. The second part is the tail of the Laplace law. □\square

Cost. Sorting takes O(nlog⁡n)O(n \log n). Line L1 tries k=0,1,…,γ(x)k = 0, 1, \dots, \gamma(x) and each try takes O(k)O(k), so it takes O(min⁡(γ(x),n)2)O(\min(\gamma(x), n)^2) after the sort. Lines L2 to L4 take O(1)O(1). The total is O(n2)O(n^2) time in the worst case and O(n)O(n) extra space.

Complexity

In the real-RAM model, sorting takes O(nlog⁡n)O(n \log n). Line L1 tries k=0,1,…,γk = 0, 1, \dots, \gamma and each try scans k+2k + 2 terms, so it takes O(min⁡(γ,n)2)O(\min(\gamma, n)^2). Lines L2 to L4 take O(1)O(1). The total is O(n2)O(n^2) time in the worst case and O(n)O(n) extra space. For a general ff, line L1 can be hard to compute, and this is the main limit of PTR.

Properties

  • Any function. The privacy proof uses only the sensitivity 1 of γ\gamma and the bound LS(x)≤bLS(x) \le b when γ(x)≥1\gamma(x) \ge 1. It works for every ff and bb.
  • Approximate DP only. The output is (2ε,δ)(2\varepsilon, \delta)-DP and not pure DP, because a dataset with γ=0\gamma = 0 still passes with probability δ/2\delta/2. Bun and Steinke note that it is also not zero-concentrated DP.
  • A private "no". The output ⊥\bot is itself private: it tells only that the data is close to an unstable dataset.
  • Data-dependent error. When the test passes, the error is that of Lap(b/ε)\mathrm{Lap}(b/\varepsilon), set by the proposal and not by Λ\Lambda.

Variants and improvements

  • Release of stable values. If ff is constant on all datasets within distance γ\gamma, line L4 can output f(x)f(x) with no noise (Vadhan Proposition 3.3; Dwork and Roth Algorithm 13). This gives a private mode and the stability-based histogram.
  • Scale first. Dwork and Lei, and Dwork and Roth Algorithm 12, first estimate the interquartile range with PTR on a log scale, and then use it as the proposal bb for the median. Dwork and Roth Theorem 7.1 gives (4ε,δ)(4\varepsilon, \delta)-DP for the scale step.
  • Many proposals. Try b=1,2,4,…b = 1, 2, 4, \dots and stop at the first pass. With the sparse vector technique the cost of the failed tests is small.
  • Smooth sensitivity. Smooth sensitivity scales the noise to the local sensitivity near xx without a test, and it can give pure DP with heavy-tailed noise.

When to use it

Use PTR when a statistic has a large global sensitivity but is stable on typical data, and when a "no answer" output is acceptable: a median, a quantile, a mode, or a robust regression estimate on a large sample. Use the Laplace mechanism when the global sensitivity is small. Use subsample and aggregate when the distance to instability is hard to compute.

Pitfalls

  • Release without the test. Skipping line L3, or releasing γ\gamma itself, breaks privacy. The proposal bb alone is not a bound on the local sensitivity of every dataset.
  • No noise in line L2. A test on the exact γ\gamma leaks whether γ\gamma is above the threshold, which can single out one record. The noise Lap(1/ε)\mathrm{Lap}(1/\varepsilon) is required.
  • A data-dependent proposal. The bound bb must not depend on xx, unless it comes from a private step whose cost is counted, as in the scale step of Dwork and Lei. A bb read from the data makes line L4 leak.
  • The wrong distance. Line L1 must be the distance to the nearest dataset with LS>bLS > b, not LS(x)LS(x) itself. A dataset with LS(x)≤bLS(x) \le b can have a neighbor with a large LSLS.
  • The privacy cost. The total is 2ε2\varepsilon, not ε\varepsilon. Count both lines L2 and L4 in the budget.
  • 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
propose_test_release.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/propose-test-release/. The authors are listed in prov/DV793R.jsonl.
"""Propose-test-release (PTR) of Dwork and Lei (2009), in the form of
Vadhan (2017, Proposition 3.2), for the median of values in [0, lam].

Neighbors replace one value by another, so n is fixed. The analyst proposes
a bound b on the local sensitivity. The mechanism computes the distance
from x to the nearest dataset whose local sensitivity is above b, tests a
noisy copy of it against ln(1/delta)/epsilon, and releases the median with
Lap(b/epsilon) noise only if the test passes. Otherwise it outputs None
(the symbol "no answer"). The whole run is (2 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 Optional, 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 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}, with x_i = 0 for i <= 0 and lam for i > n.

    This is the largest local sensitivity of the median over the datasets within k replacements
    of x (Nissim, Raskhodnikova and Smith 2007, Proposition 3.4). Cost: O(n log n + k).
    """
    return _ball(_padded(xs, lam), (len(xs) + 1) // 2, k)


def _padded(xs: Sequence[float], lam: float) -> list[float]:
    # Index i of the list is x_{i - n - 1}: n zeros, the sorted values, then n + 2 copies of lam.
    n = len(xs)
    return [0.0] * (n + 1) + [float(v) for v in sorted(xs)] + [float(lam)] * (n + 2)


def _ball(p: list[float], m: int, k: int) -> float:
    off = (len(p) - 1) // 3  # the offset of x_0 in the padded list
    return max(p[off + m + t] - p[off + m + t - k - 1] for t in range(k + 2))


def distance_to_instability(xs: Sequence[float], b: float, lam: float) -> float:
    """The number of replacements from x to the nearest dataset whose local sensitivity is above b.

    It is the least k with A(k, x) > b, because A(k, x) grows with k. It is infinite when b >= lam.
    Precondition: n odd, values in [0, lam]. Cost: O(n log n + gamma^2).
    """
    p = _padded(xs, lam)
    m = (len(xs) + 1) // 2
    for k in range(len(xs) + 1):
        if _ball(p, m, k) > b:
            return float(k)
    return math.inf


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 laplace_cdf(t: float, b: float) -> float:
    """P(Lap(b) <= t). Cost: O(1)."""
    if t < 0:
        return 0.5 * math.exp(t / b)
    return 1.0 - 0.5 * math.exp(-t / b)


def pass_probability(gamma: float, epsilon: float, delta: float) -> float:
    """P(gamma + Lap(1/epsilon) > ln(1/delta)/epsilon), the chance that the test of line L3 passes. Cost: O(1)."""
    if math.isinf(gamma):
        return 1.0
    return 1.0 - laplace_cdf(math.log(1.0 / delta) / epsilon - gamma, 1.0 / epsilon)


def propose_test_release_median(
    xs: Sequence[float], lam: float, b: float, epsilon: float, delta: float, rng: random.Random
) -> Optional[float]:
    """PTR for the median. Returns None for "no answer", else median(x) + Lap(b/epsilon).

    Precondition: n odd, values in [0, lam], b > 0, epsilon > 0, 0 < delta < 1.
    Guarantee: (2 epsilon, delta)-DP for replace neighbors (Vadhan, Proposition 3.2).
    Cost: O(n^2) time and O(n) extra space.
    """
    if epsilon <= 0 or not 0 < delta < 1 or b <= 0:
        raise ValueError("need epsilon > 0, 0 < delta < 1 and b > 0")
    if len(xs) % 2 == 0:
        raise ValueError("n must be odd")
    gamma = distance_to_instability(xs, b, lam)  # @line L1
    noisy = gamma + laplace_noise(1.0 / epsilon, rng)  # @line L2
    if noisy <= math.log(1.0 / delta) / epsilon:  # @line L3
        return None
    return median(xs) + laplace_noise(b / epsilon, rng)  # @line L4
test_propose_test_release.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/propose-test-release/. The authors are listed in prov/DV793R.jsonl.

import itertools
import math
import random

import dpkit
from propose_test_release import (
    distance_to_instability,
    laplace_noise,
    median,
    pass_probability,
    propose_test_release_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 _bfs_distance(xs, b, lam):
    # Breadth-first search over the multisets of the grid {0..lam}^n, one replacement for each step.
    start = tuple(sorted(xs))
    seen = {start}
    frontier = [start]
    dist = 0
    while frontier:
        if any(_local_sensitivity(y, lam) > b for y in frontier):
            return float(dist)
        nxt = []
        for y in frontier:
            for i in range(len(y)):
                for v in range(lam + 1):
                    z = tuple(sorted(y[:i] + (v,) + y[i + 1:]))
                    if z not in seen:
                        seen.add(z)
                        nxt.append(z)
        frontier = nxt
        dist += 1
    return math.inf


def test_distance_matches_breadth_first_search() -> None:
    count = 0
    for n in (1, 3, 5):
        for lam in (1, 2, 4):
            for xs in itertools.combinations_with_replacement(range(lam + 1), n):
                for b in (0, 0.5, 1, 2, lam):
                    assert distance_to_instability(xs, b, lam) == _bfs_distance(xs, b, lam)
                    count += 1
    assert count >= 500


def test_distance_has_sensitivity_one() -> None:
    rng = random.Random(1)
    for _ in range(500):
        n, lam = rng.choice([3, 5, 9, 21]), 30
        b = rng.choice([1, 2, 4, 8])
        xs = [rng.randrange(lam + 1) for _ in range(n)]
        ys = list(xs)
        ys[rng.randrange(n)] = rng.randrange(lam + 1)
        assert abs(distance_to_instability(xs, b, lam) - distance_to_instability(ys, b, lam)) <= 1


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


def _output_law(xs, lam, b, epsilon, delta, grid, h):
    # The exact law of the output: the mass of "no answer" and the density on a grid times h.
    p = pass_probability(distance_to_instability(xs, b, lam), epsilon, delta)
    c, s = median(xs), b / epsilon
    return 1.0 - p, [p * h * math.exp(-abs(z - c) / s) / (2 * s) for z in grid]


def test_two_epsilon_delta_dp_by_hockey_stick() -> None:
    # Vadhan Proposition 3.2: (2 epsilon, delta)-DP. The proof gives delta/2; we check delta/2.
    lam, b, epsilon, delta = 4, 1.0, 0.5, 0.1
    h = 0.05
    grid = [-40 + h * (i + 0.5) for i in range(int(84 / h))]
    universe = range(lam + 1)
    laws = {}
    for xs in itertools.combinations_with_replacement(universe, 3):
        laws[xs] = _output_law(xs, lam, b, epsilon, delta, grid, h)
    worst = 0.0
    worst_one = 0.0
    for xs in laws:
        for ys in dpkit.neighbors_replace(xs, universe):
            ys = tuple(sorted(ys))
            (bx, dx), (by, dy) = laws[xs], laws[ys]
            for eps, store in ((2 * epsilon, "two"), (epsilon, "one")):
                e = math.exp(eps)
                hs = max(0.0, bx - e * by) + sum(max(0.0, a - e * c) for a, c in zip(dx, dy))
                if store == "two":
                    worst = max(worst, hs)
                else:
                    worst_one = max(worst_one, hs)
            assert bx <= math.exp(epsilon) * by + 1e-12
    assert worst <= delta / 2 + 1e-3
    assert worst_one > worst  # the test and the release each spend epsilon


def test_pass_probability_formula_and_sampling() -> None:
    rng = random.Random(3)
    xs = [rng.randrange(101) for _ in range(31)]
    for b, epsilon, delta in ((10, 1.0, 1e-3), (20, 0.5, 1e-2), (40, 1.0, 1e-6)):
        p = pass_probability(distance_to_instability(xs, b, 100), epsilon, delta)
        n = 3000
        hits = sum(propose_test_release_median(xs, 100, b, epsilon, delta, rng) is not None for _ in range(n))
        assert abs(hits / n - p) <= dpkit.hoeffding_margin(n, 1e-6)


def test_released_value_is_median_plus_laplace() -> None:
    rng = random.Random(4)
    xs = list(range(51))  # distance 25 to instability for b = 30, so the test passes
    outs = [propose_test_release_median(xs, 100, 30, 1.0, 1e-6, rng) for _ in range(3000)]
    assert all(o is not None for o in outs)
    n = len(outs)
    frac = sum(abs(o - 25) > 30 for o in outs) / n
    assert abs(frac - math.exp(-1.0)) <= dpkit.hoeffding_margin(n, 1e-6)


def test_example_values() -> None:
    xs = list(range(101))
    got = [(b, distance_to_instability(xs, b, 100)) for b in (5, 10, 15, 20, 30)]
    assert got == [(5, 5), (10, 10), (15, 15), (20, 20), (30, 30)]
    probs = [pass_probability(g, 1.0, 1e-6) for _, g in got]
    assert probs[0] < 1e-4 and 0.010 < probs[1] < 0.012 and 0.84 < probs[2] < 0.85
    assert probs[3] > 0.998 and probs[4] > 0.999999
    assert distance_to_instability(xs, 100, 100) == math.inf


def test_laplace_tail() -> None:
    rng = random.Random(5)
    n = 20000
    frac = sum(abs(laplace_noise(2.0, rng)) > 3.0 for _ in range(n)) / n
    assert abs(frac - math.exp(-1.5)) <= dpkit.hoeffding_margin(n, 1e-6)


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

History

Nissim, Raskhodnikova and Smith (STOC 2007) showed that noise scaled to the local sensitivity is not safe and gave smooth sensitivity. Dwork and Lei (STOC 2009) gave propose-test-release and used it to make robust estimators of scale, location and regression private. Dwork and Roth (2014) and Vadhan (2017) gave the general form used here, and Vadhan used the stable-value form for private histograms over large universes.

References

  1. Salil Vadhan, The complexity of differential privacy, in Tutorials on the Foundations of Cryptography, Springer, 2017, pages 347 to 450, Section 3: Proposition 3.2 (propose-test-release, (2 epsilon, delta)-DP) and Proposition 3.3 (releasing stable values)
  2. Cynthia Dwork and Aaron Roth, The Algorithmic Foundations of Differential Privacy, Foundations and Trends in Theoretical Computer Science 9(3-4), 2014, Section 7: Algorithm 12 (Scale, the interquartile range) with Theorem 7.1 ((4 epsilon, delta)-DP), and Algorithm 13 (A_dist, release based on the distance to instability)
  3. Cynthia Dwork and Jing Lei, Differential privacy and robust statistics, STOC 2009, the propose-test-release framework and its use for scale, location and regression
  4. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point noise and the snapping defense

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example