Algorithm Search⌘K

Algorithmresearch

Optimized local hashing

Also called OLH.

A local frequency oracle in which each user hashes the value into a small range and applies generalized randomized response to the hash.

Time
O(n d) worst
Space
O(d) extra
Where
d = the size of the domain; n = the number of reports
Properties
randomizedrandomized
Origin
Tianhao Wang, Jeremiah Blocki, Ninghui Li, Somesh Jha, 2017

Optimized local hashing (OLH) is a local frequency oracle: it lets a collector estimate how many clients hold each value of a domain of size dd, while each client's report is ε\varepsilon-locally differentially private. Each client picks a random hash function HH from a family into {0,…,g−1}\{0, \ldots, g - 1\}, and applies generalized randomized response to H(v)H(v), not to vv. It sends HH (as a seed) and the noisy hash value. Wang, Blocki, Li and Jha (2017) showed that g=eε+1g = e^{\varepsilon} + 1 minimizes the variance, which is then n⋅4eε/(eε−1)2n \cdot 4e^{\varepsilon}/(e^{\varepsilon} - 1)^2 for nn clients. This does not depend on dd, while plain randomized response over dd values has a variance that grows with dd.

In plain words

Each client wants to report one item from a long list, such as a web page, without saying which one. Randomized response over the whole list works badly: when the list is long, the true item is only rarely sent.

So each client first picks a random way to sort all items into a few buckets, say four. It finds the bucket of its item, and then sends that bucket truthfully with some probability, or one of the other buckets. It also says which way of sorting it used.

The collector checks, for each item, how many reports point to that item's bucket. Items that many clients hold get extra hits. The collector subtracts the expected number of chance hits.

The problem

Each of nn clients holds a value vu∈{0,…,d−1}v_u \in \{0, \ldots, d - 1\}. The collector wants, for every value vv, an estimate of nvn_v, the number of clients that hold vv. Each client sends one report, and the report must be ε\varepsilon-LDP: for all values u,u′u, u' and every report rr, Pr⁡[R(u)=r]≤eεPr⁡[R(u′)=r]\Pr[R(u) = r] \le e^{\varepsilon}\Pr[R(u') = r]. The neighbor relation is replace: one client changes its value. The goal is a small variance of each estimate, and a short report.

The algorithm

The parameter is the exact rational eε>1e^{\varepsilon} > 1. Let gg be the hash range and p=eε/(eε+g−1)p = e^{\varepsilon}/(e^{\varepsilon} + g - 1). The family {Hs}\{H_s\} must satisfy Pr⁡s[Hs(u)=Hs(v)]=1/g\Pr_s[H_s(u) = H_s(v)] = 1/g for all u≠vu \ne v (a universal hashing property).

  1. OLH-REPORT(v, e^epsilon) ▷ run by the client
  2. 1s <- a uniform seed of the hash family
  3. 2x <- H_s(v) ▷ a value in {0, ..., g - 1}
  4. 3if a coin with Pr[1] = p gives 1 then
  5. 4return (s, x) ▷ send the true hash value
  6. 5y <- a uniform value of {0, ..., g - 1} other than x; return (s, y)
  7. OLH-ESTIMATE(reports, e^epsilon) ▷ run by the collector; n reports
  8. 6for each value v: C(v) <- the number of reports (s, y) with H_s(v) = y
  9. 7c(v) <- (C(v) - n/g) / (p - 1/g)
  10. 8return c

Lines L1 and L2 hash the value with a fresh random function. Lines L3 to L5 are generalized randomized response over the gg hash values: the true value with probability pp, and each of the other g−1g - 1 values with probability (1−p)/(g−1)(1 - p)/(g - 1). The report is the pair of the seed and the value.

Line L6 counts the reports that "support" vv: those whose hash function maps vv to the reported value. A client that holds vv supports it with probability pp. A client that holds another value supports vv with probability exactly 1/g1/g, by the collision property. Line L7 removes the expected n/gn/g chance supports and scales the rest, which gives an unbiased estimate.

