Algorithm Search⌘K

Algorithmcore

Report noisy max

Also called noisy argmax.

Adds independent Laplace or exponential noise to each candidate's count and reports only the index of the largest.

Time
O(m) worst
Space
O(1) extra
Where
m = the number of scores
Properties
randomizedrandomized
Origin
Cynthia Dwork, Aaron Roth, 2014

Report noisy max selects the best of mm candidates privately. It adds independent Laplace noise to the score of each candidate, such as a count, and releases only the index of the largest noisy score. For counts under add/remove neighbors, noise of scale 1/ε1/\varepsilon makes the index ε\varepsilon-differentially private, although mm noisy counts released in full would cost mεm\varepsilon. Dwork and Roth (2014) give it with this proof. It is one of the two standard tools for private selection, next to the exponential mechanism.

In plain words

You count the votes for each of several options and want to name the winner without revealing any one vote. You add a little random noise to each count, compare the noisy counts, and say only which option won. You do not show the noisy counts.

Showing all the noisy counts would need much more noise, because every count can leak something. But the winner is only one piece of information. One vote can help only one option, and it can help it by at most one. So the chance that a given option wins changes by at most a small factor when one voter leaves.

The problem

The input is a list of mm scores c1(x),…,cm(x)c_1(x), \ldots, c_m(x) that depend on a dataset xx, a number Δ\Delta and a privacy parameter ε>0\varepsilon > 0. Each score has sensitivity at most Δ\Delta: ∣ci(x)−ci(x′)∣≤Δ|c_i(x) - c_i(x')| \le \Delta for all ii and all neighbors x∼x′x \sim x'. The page uses add/remove neighbors unless it says otherwise.

The scores are monotone under a neighbor relation if, for every pair x∼x′x \sim x', either ci(x)≤ci(x′)c_i(x) \le c_i(x') for all ii, or ci(x)≥ci(x′)c_i(x) \ge c_i(x') for all ii. Counts are monotone under add/remove, because a new record never lowers a count. Under replace, one count can rise while another falls, so counts are not monotone there.

The output is one index i∈{1,…,m}i \in \{1, \ldots, m\}. The map from xx to the distribution of the index must be ε\varepsilon-DP, and the score of the chosen index must be close to max⁡jcj(x)\max_j c_j(x).

The algorithm

  1. REPORT-NOISY-MAX(c_1, ..., c_m, epsilon, Delta, monotone) ▷ each c_i has sensitivity <= Delta
  2. 1b <- Delta / epsilon if monotone else 2 Delta / epsilon
  3. 2best <- -infinity; best_i <- none
  4. 3for i <- 1 to m do
  5. 4y <- c_i + a fresh sample of Lap(b)
  6. 5if y > best then best <- y; best_i <- i
  7. 6return best_i ▷ the noisy scores are never released

Line L1 sets the scale of the noise. Line L4 reads the score of candidate ii, and the scores are the only input that depends on the data. The Laplace sample of line L4 is drawn by inverse transform sampling, as on the Laplace mechanism page. Line L5 keeps the largest noisy score seen so far. Ties have probability 0 in the real RAM; the code gives a tie to the lower index. Line L6 releases only the index. The noisy values yy and the noise are not published, and the privacy proof depends on that.

The code on this site uses floats and a seeded pseudorandom generator, so that the tests can repeat each run. A deployment needs a cryptographic source of randomness and an exact sampler (Mironov 2012).

Example

The candidates are AA, BB and CC, and their vote counts are c=(4,2,3)c = (4, 2, 3). Counts have sensitivity Δ=1\Delta = 1 and are monotone under add/remove. With ε=1\varepsilon = 1, line L1 gives b=1b = 1. Assume that the Laplace sampler of line L4 draws its uniform value uu in (−1/2,1/2)(-1/2, 1/2) as 0.30.3, −0.1-0.1 and 0.450.45, which gives the noise −sgn(u)ln⁡(1−2∣u∣)-\mathrm{sgn}(u)\ln(1 - 2|u|).

step ii cic_i noise yy (line L4) best, best_i (line L5)
L1, L2 b=1b = 1; −∞-\infty, none
L3 to L5 1 4 0.916291 4.916291 4.916291, 1
L3 to L5 2 2 −0.223144-0.223144 1.776856 4.916291, 1
L3 to L5 3 3 2.302585 5.302585 5.302585, 3
L6 return 3

The output is CC, the second best candidate, because its noise was large. Over all noise, the exact output distribution is (0.671265,0.082510,0.246225)(0.671265, 0.082510, 0.246225). A new vote for AA gives the add/remove neighbor with counts (5,2,3)(5, 2, 3) and the distribution (0.833750,0.042318,0.123932)(0.833750, 0.042318, 0.123932). The log ratios of the two distributions are −0.217-0.217, 0.6680.668 and 0.6870.687, all at most ε=1\varepsilon = 1. For comparison, the exponential mechanism with c=1c = 1 on the same counts gives (0.665241,0.090031,0.244728)(0.665241, 0.090031, 0.244728), which is close but not equal.

The accuracy theorem below with β=0.1\beta = 0.1 says that, with probability at least 0.9, the chosen count is at least 4−2ln⁡30=4−6.8023954 - 2\ln 30 = 4 - 6.802395. With only three candidates this bound says nothing. With counts in the thousands it says that the chosen count is within about 7 of the largest.

Correctness

Theorem (privacy; Dwork-Roth Claim 3.9). If every score has sensitivity at most Δ\Delta and the scores are monotone, then REPORT-NOISY-MAX with b=Δ/εb = \Delta/\varepsilon is ε\varepsilon-DP. Without the monotone condition, b=2Δ/εb = 2\Delta/\varepsilon is enough.

The key step fixes the noise r−ir_{-i} of all candidates except ii. For neighbors with cj(x′)≤cj(x)≤cj(x′)+Δc_j(x') \le c_j(x) \le c_j(x') + \Delta for all jj, let r∗r^* be the smallest noise of ii for which ii wins on x′x'. Then any noise ri≥r∗+Δr_i \ge r^* + \Delta makes ii win on xx:

ci(x)+ri≥ci(x′)+r∗+Δ>cj(x′)+rj+Δ≥cj(x)+rjfor all j≠i.c_i(x) + r_i \ge c_i(x') + r^* + \Delta > c_j(x') + r_j + \Delta \ge c_j(x) + r_j \quad \text{for all } j \ne i.

The Laplace density with scale Δ/ε\Delta/\varepsilon changes by at most the factor eεe^{\varepsilon} under a shift by Δ\Delta, so Pr⁡[i wins on x∣r−i]≥e−εPr⁡[i wins on x′∣r−i]\Pr[i \text{ wins on } x \mid r_{-i}] \ge e^{-\varepsilon}\Pr[i \text{ wins on } x' \mid r_{-i}]. The same argument with xx and x′x' swapped gives the other direction, and the average over r−ir_{-i} gives the claim. Without monotone scores, the shift must be 2Δ2\Delta, which is why line L1 doubles the scale. Dwork and Roth prove the case of counts under add/remove. The full proof, for any Δ\Delta and both cases, is in the correctness proof of this page.

Theorem (accuracy). For 0<β<10 < \beta < 1, with probability at least 1−β1 - \beta, the chosen index ii has ci≥max⁡jcj−2bln⁡(m/β)c_i \ge \max_j c_j - 2b\ln(m/\beta). The proof is a union bound over the mm tails Pr⁡[∣Z∣>t]=e−t/b\Pr[|Z| > t] = e^{-t/b}: if every noise is at most bln⁡(m/β)b\ln(m/\beta) in absolute value, the winner cannot be more than twice that below the best.

Proof: Report noisy max is epsilon-DP and picks a nearly best indexfull

We work in the real RAM. Fix a neighbor relation ∼\sim, scores c1,…,cmc_1, \ldots, c_m with m≥1m \ge 1, a number Δ>0\Delta > 0 with ∣ci(x)−ci(x′)∣≤Δ|c_i(x) - c_i(x')| \le \Delta for all ii and all x∼x′x \sim x', and ε>0\varepsilon > 0. Let bb be the scale of line L1. Line L4 draws ri∼Lap(b)r_i \sim \mathrm{Lap}(b), independent for each ii; the sampler is the one of the Laplace mechanism, and the correctness proof of that page shows that it draws Lap(b)\mathrm{Lap}(b). Let pb(z)=12be−∣z∣/bp_b(z) = \frac{1}{2b}e^{-|z|/b}.

Lemma 1 (the loop computes the noisy argmax). Line L6 returns an index ii with ci+ri=max⁡j(cj+rj)c_i + r_i = \max_j (c_j + r_j), the lowest such index if there are ties. Ties have probability 0.

Proof. After pass ii of the loop, best=max⁡j≤i(cj+rj)best = \max_{j \le i}(c_j + r_j) and best_ibest\_i is the lowest index that attains it: line L5 replaces the pair only when the new value is strictly larger. The first pass replaces −∞-\infty, so best_ibest\_i is an index. For i≠ji \ne j the event ci+ri=cj+rjc_i + r_i = c_j + r_j fixes rir_i given rjr_j, and rir_i has a density, so it has probability 0. □\square

So the output is M(x)=arg⁡max⁡j(cj(x)+rj)M(x) = \arg\max_j (c_j(x) + r_j), well defined with probability 1.

Lemma 2 (shift). For every t∈Rt \in \mathbb R and s≥0s \ge 0, Pr⁡[ri≥t+s]≥e−s/bPr⁡[ri≥t]\Pr[r_i \ge t + s] \ge e^{-s/b}\Pr[r_i \ge t].

Proof. For every zz, ∣z+s∣≤∣z∣+s|z + s| \le |z| + s, so pb(z+s)≥e−s/bpb(z)p_b(z + s) \ge e^{-s/b} p_b(z). Then Pr⁡[ri≥t+s]=∫t∞pb(z+s) dz≥e−s/b∫t∞pb(z) dz\Pr[r_i \ge t + s] = \int_t^\infty p_b(z + s)\,dz \ge e^{-s/b}\int_t^\infty p_b(z)\,dz. □\square

Lemma 3 (one direction). Let xx and x′x' be datasets, ii an index and s≥0s \ge 0 a number such that

ci(x)+s≥ci(x′)+(cj(x)−cj(x′))for every j≠i.(∗)c_i(x) + s \ge c_i(x') + (c_j(x) - c_j(x')) \quad \text{for every } j \ne i. \tag{$*$}

Then Pr⁡[M(x)=i]≥e−s/bPr⁡[M(x′)=i]\Pr[M(x) = i] \ge e^{-s/b}\Pr[M(x') = i].

Proof. Fix the noise r−i=(rj)j≠ir_{-i} = (r_j)_{j \ne i}. The index ii wins on x′x' when ri>t′=max⁡j≠i(cj(x′)+rj)−ci(x′)r_i > t' = \max_{j \ne i}(c_j(x') + r_j) - c_i(x'), up to a tie of probability 0, and the event is a half-line in rir_i because the left side ci(x′)+ric_i(x') + r_i grows with rir_i. If ri>t′+sr_i > t' + s, then for every j≠ij \ne i,

ci(x)+ri>ci(x)+t′+s≥ci(x)+cj(x′)+rj−ci(x′)+s≥cj(x)+rj,c_i(x) + r_i > c_i(x) + t' + s \ge c_i(x) + c_j(x') + r_j - c_i(x') + s \ge c_j(x) + r_j,

where the last step is (∗)(*). So ii wins on xx. By Lemma 2 and the independence of rir_i from r−ir_{-i}, Pr⁡[M(x)=i∣r−i]≥Pr⁡[ri>t′+s]≥e−s/bPr⁡[ri>t′]=e−s/bPr⁡[M(x′)=i∣r−i]\Pr[M(x) = i \mid r_{-i}] \ge \Pr[r_i > t' + s] \ge e^{-s/b}\Pr[r_i > t'] = e^{-s/b}\Pr[M(x') = i \mid r_{-i}]. The expectation over r−ir_{-i} gives the claim. □\square

Theorem 1 (privacy). (a) If the scores are monotone and b=Δ/εb = \Delta/\varepsilon, then MM is ε\varepsilon-DP. (b) In general, if b=2Δ/εb = 2\Delta/\varepsilon, then MM is ε\varepsilon-DP.

Proof. Fix x∼x′x \sim x' and an index ii. A set SS of indices has Pr⁡[M(x)∈S]=∑i∈SPr⁡[M(x)=i]\Pr[M(x) \in S] = \sum_{i \in S}\Pr[M(x) = i], so it is enough to prove Pr⁡[M(x)=i]≥e−εPr⁡[M(x′)=i]\Pr[M(x) = i] \ge e^{-\varepsilon}\Pr[M(x') = i] for every ordered pair of neighbors, because the relation is symmetric.

(a) Assume first cj(x′)≤cj(x)c_j(x') \le c_j(x) for all jj, so 0≤cj(x)−cj(x′)≤Δ0 \le c_j(x) - c_j(x') \le \Delta. Then (∗)(*) holds with s=Δs = \Delta: its left side is at least ci(x′)+Δc_i(x') + \Delta and its right side is at most ci(x′)+Δc_i(x') + \Delta. If instead cj(x′)≥cj(x)c_j(x') \ge c_j(x) for all jj, then cj(x)−cj(x′)≤0c_j(x) - c_j(x') \le 0 and ci(x)≥ci(x′)−Δc_i(x) \ge c_i(x') - \Delta, so (∗)(*) holds again with s=Δs = \Delta. By monotonicity one of the two cases holds. Lemma 3 with s/b=Δ/(Δ/ε)=εs/b = \Delta/(\Delta/\varepsilon) = \varepsilon gives the bound.

(b) Without monotonicity, ci(x)≥ci(x′)−Δc_i(x) \ge c_i(x') - \Delta and cj(x)−cj(x′)≤Δc_j(x) - c_j(x') \le \Delta, so (∗)(*) holds with s=2Δs = 2\Delta. Lemma 3 with s/b=2Δ/(2Δ/ε)=εs/b = 2\Delta/(2\Delta/\varepsilon) = \varepsilon gives the bound. □\square

This is the argument of Dwork-Roth Claim 3.9, which treats counts under add/remove neighbors, where case (a) applies with Δ=1\Delta = 1.

Theorem 2 (accuracy). For 0<β<10 < \beta < 1, let i=M(x)i = M(x). Then Pr⁡[ci(x)<max⁡jcj(x)−2bln⁡(m/β)]≤β\Pr[c_i(x) < \max_j c_j(x) - 2b\ln(m/\beta)] \le \beta.

Proof. Let t=bln⁡(m/β)t = b\ln(m/\beta). For each jj, Pr⁡[∣rj∣>t]=2∫t∞pb=e−t/b=β/m\Pr[|r_j| > t] = 2\int_t^\infty p_b = e^{-t/b} = \beta/m. By the union bound, with probability at least 1−β1 - \beta every ∣rj∣≤t|r_j| \le t. In that event, let kk be an index with the largest score. Since ii wins, ci+ri≥ck+rkc_i + r_i \ge c_k + r_k, so ci≥ck+rk−ri≥ck−2tc_i \ge c_k + r_k - r_i \ge c_k - 2t. □\square

Complexity

The model is the real RAM: a uniform real number, a logarithm and a comparison each cost one step. The cost is counted after the mm scores are computed.

  • Time. The loop of line L3 runs mm times, and each pass draws one Laplace sample and does one comparison. So the time is O(m)O(m) in the worst case.
  • Space. The loop keeps the best value and its index, and each noise is used once and dropped. So the extra space is O(1)O(1), and the scores can come one at a time from a stream.

Properties

  • Pure privacy for one index. The index is (ε,0)(\varepsilon, 0)-DP, at the cost of one noisy count and not mm. The tests compute the exact output distribution by numerical integration on every dataset of at most 3 records over 3 values. For counts under add/remove with b=1/εb = 1/\varepsilon, the largest log ratio is 0.910 for ε=1\varepsilon = 1 and 0.428 for ε=0.5\varepsilon = 0.5 (a measurement on the test data).
  • Utility that grows like ln⁡m\ln m. The chosen score is within O(bln⁡m)O(b\ln m) of the best with high probability, and this does not depend on the size of the dataset.
  • Not the exponential mechanism. Laplace noise gives a different distribution from the exponential mechanism, although the guarantees are similar (Dwork-Roth Remark 3.1). Gumbel noise in line L4, with the scores scaled as in the exponential mechanism, gives exactly the exponential mechanism.
  • Closed under post-processing. Any map of the index that does not read xx keeps ε\varepsilon-DP, by the post-processing theorem.

Variants and improvements

  • One-sided exponential noise. Report one-sided noisy arg-max adds noise from the exponential distribution with parameter ε/Δ\varepsilon/\Delta for monotone scores and ε/(2Δ)\varepsilon/(2\Delta) otherwise (Dwork-Roth Section 3.4 and Theorem 3.13). The noise is never negative, so a bad candidate needs a large draw to win.
  • Gumbel noise. Gumbel noise gives the exponential mechanism exactly, by the Gumbel max trick.
  • Integer counts. For integer scores, a discrete noise such as that of the geometric mechanism avoids floats, but then ties have positive probability and need a fixed rule.
  • Inside larger algorithms. PATE uses a noisy max of the votes of teacher models to label each query. The sparse vector technique uses a similar argument for the first query above a noisy threshold. MWEM needs one selection per round, done by the exponential mechanism or by report noisy max.

When to use it

Use report noisy max to choose the best of a moderate number of candidates whose scores are counts or other low-sensitivity numbers, when only the identity of the best is needed. It is simple, it streams, and the proof is short. If the utility is not a sum of simple counts, or the candidate set is very large and structured, use the exponential mechanism, which also allows any base measure. If you need the value of the best score as well, use a second, separate query.

Pitfalls

  • Releasing the noisy score. The privacy proof covers only the index. Publishing the largest noisy value, or all noisy values, is not covered. To publish the score of the winner, answer it with a fresh Laplace query and pay for it by the sequential composition theorem.
  • The wrong neighbor relation. Counts are not monotone under replace. With b=1/εb = 1/\varepsilon, the tests measure a largest log ratio of 1.556 for ε=1\varepsilon = 1 under replace, so it is not 11-DP there. With b=2/εb = 2/\varepsilon the measured value is 0.706.
  • Scores that are not monotone. A score such as the error of a query, or a count minus another count, can move in both directions between neighbors. Then line L1 must use 2Δ/ε2\Delta/\varepsilon.
  • Candidates that depend on the data. The list of candidates must be fixed in advance. A list built from the values that occur in xx leaks those values.
  • Float noise. Line L4 on floats with a non-cryptographic generator is fine for study, but not for a release.

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
report_noisy_max.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/report-noisy-max/. The authors are listed in prov/GKS5RH.jsonl.
"""Report Noisy Max with Laplace noise (Dwork and Roth, Claim 3.9).

Add independent Laplace noise to each of m scores and release only the index
of the largest noisy score. For counting queries under add/remove neighbors
the scale Delta / epsilon is enough (monotone=True). For scores whose changes
can go in both directions the scale is 2 Delta / epsilon (monotone=False).

Floats and random.Random are used so that the tests are reproducible; a
deployment needs a cryptographic source of randomness and exact sampling.
"""

from __future__ import annotations

import math
import random
from typing import Sequence


def laplace_sample(b: float, rng: random.Random) -> float:
    """One draw of Lap(b) by the inverse CDF. Cost: O(1)."""
    u = rng.random() - 0.5
    while u == -0.5:
        u = rng.random() - 0.5
    return -b * math.copysign(1.0, u) * math.log(1.0 - 2.0 * abs(u))


def noise_scale(sensitivity: float, epsilon: float, monotone: bool = True) -> float:
    """b = Delta / epsilon if the scores are monotone in the data, else 2 Delta / epsilon."""
    if sensitivity <= 0 or epsilon <= 0:
        raise ValueError("need sensitivity > 0 and epsilon > 0")
    return (1.0 if monotone else 2.0) * sensitivity / epsilon


def report_noisy_max(
    scores: Sequence[float],
    epsilon: float,
    rng: random.Random,
    sensitivity: float = 1.0,
    monotone: bool = True,
) -> int:
    """Return the index of the largest score after Lap(b) noise is added to each score.

    Precondition: at least one score; each score has sensitivity at most
    Delta under the chosen neighbor relation; monotone=True only if every
    score moves in the same direction between neighbors. Ties, which have
    probability 0, go to the lowest index. Only the index is released.
    Cost: O(m) for m scores.
    """
    if not scores:
        raise ValueError("need at least one score")
    b = noise_scale(sensitivity, epsilon, monotone)  # @line L1
    best, best_i = -math.inf, -1  # @line L2
    for i, c in enumerate(scores):  # @line L3
        y = c + laplace_sample(b, rng)  # @line L4
        if y > best:  # @line L5
            best, best_i = y, i
    return best_i  # @line L6


def accuracy_gap(b: float, m: int, beta: float) -> float:
    """2 b ln(m / beta): with probability at least 1 - beta, the chosen score is within this of the maximum."""
    if m < 1 or not 0 < beta < 1:
        raise ValueError("need m >= 1 and 0 < beta < 1")
    return 2.0 * b * math.log(m / beta)
test_report_noisy_max.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/report-noisy-max/. The authors are listed in prov/GKS5RH.jsonl.

import itertools
import math
import random

import pytest

import dpkit
from report_noisy_max import accuracy_gap, laplace_sample, noise_scale, report_noisy_max

UNIVERSE = (0, 1, 2)


def lap_pdf(z, b):
    return math.exp(-abs(z) / b) / (2 * b)


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


def simpson(g, a, b, n):
    h = (b - a) / n
    s = g(a) + g(b)
    for i in range(1, n):
        s += (4 if i % 2 else 2) * g(a + i * h)
    return s * h / 3


def exact_pmf(scores, b):
    """Oracle: P(index i wins) = integral of pdf_i(y) prod_{j != i} cdf_j(y) dy.

    The integrand is smooth between the scores, so Simpson's rule is used on
    each piece between sorted break points, with a step of at most b / 12
    between the scores. The tails go out to 40 b on pieces that grow as the
    integrand decays, with at most 64 steps per piece. The total error is
    below 1e-5 on the inputs of these tests.
    """
    pts = sorted(set(scores))
    steps = (40, 24, 12, 6, 3, 1)
    edges = [pts[0] - k * b for k in steps] + pts + [pts[-1] + k * b for k in reversed(steps)]
    out = {}
    for i, ci in enumerate(scores):
        def g(y, i=i, ci=ci):
            v = lap_pdf(y - ci, b)
            for j, cj in enumerate(scores):
                if j != i:
                    v *= lap_cdf(y - cj, b)
            return v
        total = 0.0
        for lo, hi in zip(edges, edges[1:]):
            if hi > lo:
                steps_here = max(8, 2 * math.ceil(6 * (hi - lo) / b))
                if lo < pts[0] or hi > pts[-1]:
                    steps_here = min(64, steps_here)
                total += simpson(g, lo, hi, steps_here)
        out[i] = total
    return out


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


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


ADD_REMOVE = [(x, y) for x in all_datasets(3) for y in dpkit.neighbors_add_remove(x, UNIVERSE)]
REPLACE = [(x, y) for x in all_datasets(3) for y in dpkit.neighbors_replace(x, UNIVERSE)]


def worst_loss(b, pairs):
    cache = {}

    def mech(x):
        h = histogram(x)
        if h not in cache:
            cache[h] = exact_pmf(list(h), b)
        return cache[h]

    best = 0.0
    for x, y in pairs:
        p, q = mech(x), mech(y)
        best = max(best, dpkit.max_privacy_loss(p, q), dpkit.max_privacy_loss(q, p))
    return best


def test_oracle_sums_to_one_and_is_symmetric():
    rng = random.Random(40)
    for _ in range(200):
        m = rng.randint(1, 4)
        scores = [rng.randint(0, 5) for _ in range(m)]
        pmf = exact_pmf(scores, rng.uniform(0.5, 3.0))
        assert abs(sum(pmf.values()) - 1) < 1e-5
        for i in range(m):
            for j in range(m):
                if scores[i] == scores[j]:
                    assert abs(pmf[i] - pmf[j]) < 1e-9
                if scores[i] > scores[j]:
                    assert pmf[i] > pmf[j]


def test_counts_under_add_remove_are_epsilon_dp():
    for eps in (0.5, 1.0):
        loss = worst_loss(noise_scale(1, eps), ADD_REMOVE)
        assert loss <= eps + 1e-5


def test_counts_under_replace_with_scale_one_over_epsilon():
    # A measurement: under replace one count rises and another falls.
    # The scale 1 / epsilon then gives a loss near 1.556 > 1 on these datasets.
    eps = 1.0
    loss = worst_loss(noise_scale(1, eps, monotone=True), REPLACE)
    assert loss > 1.5 * eps
    assert worst_loss(noise_scale(1, eps, monotone=False), REPLACE) <= eps + 1e-5


def test_sampler_matches_oracle():
    rng = random.Random(41)
    n = 2000
    scores = [3, 1, 2, 3]
    b = noise_scale(1, 1.0)
    pmf = exact_pmf(scores, b)
    emp = dpkit.empirical_pmf(report_noisy_max(scores, 1.0, rng) for _ in range(n))
    t = dpkit.hoeffding_margin(n, 1e-6 / len(scores))
    for i in range(len(scores)):
        assert abs(emp.get(i, 0.0) - pmf[i]) <= t


def test_laplace_sampler_tail():
    rng = random.Random(42)
    n = 2000
    b = 2.0
    hits = sum(abs(laplace_sample(b, rng)) > 4.6052 for _ in range(n))
    assert abs(hits / n - 0.1) <= dpkit.hoeffding_margin(n, 1e-6)


def test_accuracy_bound_holds_on_random_instances():
    rng = random.Random(43)
    for _ in range(500):
        m = rng.randint(1, 4)
        scores = [rng.randint(0, 6) for _ in range(m)]
        eps = rng.uniform(0.3, 1.5)
        beta = rng.uniform(0.01, 0.5)
        b = noise_scale(1, eps)
        pmf = exact_pmf(scores, b)
        gap = accuracy_gap(b, m, beta)
        bad = sum(p for i, p in pmf.items() if scores[i] < max(scores) - gap)
        assert bad <= beta + 1e-5


def test_edge_cases():
    rng = random.Random(0)
    with pytest.raises(ValueError):
        report_noisy_max([], 1.0, rng)
    with pytest.raises(ValueError):
        report_noisy_max([1, 2], 0.0, rng)
    with pytest.raises(ValueError):
        accuracy_gap(1.0, 0, 0.1)
    assert report_noisy_max([7], 1.0, rng) == 0
    assert noise_scale(2, 0.5) == 4.0
    assert noise_scale(2, 0.5, monotone=False) == 8.0
    # A huge gap makes the true maximum win almost surely.
    assert all(report_noisy_max([0, 1000, 0], 1.0, rng) == 1 for _ in range(200))

History

Dwork and Roth (2014) present report noisy max with Laplace noise in Section 3.3 of their monograph and prove that it is ε\varepsilon-DP for counts. In Section 3.4 they define monotone utilities, give the one-sided exponential variant, and remark that Gumbel noise gives the exponential mechanism of McSherry and Talwar (2007). Later algorithms, such as PATE for private machine learning, use report noisy max as their selection step.

References

  1. 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 Report Noisy Max algorithm and Claim 3.9 (privacy); Section 3.4, the definition of a monotonic function, Theorem 3.13 (report one-sided noisy arg-max) and Remark 3.1 (Gumbel noise)
  2. Frank McSherry and Kunal Talwar, Mechanism design via differential privacy, FOCS 2007, pages 94 to 103, the exponential mechanism, the other standard tool for private selection
  3. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why float Laplace noise is not enough for a release

Where this leads

About this page

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

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