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
- Model
- Word RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- 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 , while each client's report is -locally differentially private. Each client picks a random hash function from a family into , and applies generalized randomized response to , not to . It sends (as a seed) and the noisy hash value. Wang, Blocki, Li and Jha (2017) showed that minimizes the variance, which is then for clients. This does not depend on , while plain randomized response over values has a variance that grows with .
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 clients holds a value . The collector wants, for every value , an estimate of , the number of clients that hold . Each client sends one report, and the report must be -LDP: for all values and every report , . 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 . Let be the hash range and . The family must satisfy for all (a universal hashing property).
OLH-REPORT(v, e^epsilon) ▷ run by the client- 1
s <- a uniform seed of the hash family - 2
x <- H_s(v) ▷ a value in {0, ..., g - 1} - 3
if a coin with Pr[1] = p gives 1 then - 4
return (s, x) ▷ send the true hash value - 5
y <- a uniform value of {0, ..., g - 1} other than x; return (s, y) OLH-ESTIMATE(reports, e^epsilon) ▷ run by the collector; n reports- 6
for each value v: C(v) <- the number of reports (s, y) with H_s(v) = y - 7
c(v) <- (C(v) - n/g) / (p - 1/g) - 8
return c
Lines L1 and L2 hash the value with a fresh random function. Lines L3 to L5 are generalized randomized response over the hash values: the true value with probability , and each of the other values with probability . The report is the pair of the seed and the value.
Line L6 counts the reports that "support" : those whose hash function maps to the reported value. A client that holds supports it with probability . A client that holds another value supports with probability exactly , by the collision property. Line L7 removes the expected chance supports and scales the rest, which gives an unbiased estimate.
The choice of trades two effects. A large makes chance supports rare, but then the true hash value is sent with a small probability. The variance is smallest at . The code takes the best integer: or , whichever gives the smaller variance. Plain rounding of is not always best: at , beats .
The code uses the family of all functions from the domain to , where the seed is a number below and is digit of in base . This family has the collision property exactly, so the tests can check every claim with fractions. Its seeds have 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 and . Then and . Four clients report. The seed is a number below , and the table lists , the base-4 digits of from the lowest.
| client | seed (line L1) | (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, | (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 . 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 , which is . The true counts are .
With four clients the estimate is very noisy: by Theorem 2 below, the standard deviation is about . For clients and , the standard deviation is for OLH, against 1600.8 for randomized response over all 1024 values, whose variance per client is .
Correctness
Theorem 1 (privacy). Each report is -LDP, and the bound is tight.
A report has probability if and otherwise. The ratio of the two is , for every .
Theorem 2 (unbiased estimate; Wang, Blocki, Li and Jha, Theorem 2 for pure protocols). If the family has the collision property, then and
Theorem 3 (the best range). The approximate variance is smallest at , with the value .
The key step of Theorem 2 is that a client with another value supports with probability . 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 , let , and let be a finite family of functions from the domain to with the collision property
where is uniform on . The family of all functions has property (1), because the digits of a uniform seed in base are independent and uniform. Write (rational), and . Let be the report of line L1 to line L5 on the value .
Lemma 1 (the pmf of one report). For every seed and every ,
Proof. Line L1 picks uniformly, and line L2 sets . Line L3 compares a uniform integer below the denominator of with its numerator, so it keeps (line L4) with probability exactly. Otherwise line L5 draws uniform on and maps it to or . This map is a bijection onto the values other than , so each of them has probability .
Theorem 1 (privacy). is -LDP. If some seed has , no smaller holds for the pair .
Proof. By Lemma 1, the ratio is one of , and its inverse. Since , we get . So the ratio is at most , and it equals at for a seed with .
Lemma 2 (the support probability). Fix a value , and let for the report . Then if , and if .
Proof. If , then exactly when line L4 runs, which has probability . If , condition on . When , the probability of is . When , it is . By (1),
Theorem 2 (unbiased estimate). Let clients send one independent report each, and let of them hold . If , the estimate of line L7 has and
Proof. Line L6 computes , a sum of independent indicators. By Lemma 2, . Since , . Line L7 is , so its mean is . The variance of is the sum of the variances and of the indicators, and the affine map divides it by .
When is small against , the variance is close to , the quantity that Wang, Blocki, Li and Jha minimize.
Theorem 3 (the best range). As a function of a real , is minimized at , where . Over the integers , with , the minimum is at if and at otherwise.
Proof. Let . Then and . So
The function is strictly convex on , with , which is zero at . So the real minimum is at , and its value is .
Over the integers, convexity puts the minimum at or . With , , which is positive exactly when .
Theorem 1 gives the privacy of each client, Theorem 2 gives the correctness of the collector, and Theorem 3 justifies the choice of 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.
Complexity
The model is the word RAM, with a hash evaluation counted as word operations.
- Client. Lines L1 to L5 take time and three uniform draws. The report has bits. With a family of short seeds this is bits; with the family of all functions it is bits.
- Collector. Line L6 evaluates one hash for each pair of a report and a value, so the estimate of all counts takes time. The extra space is 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 for the true value and a constant for every other value. This makes the estimate of line L7 unbiased.
- The variance does not depend on . At the best , . For it is 3. Randomized response over values has , which is 256.25 for .
- Short reports. Optimized unary encoding, from the same paper, has the same variance, but its report has bits.
- Slow decoding. The collector does 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 again, by sequential composition. OLH has no permanent step like RAPPOR.
Variants and improvements
- Binary local hashing. With , 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 .
- Optimized unary encoding. Encode as a one-hot vector of 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 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 , the point where the two variances cross), and the collector can afford 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 , or with in place of , is biased. Line L7 must subtract , the expected number of chance supports, and divide by .
- A weak hash family. If line L1 uses a family whose collision probability is not , the chance supports of line L6 are not 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 " gives a probability that differs a little from . Compare a uniform integer with the numerator of the exact fraction.
- Ignoring the range choice. Line L2 with a fixed for a large wastes privacy budget: at , gives against at .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Checkers for differential privacy on small finite examples.
A dataset is a tuple of records from a finite universe. A pmf is a dict from
outputs to probabilities; the probabilities may be fractions.Fraction (exact)
or float. A mechanism pmf is a function from a dataset to the pmf of the
output of the mechanism on that dataset.
This module holds the neighbor relations, the privacy loss, the hockey-stick
and Renyi divergences, the pure and approximate DP checks over a list of
neighbor pairs, an empirical pmf, the Hoeffding margin for Monte Carlo
checks, and a grid check of a log density ratio. It holds no mechanism, no
noise sampler and no accountant: those belong to the pages that define them.
Natural logarithms are used throughout, as in the DP literature.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import Callable, Hashable, Iterable, Mapping, Sequence, Union
Number = Union[int, float, Fraction]
Pmf = Mapping[Hashable, Number]
Dataset = tuple
Pair = tuple[Dataset, Dataset]
def neighbors_add_remove(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
"""All datasets at add/remove distance 1 from dataset.
A neighbor removes one record, or appends one record from the universe.
Datasets are treated as multisets: a removal keeps the order of the other
records, and equal results are listed once. Cost: O(n (n + |universe|)).
"""
x = tuple(dataset)
out: list[Dataset] = []
seen: set[Dataset] = set()
for i in range(len(x)):
y = x[:i] + x[i + 1:]
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
for v in universe:
y = x + (v,)
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
return out
def neighbors_replace(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
"""All datasets of the same size that differ from dataset in one record.
The record at index i is replaced by a different value of the universe.
Equal multisets are listed once. Cost: O(n^2 |universe|).
"""
x = tuple(dataset)
values = list(universe)
out: list[Dataset] = []
seen: set[Dataset] = set()
for i in range(len(x)):
for v in values:
if v == x[i]:
continue
y = x[:i] + (v,) + x[i + 1:]
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
return out
def _ratio(a: Number, b: Number) -> Number:
if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
return Fraction(a) / Fraction(b)
return float(a) / float(b)
def privacy_loss(p: Pmf, q: Pmf) -> dict[Hashable, float]:
"""The privacy loss ln(p(y) / q(y)) at each output y with p(y) > 0 or q(y) > 0.
The value is +inf where q(y) = 0 < p(y) and -inf where p(y) = 0 < q(y).
Outputs with p(y) = q(y) = 0 are left out. Cost: O(|support|).
"""
out: dict[Hashable, float] = {}
for y in set(p) | set(q):
a, b = p.get(y, 0), q.get(y, 0)
if a == 0 and b == 0:
continue
if b == 0:
out[y] = math.inf
elif a == 0:
out[y] = -math.inf
else:
out[y] = math.log(_ratio(a, b))
return out
def max_privacy_loss(p: Pmf, q: Pmf) -> float:
"""The largest privacy loss ln(p(y) / q(y)) over the outputs y with p(y) > 0.
Returns -inf when p has no output of positive probability. Cost: O(|support|).
"""
best = -math.inf
for y, v in privacy_loss(p, q).items():
if p.get(y, 0) > 0 and v > best:
best = v
return best
def hockey_stick(p: Pmf, q: Pmf, epsilon: float) -> float:
"""The hockey-stick divergence: the sum over y of max(0, p(y) - e^epsilon q(y)).
It is sup over sets S of P(S) - e^epsilon Q(S). Cost: O(|support|).
"""
a = math.exp(epsilon)
total = 0.0
for y in set(p) | set(q):
d = float(p.get(y, 0)) - a * float(q.get(y, 0))
if d > 0:
total += d
return total
def is_pure_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, tol: float = 1e-12) -> bool:
"""True if max privacy loss <= epsilon + tol for both orders of every pair.
Precondition: mech_pmf returns the exact output pmf of the mechanism.
Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
"""
for x, y in pairs:
p, q = mech_pmf(x), mech_pmf(y)
if max_privacy_loss(p, q) > epsilon + tol or max_privacy_loss(q, p) > epsilon + tol:
return False
return True
def is_approx_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, delta: float, tol: float = 1e-12) -> bool:
"""True if the hockey-stick divergence at e^epsilon is <= delta + tol for both orders of every pair.
Precondition: mech_pmf returns the exact output pmf of the mechanism.
Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
"""
for x, y in pairs:
p, q = mech_pmf(x), mech_pmf(y)
if hockey_stick(p, q, epsilon) > delta + tol or hockey_stick(q, p, epsilon) > delta + tol:
return False
return True
def renyi_divergence(p: Pmf, q: Pmf, alpha: float) -> float:
"""The Renyi divergence of order alpha > 1: ln(sum_y p(y)^alpha q(y)^(1 - alpha)) / (alpha - 1).
Returns +inf when q(y) = 0 < p(y) for some y. Cost: O(|support|).
"""
if alpha <= 1:
raise ValueError("alpha must be greater than 1")
s = 0.0
for y in set(p) | set(q):
a, b = float(p.get(y, 0)), float(q.get(y, 0))
if a == 0:
continue
if b == 0:
return math.inf
s += a * (a / b) ** (alpha - 1)
return math.log(s) / (alpha - 1)
def empirical_pmf(samples: Iterable[Hashable]) -> dict[Hashable, float]:
"""The fraction of the samples equal to each value. Cost: O(number of samples)."""
counts: dict[Hashable, int] = {}
n = 0
for s in samples:
counts[s] = counts.get(s, 0) + 1
n += 1
if n == 0:
return {}
return {k: c / n for k, c in counts.items()}
def hoeffding_margin(n: int, beta: float) -> float:
"""The margin t = sqrt(ln(2 / beta) / (2 n)).
For n independent samples of a [0, 1] variable, the empirical mean is
within t of the true mean with probability at least 1 - beta (Hoeffding).
"""
if n <= 0 or not 0 < beta < 1:
raise ValueError("need n >= 1 and 0 < beta < 1")
return math.sqrt(math.log(2 / beta) / (2 * n))
def log_ratio_grid(logpdf_x: Callable[[float], float], logpdf_y: Callable[[float], float], grid: Iterable[float]) -> float:
"""The largest |logpdf_x(z) - logpdf_y(z)| over the points z of the grid.
Use it to check the log density ratio of a continuous mechanism on two
neighbors. Cost: O(|grid|) calls of each function.
"""
best = 0.0
for z in grid:
d = abs(logpdf_x(z) - logpdf_y(z))
if d > best:
best = d
return best
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 gave optimized local hashing. Later work on local frequency estimation often compares against OLH and optimized unary encoding.
References
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4AE9P1 Edit this page History Report an error Markdown