The choice of gg trades two effects. A large gg makes chance supports rare, but then the true hash value is sent with a small probability. The variance is smallest at g=eε+1g = e^{\varepsilon} + 1. The code takes the best integer: ⌊eε⌋+1\lfloor e^{\varepsilon} \rfloor + 1 or ⌊eε⌋+2\lfloor e^{\varepsilon} \rfloor + 2, whichever gives the smaller variance. Plain rounding of eε+1e^{\varepsilon} + 1 is not always best: at eε=2.45e^{\varepsilon} = 2.45, g=4g = 4 beats g=3g = 3.

The code uses the family of all functions from the domain to {0,…,g−1}\{0, \ldots, g - 1\}, where the seed ss is a number below gdg^d and Hs(v)H_s(v) is digit vv of ss in base gg. This family has the collision property exactly, so the tests can check every claim with fractions. Its seeds have dlog⁡2gd \log_2 g bits, so a deployment uses a family with short seeds instead. The coins use exact fractions, and a deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012).

Example

Take eε=3e^{\varepsilon} = 3 and d=4d = 4. Then g=4g = 4 and p=3/6=1/2p = 3/6 = 1/2. Four clients report. The seed ss is a number below 44=2564^4 = 256, and the table lists Hs(0),…,Hs(3)H_s(0), \ldots, H_s(3), the base-4 digits of ss from the lowest.

client vv seed ss (line L1) Hs(0..3)H_s(0..3) xx (line L2) coin (line L3) report
1 2 201 1, 2, 0, 3 0 keep (201, 0)
2 2 54 2, 1, 3, 0 3 change, y=1y = 1 (54, 1)
3 0 147 3, 0, 1, 2 3 keep (147, 3)
4 2 30 2, 3, 1, 0 1 keep (30, 1)

Line L6 checks each value against each report. Value 2 is supported by reports 1 and 4, so C(2)=2C(2) = 2. Value 0 is supported by report 3 only, value 1 by report 2 only (a chance support), and value 3 by none. Line L7 gives c(v)=(C(v)−1)/(1/4)=4(C(v)−1)c(v) = (C(v) - 1)/(1/4) = 4(C(v) - 1), which is 0,0,4,−40, 0, 4, -4. The true counts are 1,0,3,01, 0, 3, 0.

With four clients the estimate is very noisy: by Theorem 2 below, the standard deviation is about 4⋅3=3.5\sqrt{4 \cdot 3} = 3.5. For n=10000n = 10000 clients and d=1024d = 1024, the standard deviation is 3n=173.2\sqrt{3n} = 173.2 for OLH, against 1600.8 for randomized response over all 1024 values, whose variance per client is (d−2+eε)/(eε−1)2(d - 2 + e^{\varepsilon})/(e^{\varepsilon} - 1)^2.

Correctness

Theorem 1 (privacy). Each report is ε\varepsilon-LDP, and the bound is tight.

A report (s,y)(s, y) has probability p/∣S∣p/|\mathcal S| if y=Hs(v)y = H_s(v) and (1−p)/((g−1)∣S∣)(1 - p)/((g - 1)|\mathcal S|) otherwise. The ratio of the two is p(g−1)/(1−p)=eεp(g - 1)/(1 - p) = e^{\varepsilon}, for every gg.

Theorem 2 (unbiased estimate; Wang, Blocki, Li and Jha, Theorem 2 for pure protocols). If the family has the collision property, then E[c(v)]=nv\mathbb E[c(v)] = n_v and

Var[c(v)]=nv p(1−p)+(n−nv) q(1−q)(p−q)2,q=1g.\mathrm{Var}[c(v)] = \frac{n_v\,p(1 - p) + (n - n_v)\,q(1 - q)}{(p - q)^2}, \qquad q = \frac1g.

Theorem 3 (the best range). The approximate variance Var∗=nq(1−q)/(p−q)2\mathrm{Var}^* = n q(1 - q)/(p - q)^2 is smallest at g=eε+1g = e^{\varepsilon} + 1, with the value n⋅4eε/(eε−1)2n \cdot 4e^{\varepsilon}/(e^{\varepsilon} - 1)^2.

