Algorithmadvanced
RAPPOR
Also called randomized aggregatable privacy-preserving ordinal response.
Encodes each value into a Bloom filter and applies two stages of randomized response, so a server can estimate value frequencies over time.
- Time
- O(N k + k m M^2 + M^3) worst
- Space
- O(k m M) extra
- Where
- M = the candidate values; N = the number of reports; h = the hash functions; k = the bits of the Bloom filter; m = the cohorts
- Model
- Word RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- ��lfar Erlingsson, Vasyl Pihur, Aleksandra Korolova, 2014
RAPPOR is a local differential privacy method to collect strings, such as a browser setting, from many clients. Each client hashes its value into a Bloom filter of bits. It then applies randomized response to each bit two times. The first time, the result is stored and reused for this value forever (the permanent step). The second time, fresh noise is added for each report (the instantaneous step). The permanent step limits what any number of reports of one value can leak to . The instantaneous step makes a single report leak much less, and makes two reports hard to link. The collector counts the ones per bit, removes the known bias, and fits the counts of a list of candidate strings by least squares. Erlingsson, Pihur and Korolova (2014) designed it for the Chrome web browser.
In plain words
Each client turns its answer into a short row of bits. A few bits are on, chosen by hashing the answer. The client then lies about some of the bits, at random. It writes this lie down and keeps it. Each time the server asks, the client lies again about the written row, with new coins, and sends that.
Because the written row never changes for one answer, the server cannot remove the noise by asking many times. Because each report adds new noise, one report shows very little.
The server knows how often the coins lie. It adds up the reports from many clients, removes the expected share of lies, and finds which answers best explain the counts. This works for answers that many clients share. Rare answers stay hidden in the noise.
The problem
There are clients. Client holds a value from a large set of strings that the collector does not know in advance. The collector wants the number of clients that hold each popular value. The data of each client must stay private from the collector, under the local model: the randomizer of one client, as a function of that client's value, must be -LDP. The neighbor relation is replace: two inputs of one client are two different values.
A client may report many times, for example once a day, about the same value. The privacy claim must hold for all these reports together, not only for one.
The algorithm
The parameters are the filter size , the number of hash functions, the number of cohorts, and three rational probabilities: for the permanent step and for the instantaneous step. Each client is in one fixed cohort , and each cohort has its own hash functions into .
REPORT(client, v) ▷ run by the client; memo is kept on the device- 1
if memo has no entry for v then - 2
B <- the k-bit Bloom filter of v: bit H_{j,t}(v) is 1 for t = 1, ..., h - 3
for each bit i: B'_i <- 1 w.p. f/2, 0 w.p. f/2, else B_i - 4
memo[v] <- B' - 5
B' <- memo[v] - 6
for each bit i: S_i <- 1 w.p. q if B'_i = 1, w.p. p if B'_i = 0 - 7
return S ESTIMATE(reports, candidates) ▷ run by the collector- 8
c_{ji} <- the number of reports of cohort j with bit i set; N_j <- the reports of cohort j - 9
t_{ji} <- (c_{ji} - p* N_j) / ((1 - f)(q - p)) - 10
X <- the km x M matrix: column v has a 1 at row (j, i) when bit i of v's filter in cohort j is 1 - 11
a <- the least squares solution of X a = t - 12
return m a ▷ the cohorts are balanced
Lines L1 to L4 run only the first time a client sees the value . Line L2 computes the Bloom filter , which has at most ones. Line L3 is the permanent randomized response: each bit is forced to 1 or to 0 with probability each, and is kept otherwise. Line L4 stores the result on the device. Lines L5 and L6 run for every report: they read and send a fresh noisy copy , where a 1 of becomes a 1 with probability and a 0 becomes a 1 with probability .
On the collector side, a reported bit is 1 with probability when the true bit is 1, and when it is 0. Line L9 inverts this, so that estimates the number of clients of cohort whose filter has bit on. Line L10 builds the matrix of the candidate filters, and line L11 finds the candidate counts that best explain . The paper first selects the candidates with the Lasso and then fits them by least squares, and it keeps only the candidates that pass a significance test. The code on this page has only the least squares step on a given list.
The coins of lines L3 and L6 use exact rational probabilities and one uniform integer per bit. The tests use a seeded generator so that each run repeats. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012).
Example
Take , , one cohort, , and . The code hashes the value "apple" to the bits 2 and 3, so . Line L3 draws from for each bit: forces a 1, forces a 0, and keeps the bit. Line L6 draws from and sends 1 below 3 when , and draws from and sends 1 below 1 when .
| bit | (line L2) | draw of line L3 | draw of line L6 | ||
|---|---|---|---|---|---|
| 0 | 0 | 2 | 0 | 1 | 0 |
| 1 | 0 | 0 | 1 | 2 | 1 |
| 2 | 1 | 3 | 1 | 0 | 1 |
| 3 | 1 | 1 | 0 | 0 | 1 |
| 4 | 0 | 2 | 0 | 1 | 0 |
| 5 | 0 | 3 | 0 | 0 | 1 |
| 6 | 0 | 1 | 0 | 1 | 0 |
| 7 | 0 | 2 | 0 | 1 | 0 |
The client stores and sends . The next report of "apple" skips lines L2 to L4 and draws only line L6 again.
These parameters give and . The bound for all reports of one value is , and the bound for one report is . With they grow to and .
On the collector side, suppose that clients report and that 300 of them have bit 2 on. Then , and line L9 gives , which is 300 when . The standard deviation of is 15.39, so the standard deviation of is 123.1. A count of 300 among 1000 is only about 2.4 standard deviations from 0. RAPPOR needs many clients.
Correctness
Theorem (longitudinal privacy; Erlingsson, Pihur and Korolova, Theorem 1). All the reports that a client sends about one value are together -LDP, with , for any number of reports.
Two Bloom filters differ in at most bits, and the ratio of the probabilities of at each such bit is at most . Every report is a function of and of fresh coins, so the post-processing theorem carries the bound to all reports.
Theorem (one report; their Theorem 2). A single report is -LDP with .
Theorem (unbiased counts). For one report per client, is the true number of clients of cohort whose filter has bit on. If every client holds a candidate, the cohorts are balanced and has independent columns, line L12 is an unbiased estimate of the true counts.
Both privacy bounds are tight for two values whose filters have ones each and no common one. The full proofs are in the correctness proof of this page. The tests check both bounds with exact fractions on all filters of 4 bits, and the two-report law against .
Proof: RAPPOR meets its two privacy bounds and its decoded counts are unbiasedfull
Fix the parameters: bits, hash functions, cohorts, and , all rational. For a value and a cohort, let be the Bloom filter of line L2. It has at most ones, because each of the hash functions sets one bit. Write
Lemma 1 (the coins). Line L3 sets each bit to 1 with probability , to 0 with probability , and to with probability , independently over . Line L6 sets with probability if and if , independently over and given .
Proof. Let in lowest terms. Line L3 draws uniform on . The events and have probability each, and the rest has probability . Line L6 draws one uniform integer below the denominator of or and compares it with the numerator, which gives probability or exactly. Each bit uses its own draw.
Lemma 2 (one report). If no memo exists for , the bits of the report are independent, and if and if .
Proof. By Lemma 1, if then , so . If then , so . The pairs are independent over .
Note that .
Theorem 1 (longitudinal bound). Let . For two values of the same cohort and every output , . So the sequence of all reports that a client sends for one value is -LDP, for any number of reports. The bound is attained when and have ones each and no common one.
Proof. By Lemma 1, with and . Let be the set of positions where and differ. The factors outside cancel. Inside , each factor of the ratio is or its inverse, and because . So the ratio is at most . Each filter has at most ones, so , which gives . Equality holds for when .
Lines L1 and L4 store the first time the value is seen, and line L5 reads it back each later time. So every report of is $S = $ L6 applied to the same , with fresh coins that do not depend on . The sequence of reports is a randomized function of alone, and the post-processing theorem gives the same bound for it.
Theorem 2 (bound for one report). Let . One report of a value with no memo is -LDP among the values of one cohort, and the bound is attained for two disjoint filters with ones each.
Proof. By Lemma 2, the ratio is the product over of a factor that depends on . Let be the positions with and , and the others in . On , the factor is if and if . The first is above 1 and the second below 1, because . On the factors are and , and the second is the one above 1. So
since (the ones of ) and (the ones of ), and both bases are at least 1. Equality holds when and .
Theorem 3 (unbiased bit counts). Let cohort have clients that each send one report, and let be the number of them whose filter has bit set. Then the value of line L9 has and
Proof. Line L8 counts , a sum of independent indicators: of them have mean and the others have mean , by Lemma 2. So . Line L9 computes , and , so . The variance of a sum of independent indicators is the sum of their variances, and the affine map divides it by .
Theorem 4 (the fit). Let be the matrix of line L10 and suppose its columns are independent. Suppose that every client holds one of the candidate values and that cohort has clients with value . If each candidate has the same count in every cohort, then line L11 returns an unbiased estimate of , and line L12 returns an unbiased estimate of the totals .
Proof. Since has independent columns, is invertible, and line L11 returns , the unique solution of the normal equations. By the definition of , , so as vectors. By Theorem 3 and linearity, . Line L12 multiplies by .
Theorems 1 and 2 give the privacy of the client for many reports and for one report. Theorems 3 and 4 give the correctness of the collector when the candidate list is complete and the cohorts are balanced. If some clients hold a value outside the list, Theorem 4 does not apply, and the fit can be biased.
Complexity
The model is the word RAM. A hash is counted as word operations.
- One report. Line L2 costs , line L3 costs and draws, and line L6 costs and draws. So a report costs time and at most draws. The memo holds bits for each value that the client has reported.
- Counting. Line L8 reads reports of bits in time. Line L9 is .
- Fit. Line L10 builds a matrix with work. The normal equations cost to form and to solve. So the collector runs in time and extra space.
Properties
- Two levels of privacy. The permanent bits protect against an observer who collects every report for a long time. The instantaneous bits protect a single report much more: against in the example.
- Per value, not per client. The bound holds for one value. A client whose value changes gets a new for each new value, and the losses add up by sequential composition. Values that change in a correlated way can leak more than one value's worth.
- Unbiased, with a large variance. The variance of is about . Only values held by a large share of the clients can be found.
- Unknown domain. The collector needs only a list of candidate strings at decoding time, not before collection. Strings that are not on the list are not found, and they bias the fit.
- Cohorts. Different hash functions per cohort reduce the chance that two candidates collide in every cohort, so that has independent columns.
Variants and improvements
- One-time RAPPOR. If each client reports only once, the instantaneous step can be left out, and the report is itself, with the loss (Erlingsson, Pihur and Korolova).
- Basic RAPPOR. For a small known domain, and one bit per value (a one-hot code) remove the hash collisions. Wang, Blocki, Li and Jha (2017) analyze this case as a frequency oracle.
- Optimized local hashing. For one report per client, optimized local hashing has a smaller variance than basic RAPPOR in most settings, and its report is bits, not .
- Shuffling. Mixing the reports of many clients before the collector reads them gives central DP with a smaller (privacy amplification by shuffling).
- Unknown strings. Fanti, Pihur and Erlingsson (2016) extended RAPPOR to learn the strings themselves, without a candidate list, by reporting several parts of each string and learning which parts occur together.
When to use it
Use RAPPOR when the collector is not trusted, the clients are many (at least tens of thousands), and each client reports the same slowly changing value many times. The permanent step is the reason to choose it over a plain local frequency oracle. For one report per client over a known domain, optimized local hashing gives a smaller error. If a trusted curator is available, the geometric mechanism on each count gives an error that is smaller by a factor of about .
Pitfalls
- No memo. Lines L1 to L5 replaced by a fresh line L3 for each report give a new each time. The collector can average the reports and recover , and the loss grows with the number of reports. Line L3 must run once per value, and line L4 must store the result on the device.
- A new cohort for each report. If line L2 uses a new random cohort for each report, the filter changes, and so does . Each report then spends again. The cohort of a client must stay fixed.
- The wrong correction. Line L9 with in place of , or a division by in place of , gives biased counts. Line L9 must use the two-stage values.
- Float coins. Lines L3 and L6 written as "random float below " give probabilities that differ a little from the analysis. The coins must compare a uniform integer with the numerator of an exact fraction.
- A short candidate list. Line L11 on a list that misses a popular value spreads its counts over the other candidates. The paper first selects candidates with the Lasso and tests the fitted counts for significance; skip that step only when the list is known to be complete.
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
rappor.py 237 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rappor/. The authors are listed in prov/WNQFZC.jsonl.
"""RAPPOR (Erlingsson, Pihur and Korolova, CCS 2014).
A client hashes its value into a Bloom filter of k bits with h hash functions,
applies a permanent randomized response to each bit (memoized per value), and
then sends a fresh instantaneous randomized response of the memoized bits in
each report. The collector counts the ones per bit and cohort, removes the
bias of the two randomizations, and fits the counts of a list of candidate
values by least squares.
The probabilities f, p and q are Fractions so that the coins are exact and the
report pmf can be checked with fractions. random.Random is used only so that
the tests are reproducible; a deployment needs a cryptographic source of
randomness. The hash is SHA-256 of the cohort, the hash index and the value.
"""
from __future__ import annotations
import hashlib
import itertools
import math
import random
from dataclasses import dataclass, field
from fractions import Fraction
from typing import Hashable, Sequence
Bits = tuple[int, ...]
@dataclass(frozen=True)
class RapporParams:
"""k bits, h hash functions, m cohorts, permanent f and instantaneous p < q."""
k: int
h: int
f: Fraction
p: Fraction
q: Fraction
m: int = 1
def __post_init__(self) -> None:
if self.k < 1 or self.h < 1 or self.m < 1:
raise ValueError("need k, h and m at least 1")
if not (0 <= self.f < 1 and 0 <= self.p < self.q <= 1):
raise ValueError("need 0 <= f < 1 and 0 <= p < q <= 1")
def _coin(prob: Fraction, rng: random.Random) -> int:
"""1 with probability prob, exactly, from one uniform integer draw."""
return 1 if rng.randrange(prob.denominator) < prob.numerator else 0
def bloom_positions(value: Hashable, cohort: int, params: RapporParams) -> list[int]:
"""The h positions H_1(value), ..., H_h(value) of the cohort's hash functions."""
out = []
for j in range(params.h):
digest = hashlib.sha256(f"{cohort}|{j}|{value!r}".encode()).digest()
out.append(int.from_bytes(digest[:8], "big") % params.k)
return out
def bloom_filter(value: Hashable, cohort: int, params: RapporParams) -> Bits:
"""The k-bit Bloom filter B of the value: bit i is 1 when some H_j(value) = i."""
b = [0] * params.k
for i in bloom_positions(value, cohort, params):
b[i] = 1
return tuple(b)
def permanent_rr(b: Bits, f: Fraction, rng: random.Random) -> Bits:
"""Each bit becomes 1 with probability f/2, 0 with probability f/2, else stays."""
out = []
for bit in b:
u = rng.randrange(2 * f.denominator)
if u < f.numerator:
out.append(1)
elif u < 2 * f.numerator:
out.append(0)
else:
out.append(bit)
return tuple(out)
def instantaneous_rr(bp: Bits, p: Fraction, q: Fraction, rng: random.Random) -> Bits:
"""Each bit of the report is 1 with probability q if the memoized bit is 1, else p."""
return tuple(_coin(q if bit else p, rng) for bit in bp)
@dataclass
class RapporClient:
"""One client: its cohort and the memo of permanent bits for each value it has seen."""
cohort: int
params: RapporParams
memo: dict[Hashable, Bits] = field(default_factory=dict)
def report(self, value: Hashable, rng: random.Random) -> Bits:
"""One RAPPOR report of value.
Precondition: 0 <= cohort < m. All reports of the same value reuse the
same permanent bits, so together they leak at most epsilon_infinity.
Cost: O(h + k) word operations and at most 2k uniform draws per report.
"""
if not 0 <= self.cohort < self.params.m:
raise ValueError("cohort out of range")
if value not in self.memo: # @line L1
b = bloom_filter(value, self.cohort, self.params) # @line L2
bp = permanent_rr(b, self.params.f, rng) # @line L3
self.memo[value] = bp # @line L4
bp = self.memo[value] # @line L5
s = instantaneous_rr(bp, self.params.p, self.params.q, rng) # @line L6
return s # @line L7
def one_probabilities(params: RapporParams) -> tuple[Fraction, Fraction]:
"""(q*, p*): the chance that a reported bit is 1 when the true bit is 1, and when it is 0."""
f, p, q = params.f, params.p, params.q
q_star = f * (p + q) / 2 + (1 - f) * q
p_star = f * (p + q) / 2 + (1 - f) * p
return q_star, p_star
def epsilon_permanent(params: RapporParams) -> float:
"""epsilon_infinity = 2 h ln((1 - f/2) / (f/2)), the bound for all reports of one value."""
if params.f == 0:
return math.inf
half = params.f / 2
return 2 * params.h * math.log((1 - half) / half)
def epsilon_one_report(params: RapporParams) -> float:
"""epsilon_1 = h ln(q* (1 - p*) / (p* (1 - q*))), the bound for a single report."""
q_star, p_star = one_probabilities(params)
if p_star == 0 or q_star == 1:
return math.inf
return params.h * math.log(q_star * (1 - p_star) / (p_star * (1 - q_star)))
def bit_counts(reports: Sequence[tuple[int, Bits]], params: RapporParams) -> tuple[list[list[int]], list[int]]:
"""c[j][i], the number of reports of cohort j with bit i set, and N[j], the reports of cohort j."""
c = [[0] * params.k for _ in range(params.m)]
totals = [0] * params.m
for cohort, s in reports:
totals[cohort] += 1
for i, bit in enumerate(s):
c[cohort][i] += bit
return c, totals
def debiased_counts(c: list[list[int]], totals: list[int], params: RapporParams) -> list[list[Fraction]]:
"""t[j][i] = (c[j][i] - p* N[j]) / ((1 - f)(q - p)), an unbiased estimate of the true bit counts."""
_, p_star = one_probabilities(params)
scale = (1 - params.f) * (params.q - params.p)
return [[(c[j][i] - p_star * totals[j]) / scale for i in range(params.k)] for j in range(params.m)]
def design_matrix(candidates: Sequence[Hashable], params: RapporParams) -> list[list[int]]:
"""The km x M matrix X: column v has a 1 in row (j, i) when bit i of v's filter in cohort j is 1."""
rows = [[0] * len(candidates) for _ in range(params.k * params.m)]
for col, v in enumerate(candidates):
for j in range(params.m):
for i, bit in enumerate(bloom_filter(v, j, params)):
if bit:
rows[j * params.k + i][col] = 1
return rows
def _solve(a: list[list[Fraction]], b: list[Fraction]) -> list[Fraction]:
"""Solve a x = b by Gauss-Jordan elimination with exact fractions."""
n = len(a)
mat = [row[:] + [b[i]] for i, row in enumerate(a)]
for col in range(n):
piv = next((r for r in range(col, n) if mat[r][col] != 0), None)
if piv is None:
raise ValueError("the candidates are not separable: X has dependent columns")
mat[col], mat[piv] = mat[piv], mat[col]
for r in range(n):
if r != col and mat[r][col] != 0:
ratio = mat[r][col] / mat[col][col]
mat[r] = [x - ratio * y for x, y in zip(mat[r], mat[col])]
return [mat[i][n] / mat[i][i] for i in range(n)]
def fit_candidates(t: list[list[Fraction]], candidates: Sequence[Hashable], params: RapporParams) -> list[Fraction]:
"""The least squares solution of X a = t, with t flattened cohort by cohort.
Precondition: X has independent columns. Cost: O(k m M^2 + M^3) exact operations.
"""
x = design_matrix(candidates, params) # @line L10
y = [t[j][i] for j in range(params.m) for i in range(params.k)]
cols = len(candidates)
xtx = [[Fraction(sum(row[a] * row[b] for row in x)) for b in range(cols)] for a in range(cols)]
xty = [sum((row[a] * yv for row, yv in zip(x, y)), Fraction(0)) for a in range(cols)]
return _solve(xtx, xty) # @line L11
def rappor_estimate(reports: Sequence[tuple[int, Bits]], candidates: Sequence[Hashable], params: RapporParams) -> list[Fraction]:
"""Least squares estimates of how many clients hold each candidate value.
reports is a list of (cohort, report) pairs, one report per client.
Precondition: the clients are spread evenly over the m cohorts, and the
design matrix has independent columns. The fit gives the count of each
candidate in one cohort, so the result is m times the fit. This is the
least squares stage of the paper; its Lasso stage that picks the
candidates first is left out. Cost: O(N k) for the counts and
O(k m M^2 + M^3) exact arithmetic operations for the fit.
"""
c, totals = bit_counts(reports, params) # @line L8
t = debiased_counts(c, totals, params) # @line L9
per_cohort = fit_candidates(t, candidates, params)
return [params.m * a for a in per_cohort] # @line L12
def permanent_pmf(b: Bits, f: Fraction) -> dict[Bits, Fraction]:
"""The exact pmf of the permanent bits B' given the Bloom filter b."""
keep_one = 1 - f / 2
out = {}
for bp in itertools.product((0, 1), repeat=len(b)):
pr = Fraction(1)
for bit, new in zip(b, bp):
pr *= keep_one if bit == new else f / 2
out[bp] = pr
return out
def first_report_pmf(b: Bits, params: RapporParams) -> dict[Bits, Fraction]:
"""The exact pmf of one report of a value with Bloom filter b, before any memo exists."""
q_star, p_star = one_probabilities(params)
out = {}
for s in itertools.product((0, 1), repeat=len(b)):
pr = Fraction(1)
for bit, rep in zip(b, s):
one = q_star if bit else p_star
pr *= one if rep else 1 - one
out[s] = pr
return out
test_rappor.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rappor/. The authors are listed in prov/WNQFZC.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
import dpkit
from rappor import (
RapporClient,
RapporParams,
bit_counts,
bloom_filter,
bloom_positions,
debiased_counts,
epsilon_one_report,
epsilon_permanent,
first_report_pmf,
fit_candidates,
one_probabilities,
permanent_pmf,
rappor_estimate,
)
F = Fraction
BASE = RapporParams(k=4, h=2, f=F(1, 2), p=F(1, 2), q=F(3, 4))
def filters_with_at_most(k, h):
"""All k-bit vectors with between 1 and h ones: the possible Bloom filters."""
return [b for b in itertools.product((0, 1), repeat=k) if 1 <= sum(b) <= h]
def instantaneous_pmf(bp, params):
"""Exact pmf of S given the memoized bits B'."""
out = {}
for s in itertools.product((0, 1), repeat=len(bp)):
pr = F(1)
for bit, rep in zip(bp, s):
one = params.q if bit else params.p
pr *= one if rep else 1 - one
out[s] = pr
return out
def two_report_pmf(b, params):
"""Exact pmf of two reports of the same value: both reuse one draw of B'."""
out = {}
for bp, pb in permanent_pmf(b, params.f).items():
inst = instantaneous_pmf(bp, params)
for s1, p1 in inst.items():
for s2, p2 in inst.items():
out[(s1, s2)] = out.get((s1, s2), 0) + pb * p1 * p2
return out
def test_check_values():
params = RapporParams(k=8, h=2, f=F(1, 2), p=F(1, 2), q=F(3, 4))
assert one_probabilities(params) == (F(11, 16), F(9, 16))
assert abs(epsilon_permanent(params) - math.log(81)) < 1e-12
assert abs(epsilon_one_report(params) - 1.0743) < 1e-4
four = RapporParams(k=8, h=4, f=F(1, 2), p=F(1, 2), q=F(3, 4))
assert abs(epsilon_permanent(four) - 8.7889) < 1e-4
assert abs(epsilon_one_report(four) - 2.1486) < 1e-4
assert bloom_positions("apple", 0, params) == [2, 3]
assert bloom_filter("fig", 0, params) == (0, 1, 0, 0, 1, 0, 0, 0)
def test_bad_parameters():
with pytest.raises(ValueError):
RapporParams(k=4, h=2, f=F(1), p=F(1, 2), q=F(3, 4))
with pytest.raises(ValueError):
RapporParams(k=4, h=2, f=F(1, 2), p=F(3, 4), q=F(1, 2))
with pytest.raises(ValueError):
RapporClient(cohort=1, params=BASE).report("a", random.Random(0))
def test_permanent_bits_meet_epsilon_infinity_and_are_tight():
pairs = [(b1, b2) for b1 in filters_with_at_most(4, 2) for b2 in filters_with_at_most(4, 2)]
eps = epsilon_permanent(BASE)
assert dpkit.is_pure_dp(lambda b: permanent_pmf(b, BASE.f), pairs, eps)
disjoint = [((1, 1, 0, 0), (0, 0, 1, 1))]
assert not dpkit.is_pure_dp(lambda b: permanent_pmf(b, BASE.f), disjoint, eps - 0.01)
def test_one_report_meets_epsilon_one_and_is_tight():
pairs = [(b1, b2) for b1 in filters_with_at_most(4, 2) for b2 in filters_with_at_most(4, 2)]
eps = epsilon_one_report(BASE)
assert dpkit.is_pure_dp(lambda b: first_report_pmf(b, BASE), pairs, eps)
disjoint = [((1, 1, 0, 0), (0, 0, 1, 1))]
assert not dpkit.is_pure_dp(lambda b: first_report_pmf(b, BASE), disjoint, eps - 0.01)
def test_two_reports_of_one_value_stay_within_epsilon_infinity():
params = RapporParams(k=3, h=1, f=F(1, 2), p=F(1, 4), q=F(3, 4))
pairs = [((1, 0, 0), (0, 1, 0)), ((0, 0, 1), (1, 0, 0))]
assert dpkit.is_pure_dp(lambda b: two_report_pmf(b, params), pairs, epsilon_permanent(params))
# Two fresh draws of B' would spend more than one epsilon_1 each: the memo matters.
p = two_report_pmf((1, 0, 0), params)
q = two_report_pmf((0, 1, 0), params)
assert dpkit.max_privacy_loss(p, q) > epsilon_one_report(params)
def test_random_parameters_against_closed_form_loss():
rng = random.Random(11)
for _ in range(500):
k = rng.randint(2, 4)
h = rng.randint(1, 2)
den = rng.randint(3, 9)
f = F(rng.randint(1, den - 1), den)
pn = rng.randint(0, den - 2)
p = F(pn, den)
q = F(rng.randint(pn + 1, den), den)
params = RapporParams(k=k, h=h, f=f, p=p, q=q)
b1 = tuple(rng.randint(0, 1) for _ in range(k))
b2 = tuple(rng.randint(0, 1) for _ in range(k))
q_star, p_star = one_probabilities(params)
# Independent oracle: the loss is the sum of the per-bit log ratios at the worst output.
a = sum(1 for x, y in zip(b1, b2) if x == 1 and y == 0)
c = sum(1 for x, y in zip(b1, b2) if x == 0 and y == 1)
expect = a * math.log(q_star / p_star) + c * math.log((1 - p_star) / (1 - q_star))
got = dpkit.max_privacy_loss(first_report_pmf(b1, params), first_report_pmf(b2, params))
assert abs(got - expect) < 1e-9
keep = math.log((1 - f / 2) / (f / 2))
got_perm = dpkit.max_privacy_loss(permanent_pmf(b1, f), permanent_pmf(b2, f))
assert abs(got_perm - (a + c) * keep) < 1e-9
if a <= h and c <= h:
assert got <= epsilon_one_report(params) + 1e-9
assert got_perm <= epsilon_permanent(params) + 1e-9
def test_memo_is_reused_and_reports_have_the_right_law():
rng = random.Random(5)
client = RapporClient(cohort=0, params=BASE)
client.report("a", rng)
first = dict(client.memo)
for _ in range(20):
client.report("a", rng)
assert client.memo == first
client.report("b", rng)
assert set(client.memo) == {"a", "b"}
# Fresh clients: the first report has the law of first_report_pmf.
n = 2000
samples = [RapporClient(cohort=0, params=BASE).report("a", rng) for _ in range(n)]
emp = dpkit.empirical_pmf(samples)
exact = first_report_pmf(bloom_filter("a", 0, BASE), BASE)
margin = dpkit.hoeffding_margin(n, 1e-6 / 16)
for s, pr in exact.items():
assert abs(emp.get(s, 0.0) - float(pr)) <= margin
def test_debiased_counts_are_exactly_unbiased():
rng = random.Random(7)
for _ in range(500):
den = rng.randint(3, 8)
f = F(rng.randint(0, den - 1), den)
pn = rng.randint(0, den - 2)
p = F(pn, den)
q = F(rng.randint(pn + 1, den), den)
params = RapporParams(k=3, h=1, f=f, p=p, q=q)
n = rng.randint(1, 50)
n_set = rng.randint(0, n)
q_star, p_star = one_probabilities(params)
expected_c = [[n_set * q_star + (n - n_set) * p_star, 0, 0]]
t = debiased_counts(expected_c, [n], params)
assert t[0][0] == n_set
def test_least_squares_recovers_counts_from_expected_bits():
params = RapporParams(k=8, h=2, f=F(1, 2), p=F(1, 2), q=F(3, 4), m=2)
candidates = ["apple", "fig", "kiwi"]
truth = {"apple": 30, "fig": 12, "kiwi": 5}
q_star, p_star = one_probabilities(params)
# Half of the holders of each value are in each cohort; c is the exact expected count.
half = F(sum(truth.values()), 2)
c = []
for j in range(params.m):
row = []
for i in range(params.k):
n_set = sum(F(n, 2) for v, n in truth.items() if bloom_filter(v, j, params)[i])
row.append(n_set * q_star + (half - n_set) * p_star)
c.append(row)
deb = debiased_counts(c, [half] * params.m, params)
assert fit_candidates(deb, candidates, params) == [F(truth[v], 2) for v in candidates]
def test_end_to_end_estimate_is_close():
rng = random.Random(9)
params = RapporParams(k=8, h=2, f=F(1, 4), p=F(1, 4), q=F(3, 4), m=2)
values = ["apple"] * 900 + ["fig"] * 600 + ["kiwi"] * 300
reports = []
for idx, v in enumerate(values):
cohort = idx % params.m
reports.append((cohort, RapporClient(cohort=cohort, params=params).report(v, rng)))
c, totals = bit_counts(reports, params)
assert totals == [900, 900]
est = rappor_estimate(reports, ["apple", "fig", "kiwi"], params)
for got, want in zip(est, [900, 600, 300]):
assert abs(float(got) - want) < 250
History
Erlingsson, Pihur and Korolova presented RAPPOR at ACM CCS 2014. Google used it in the Chrome web browser to collect statistics on settings such as the home page, and published an open source version. It was one of the first large deployments of local differential privacy. Fanti, Pihur and Erlingsson (2016) extended it to strings that are not known in advance. Wang, Blocki, Li and Jha (2017) placed its basic form in a common framework of frequency oracles and showed that optimized local hashing has a smaller variance for one report.
References
- Úlfar Erlingsson, Vasyl Pihur and Aleksandra Korolova, RAPPOR: randomized aggregatable privacy-preserving ordinal response, ACM CCS 2014, pages 1054 to 1067, the algorithm (Bloom filter, permanent and instantaneous randomized response), Theorem 1 (the bound epsilon_infinity), Theorem 2 (the bound for one report), and Section 4 (decoding with cohorts, Lasso and least squares)
- Tianhao Wang, Jeremiah Blocki, Ninghui Li and Somesh Jha, Locally differentially private protocols for frequency estimation, USENIX Security 2017, pages 729 to 745, the comparison of basic RAPPOR with the other frequency oracles in the pure LDP framework
- 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 WNQFZC Edit this page History Report an error Markdown