The key step of Theorem 2 is that a client with another value supports vv with probability p/g+(1−1/g)(1−p)/(g−1)=1/gp/g + (1 - 1/g)(1 - p)/(g - 1) = 1/g. The full proofs are in the correctness proof of this page. The tests check the privacy with exact fractions, and the mean and variance against an exact sum over the pmf of each report, on 500 random datasets.

Proof: Optimized local hashing is epsilon-LDP, its estimate is unbiased, and g = e^epsilon + 1 minimizes the variancefull

Let the domain be {0,…,d−1}\{0, \ldots, d - 1\}, let g≥2g \ge 2, and let H={Hs:s∈S}\mathcal H = \{H_s : s \in \mathcal S\} be a finite family of functions from the domain to {0,…,g−1}\{0, \ldots, g - 1\} with the collision property

Pr⁡s[Hs(u)=Hs(v)]=1gfor all u≠v,(1)\Pr_s[H_s(u) = H_s(v)] = \frac1g \qquad \text{for all } u \ne v, \tag{1}

where ss is uniform on S\mathcal S. The family of all functions has property (1), because the digits of a uniform seed in base gg are independent and uniform. Write e=eε≥1e = e^{\varepsilon} \ge 1 (rational), p=e/(e+g−1)p = e/(e + g - 1) and q=1/gq = 1/g. Let R(v)R(v) be the report of line L1 to line L5 on the value vv.

Lemma 1 (the pmf of one report). For every seed ss and every yy,

Pr⁡[R(v)=(s,y)]=1∣S∣⋅{pif y=Hs(v),(1−p)/(g−1)otherwise.\Pr[R(v) = (s, y)] = \frac{1}{|\mathcal S|} \cdot \begin{cases} p & \text{if } y = H_s(v), \\ (1 - p)/(g - 1) & \text{otherwise.}\end{cases}

Proof. Line L1 picks ss uniformly, and line L2 sets x=Hs(v)x = H_s(v). Line L3 compares a uniform integer below the denominator of pp with its numerator, so it keeps xx (line L4) with probability pp exactly. Otherwise line L5 draws rr uniform on {0,…,g−2}\{0, \ldots, g - 2\} and maps it to rr or r+1r + 1. This map is a bijection onto the g−1g - 1 values other than xx, so each of them has probability (1−p)/(g−1)(1 - p)/(g - 1). □\square

Theorem 1 (privacy). RR is ε\varepsilon-LDP. If some seed has Hs(u)≠Hs(v)H_s(u) \ne H_s(v), no smaller ε\varepsilon holds for the pair u,vu, v.

Proof. By Lemma 1, the ratio Pr⁡[R(u)=(s,y)]/Pr⁡[R(v)=(s,y)]\Pr[R(u) = (s, y)]/\Pr[R(v) = (s, y)] is one of 11, p(g−1)/(1−p)p(g - 1)/(1 - p) and its inverse. Since 1−p=(g−1)/(e+g−1)1 - p = (g - 1)/(e + g - 1), we get p(g−1)/(1−p)=ep(g - 1)/(1 - p) = e. So the ratio is at most eεe^{\varepsilon}, and it equals eεe^{\varepsilon} at (s,Hs(u))(s, H_s(u)) for a seed with Hs(u)≠Hs(v)H_s(u) \ne H_s(v). □\square

Lemma 2 (the support probability). Fix a value vv, and let Iu=[Hs(v)=y]I_u = [H_s(v) = y] for the report (s,y)=R(u)(s, y) = R(u). Then Pr⁡[Iu=1]=p\Pr[I_u = 1] = p if u=vu = v, and Pr⁡[Iu=1]=q=1/g\Pr[I_u = 1] = q = 1/g if u≠vu \ne v.

Proof. If u=vu = v, then Iu=1I_u = 1 exactly when line L4 runs, which has probability pp. If u≠vu \ne v, condition on ss. When Hs(u)=Hs(v)H_s(u) = H_s(v), the probability of y=Hs(v)y = H_s(v) is pp. When Hs(u)≠Hs(v)H_s(u) \ne H_s(v), it is (1−p)/(g−1)(1 - p)/(g - 1). By (1),

Pr⁡[Iu=1]=pg+(1−1g)1−pg−1=pg+1−pg=1g.□\Pr[I_u = 1] = \frac{p}{g} + \left(1 - \frac1g\right)\frac{1 - p}{g - 1} = \frac{p}{g} + \frac{1 - p}{g} = \frac1g. \qquad \square

Theorem 2 (unbiased estimate). Let nn clients send one independent report each, and let nvn_v of them hold vv. If e>1e > 1, the estimate c~(v)\tilde c(v) of line L7 has E[c~(v)]=nv\mathbb E[\tilde c(v)] = n_v and

Var[c~(v)]=nv p(1−p)+(n−nv) q(1−q)(p−q)2.\mathrm{Var}[\tilde c(v)] = \frac{n_v\,p(1 - p) + (n - n_v)\,q(1 - q)}{(p - q)^2}.

Proof. Line L6 computes C(v)=∑uIuC(v) = \sum_u I_u, a sum of nn independent indicators. By Lemma 2, E[C(v)]=nvp+(n−nv)q=nv(p−q)+nq\mathbb E[C(v)] = n_v p + (n - n_v) q = n_v(p - q) + nq. Since e>1e > 1, p>qp > q. Line L7 is c~(v)=(C(v)−nq)/(p−q)\tilde c(v) = (C(v) - nq)/(p - q), so its mean is nvn_v. The variance of C(v)C(v) is the sum of the variances p(1−p)p(1 - p) and q(1−q)q(1 - q) of the indicators, and the affine map divides it by (p−q)2(p - q)^2. □\square

When nvn_v is small against nn, the variance is close to Var∗=nq(1−q)/(p−q)2\mathrm{Var}^* = n q(1 - q)/(p - q)^2, the quantity that Wang, Blocki, Li and Jha minimize.

Theorem 3 (the best range). As a function of a real g>1g > 1, Var∗\mathrm{Var}^* is minimized at g=e+1g = e + 1, where Var∗=n⋅4e/(e−1)2\mathrm{Var}^* = n \cdot 4e/(e - 1)^2. Over the integers g≥2g \ge 2, with t=⌊e⌋t = \lfloor e \rfloor, the minimum is at g=t+2g = t + 2 if e2>t(t+1)e^2 > t(t + 1) and at g=t+1g = t + 1 otherwise.

Proof. Let t=g−1>0t = g - 1 > 0. Then p−q=ee+t−1t+1=(e−1)t(e+t)(t+1)p - q = \frac{e}{e + t} - \frac{1}{t + 1} = \frac{(e - 1)t}{(e + t)(t + 1)} and q(1−q)=t(t+1)2q(1 - q) = \frac{t}{(t + 1)^2}. So

Var∗n=t(t+1)2⋅(e+t)2(t+1)2(e−1)2t2=(e+t)2(e−1)2 t=1(e−1)2(e2t+2e+t).\frac{\mathrm{Var}^*}{n} = \frac{t}{(t + 1)^2} \cdot \frac{(e + t)^2 (t + 1)^2}{(e - 1)^2 t^2} = \frac{(e + t)^2}{(e - 1)^2\,t} = \frac{1}{(e - 1)^2}\left(\frac{e^2}{t} + 2e + t\right).

The function ϕ(t)=e2/t+t\phi(t) = e^2/t + t is strictly convex on t>0t > 0, with ϕ′(t)=1−e2/t2\phi'(t) = 1 - e^2/t^2, which is zero at t=et = e. So the real minimum is at g=e+1g = e + 1, and its value is (2e)2/((e−1)2e)=4e/(e−1)2(2e)^2/((e - 1)^2 e) = 4e/(e - 1)^2.

Over the integers, convexity puts the minimum at t=⌊e⌋t = \lfloor e \rfloor or t=⌊e⌋+1t = \lfloor e \rfloor + 1. With t0=⌊e⌋≥1t_0 = \lfloor e \rfloor \ge 1, ϕ(t0)−ϕ(t0+1)=e2/(t0(t0+1))−1\phi(t_0) - \phi(t_0 + 1) = e^2/(t_0(t_0 + 1)) - 1, which is positive exactly when e2>t0(t0+1)e^2 > t_0(t_0 + 1). □\square

Theorem 1 gives the privacy of each client, Theorem 2 gives the correctness of the collector, and Theorem 3 justifies the choice of gg in the code. Property (1) holds exactly for the family of all functions used in the code; a family with only approximate collisions gives a small bias in Theorem 2. ■\blacksquare

Complexity

The model is the word RAM, with a hash evaluation counted as O(1)O(1) word operations.

  • Client. Lines L1 to L5 take O(1)O(1) time and three uniform draws. The report has log⁡2∣S∣+log⁡2g\log_2 |\mathcal S| + \log_2 g bits. With a family of short seeds this is O(log⁡n)O(\log n) bits; with the family of all functions it is dlog⁡2gd \log_2 g bits.
  • Collector. Line L6 evaluates one hash for each pair of a report and a value, so the estimate of all dd counts takes O(nd)O(n d) time. The extra space is O(d)O(d) for the counts. For a large domain the collector estimates only a list of candidate values.

Properties

  • Pure. In the terms of Wang, Blocki, Li and Jha, OLH is a pure protocol: the support probability is pp for the true value and a constant qq for every other value. This makes the estimate of line L7 unbiased.
  • The variance does not depend on dd. At the best gg, Var∗/n=4eε/(eε−1)2\mathrm{Var}^*/n = 4e^{\varepsilon}/(e^{\varepsilon} - 1)^2. For eε=3e^{\varepsilon} = 3 it is 3. Randomized response over dd values has Var∗/n=(d−2+eε)/(eε−1)2\mathrm{Var}^*/n = (d - 2 + e^{\varepsilon})/(e^{\varepsilon} - 1)^2, which is 256.25 for d=1024d = 1024.
  • Short reports. Optimized unary encoding, from the same paper, has the same variance, but its report has dd bits.
  • Slow decoding. The collector does O(nd)O(n d) work, more than unary encoding, which only adds the bit vectors.
  • One report per client. A second report of the same value with a fresh seed spends ε\varepsilon again, by sequential composition. OLH has no permanent step like RAPPOR.

Variants and improvements

  • Binary local hashing. With g=2g = 2, the report is one bit plus a seed. This is close to the protocol of Bassily and Smith (2015). By Theorem 3 it is the best integer range only when eε≤2e^{\varepsilon} \le \sqrt 2.
  • Optimized unary encoding. Encode vv as a one-hot vector of dd bits, and send each bit with randomized response with different probabilities for ones and zeros. It has the same variance as OLH, a longer report and faster decoding.
  • Large domains and heavy hitters. A frequency oracle for a domain of 2642^{64} values cannot test every value. Later protocols run OLH on prefixes or on hashes of the value, and keep only the frequent ones.
  • Shuffling. If the reports are mixed before the collector reads them, the central loss is much smaller (privacy amplification by shuffling).

When to use it

Use OLH when the collector is not trusted, each client reports once, the domain is too large for plain randomized response (roughly when d>3eε+2d > 3e^{\varepsilon} + 2, the point where the two variances cross), and the collector can afford O(nd)O(n d) work or has a candidate list. Use plain randomized response for a small domain. Use RAPPOR when one client reports the same value many times.

Pitfalls

  • The wrong correction. Line L7 with C(v)/pC(v)/p, or with n/dn/d in place of n/gn/g, is biased. Line L7 must subtract n/gn/g, the expected number of chance supports, and divide by p−1/gp - 1/g.
  • A weak hash family. If line L1 uses a family whose collision probability is not 1/g1/g, the chance supports of line L6 are not n/gn/g on average, and line L7 is biased. Use a family with a known collision probability, and use that probability in line L7.
  • A seed that the client does not choose at random. If line L1 uses the same seed for all clients, then all clients with values in the same bucket look the same, and the collector cannot tell those values apart. Each client must draw its own seed.
  • A float coin. Line L3 written as "random float below pp" gives a probability that differs a little from pp. Compare a uniform integer with the numerator of the exact fraction.
  • Ignoring the range choice. Line L2 with a fixed g=2g = 2 for a large ε\varepsilon wastes privacy budget: at eε=9e^{\varepsilon} = 9, g=2g = 2 gives Var∗/n=1.5625\mathrm{Var}^*/n = 1.5625 against 0.56250.5625 at g=10g = 10.

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
optimized_local_hashing.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimized-local-hashing/. The authors are listed in prov/4AE9P1.jsonl.
"""Optimized local hashing (Wang, Blocki, Li and Jha, USENIX Security 2017).

Each client picks a random hash function H from a family that maps the domain
{0, ..., d - 1} into {0, ..., g - 1}, hashes its value, and applies generalized
randomized response over the g hash values. It sends the hash function (its
seed) and the noisy hash value. The collector counts, for each candidate value
v, the reports whose hash function maps v to the reported value, and removes
the bias. The choice g = e^epsilon + 1 minimizes the variance.

The parameter exp_epsilon is the exact rational number e^epsilon, so the coin
is exact. The family here is the family of all functions from the domain to
{0, ..., g - 1}, indexed by a seed s in [0, g^d): H_s(v) is digit v of s in
base g. It is exactly uniform, which the proofs use; a deployment uses a
family with a short seed. random.Random is used only so that the tests are
reproducible; a deployment needs a cryptographic source of randomness.
"""

from __future__ import annotations

import random
from dataclasses import dataclass
from fractions import Fraction
from typing import Sequence

Report = tuple[int, int]


@dataclass(frozen=True)
class AllFunctions:
    """All g^d functions from {0, ..., d - 1} to {0, ..., g - 1}; seed s gives H_s(v) = digit v of s in base g."""

    d: int
    g: int

    def __post_init__(self) -> None:
        if self.d < 1 or self.g < 2:
            raise ValueError("need d >= 1 and g >= 2")

    @property
    def seeds(self) -> int:
        return self.g ** self.d

    def hash(self, seed: int, v: int) -> int:
        return (seed // self.g ** v) % self.g


def optimal_range(exp_epsilon: Fraction) -> int:
    """The integer g >= 2 that minimizes Var*; the real minimizer is g = e^epsilon + 1.

    With t = g - 1, Var* is proportional to e^2 / t + t, which is convex, so the
    best integer t is floor(e) or floor(e) + 1, and floor(e) + 1 wins exactly
    when e^2 > floor(e) (floor(e) + 1). Precondition: exp_epsilon > 1.
    """
    e = Fraction(exp_epsilon)
    if e <= 1:
        raise ValueError("need exp_epsilon > 1")
    t = e.numerator // e.denominator
    if e * e > t * (t + 1):
        t += 1
    return t + 1


def keep_probability(exp_epsilon: Fraction, g: int) -> Fraction:
    """p = e^epsilon / (e^epsilon + g - 1), the chance that the true hash value is sent."""
    e = Fraction(exp_epsilon)
    return e / (e + g - 1)


def olh_report(v: int, exp_epsilon: Fraction, family: AllFunctions, rng: random.Random) -> Report:
    """One OLH report (seed, y) of the value v.

    Precondition: 0 <= v < d and exp_epsilon >= 1 is rational. The report is
    epsilon-LDP. Cost: O(1) arithmetic and three uniform draws.
    """
    if not 0 <= v < family.d:
        raise ValueError("value out of the domain")
    if Fraction(exp_epsilon) < 1:
        raise ValueError("need exp_epsilon >= 1")
    p = keep_probability(exp_epsilon, family.g)
    s = rng.randrange(family.seeds)  # @line L1
    x = family.hash(s, v)  # @line L2
    if rng.randrange(p.denominator) < p.numerator:  # @line L3
        return (s, x)  # @line L4
    r = rng.randrange(family.g - 1)  # @line L5
    y = r if r < x else r + 1
    return (s, y)


def olh_estimate(reports: Sequence[Report], exp_epsilon: Fraction, family: AllFunctions) -> list[Fraction]:
    """Unbiased estimates of the count of each value 0, ..., d - 1.

    Precondition: the reports come from olh_report with the same parameters,
    and exp_epsilon > 1. Cost: O(n d) hash evaluations for n reports.
    """
    if Fraction(exp_epsilon) <= 1:
        raise ValueError("the estimate needs epsilon > 0")
    n = len(reports)
    g = family.g
    p = keep_probability(exp_epsilon, g)
    out = []
    for v in range(family.d):
        support = sum(1 for s, y in reports if family.hash(s, v) == y)  # @line L6
        out.append((support - Fraction(n, g)) / (p - Fraction(1, g)))  # @line L7
    return out  # @line L8


def report_pmf(v: int, exp_epsilon: Fraction, family: AllFunctions) -> dict[Report, Fraction]:
    """The exact pmf of olh_report(v) over all pairs (seed, y)."""
    g = family.g
    p = keep_probability(exp_epsilon, g)
    other = (1 - p) / (g - 1)
    weight = Fraction(1, family.seeds)
    out = {}
    for s in range(family.seeds):
        x = family.hash(s, v)
        for y in range(g):
            out[(s, y)] = weight * (p if y == x else other)
    return out


def variance_formula(n: int, n_v: int, exp_epsilon: Fraction, g: int) -> Fraction:
    """The exact variance of the estimate of a value held by n_v of the n clients."""
    p = keep_probability(exp_epsilon, g)
    q = Fraction(1, g)
    return (n_v * p * (1 - p) + (n - n_v) * q * (1 - q)) / (p - q) ** 2


def approximate_variance(n: int, exp_epsilon: Fraction, g: int) -> Fraction:
    """Var* = n q (1 - q) / (p - q)^2 with q = 1/g, the variance when n_v is small against n."""
    p = keep_probability(exp_epsilon, g)
    q = Fraction(1, g)
    return n * q * (1 - q) / (p - q) ** 2
test_optimized_local_hashing.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimized-local-hashing/. The authors are listed in prov/4AE9P1.jsonl.

import math
import random
from fractions import Fraction

import pytest

import dpkit
from optimized_local_hashing import (
    AllFunctions,
    approximate_variance,
    keep_probability,
    olh_estimate,
    olh_report,
    optimal_range,
    report_pmf,
    variance_formula,
)

F = Fraction


def test_check_values():
    assert optimal_range(3) == 4
    assert keep_probability(3, 4) == F(1, 2)
    assert approximate_variance(1, 3, 4) == 3
    # Var*/n = 4 e^epsilon / (e^epsilon - 1)^2 at g = e^epsilon + 1.
    for e in (2, 3, 5, 9):
        assert approximate_variance(1, e, e + 1) == F(4 * e, (e - 1) ** 2)
    # Direct encoding over d = 1024 values at e^epsilon = 3 has Var*/n = (d - 2 + e) / (e - 1)^2.
    assert abs(math.sqrt(10000 * 3) - 173.2) < 0.1
    assert abs(math.sqrt(10000 * (1024 - 2 + 3) / 4) - 1600.8) < 0.1
    fam = AllFunctions(d=3, g=4)
    assert [fam.hash(27, v) for v in range(3)] == [3, 2, 1]


def test_bad_input():
    with pytest.raises(ValueError):
        AllFunctions(d=3, g=1)
    with pytest.raises(ValueError):
        olh_report(3, F(3), AllFunctions(d=3, g=4), random.Random(0))
    with pytest.raises(ValueError):
        olh_estimate([(0, 0)], F(1), AllFunctions(d=3, g=4))


def test_report_is_exactly_epsilon_ldp():
    for e, g, d in ((F(3), 4, 3), (F(2), 3, 3), (F(5, 2), 2, 4)):
        fam = AllFunctions(d=d, g=g)
        pairs = [((a,), (b,)) for a in range(d) for b in range(d) if a != b]
        mech = lambda x: report_pmf(x[0], e, fam)
        assert dpkit.is_pure_dp(mech, pairs, math.log(e))
        assert not dpkit.is_pure_dp(mech, pairs, math.log(e) - 0.01)


def test_family_is_pairwise_uniform():
    fam = AllFunctions(d=3, g=3)
    for a in range(3):
        for b in range(3):
            if a != b:
                pairs = [(fam.hash(s, a), fam.hash(s, b)) for s in range(fam.seeds)]
                assert all(pairs.count((x, y)) == fam.seeds // 9 for x in range(3) for y in range(3))


def exact_moments(data, v, e, fam):
    """Independent oracle: the exact mean and variance of the estimate, from each report's pmf."""
    g = fam.g
    p = keep_probability(e, g)
    mean_c = F(0)
    var_c = F(0)
    for u in data:
        hit = sum(pr for (s, y), pr in report_pmf(u, e, fam).items() if fam.hash(s, v) == y)
        mean_c += hit
        var_c += hit * (1 - hit)
    n = len(data)
    scale = p - F(1, g)
    return (mean_c - F(n, g)) / scale, var_c / scale ** 2


def test_estimate_is_unbiased_with_the_stated_variance():
    rng = random.Random(4)
    fam_cache = {}
    for _ in range(500):
        d = rng.randint(2, 3)
        g = rng.randint(2, 3)
        e = F(rng.randint(5, 40), 4)
        fam = fam_cache.setdefault((d, g), AllFunctions(d=d, g=g))
        n = rng.randint(1, 50)
        data = [rng.randrange(d) for _ in range(n)]
        v = rng.randrange(d)
        mean, var = exact_moments(data, v, e, fam)
        assert mean == data.count(v)
        assert var == variance_formula(n, data.count(v), e, g)


def test_optimal_range_minimizes_approximate_variance():
    rng = random.Random(6)
    cases = [F(2), F(3), F(7), F(15), F(49, 20)]
    cases += [F(rng.randint(41, 2000), 40) for _ in range(500)]
    for e in cases:
        values = {g: approximate_variance(1, e, g) for g in range(2, 60)}
        best = min(values.values())
        assert values[optimal_range(e)] == best
    # Rounding e^epsilon + 1 is not always best: at e^epsilon = 2.45, g = 4 beats g = 3.
    assert optimal_range(F(49, 20)) == 4
    assert approximate_variance(1, F(49, 20), 4) < approximate_variance(1, F(49, 20), 3)


def test_monte_carlo_report_law_and_estimate():
    rng = random.Random(8)
    e = F(3)
    fam = AllFunctions(d=2, g=4)
    n = 2000
    samples = [olh_report(1, e, fam, rng) for _ in range(n)]
    emp = dpkit.empirical_pmf(samples)
    exact = report_pmf(1, e, fam)
    margin = dpkit.hoeffding_margin(n, 1e-6 / len(exact))
    for r, pr in exact.items():
        assert abs(emp.get(r, 0.0) - float(pr)) <= margin
    fam8 = AllFunctions(d=8, g=4)
    data = [0] * 1000 + [3] * 600 + [5] * 400
    reports = [olh_report(v, e, fam8, rng) for v in data]
    est = olh_estimate(reports, e, fam8)
    sd = math.sqrt(approximate_variance(len(data), e, 4))
    truth = [data.count(v) for v in range(8)]
    for got, want in zip(est, truth):
        assert abs(float(got) - want) < 5 * sd

History

Local hashing goes back to Bassily and Smith (STOC 2015), who hashed each value to a single bit before randomizing it, to get short reports for succinct histograms. Wang, Blocki, Li and Jha (USENIX Security 2017) put direct encoding, unary encoding and local hashing into one framework of pure protocols, gave the variance of each, and chose the parameters that minimize it. The choice g=eε+1g = e^{\varepsilon} + 1 gave optimized local hashing. Later work on local frequency estimation often compares against OLH and optimized unary encoding.

References

  1. Tianhao Wang, Jeremiah Blocki, Ninghui Li and Somesh Jha, Locally differentially private protocols for frequency estimation, USENIX Security 2017, pages 729 to 745, Definition 3 (pure LDP protocols and their support sets), Theorem 2 (the variance of a pure protocol), and Section 4.5 (optimized local hashing with g = e^epsilon + 1)
  2. Raef Bassily and Adam Smith, Local, private, efficient protocols for succinct histograms, STOC 2015, the earlier local protocol that hashes the value before randomizing it
  3. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why the samplers of a deployment must be exact

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