Algorithmadvanced
Binary tree mechanism
Also called tree aggregation for continual counting, continual observation counter.
Releases a running count of a bit stream at every step. It adds noise to the dyadic partial sums and adds at most log T of them, so the error grows only as a polylog of T.
- Time
- O(T log T) worst
- Space
- O(log T) extra
- Where
- T = the length of the stream
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- T. H. Hubert Chan, Elaine Shi, Dawn Song, Cynthia Dwork, Moni Naor, Toniann Pitassi, Guy N. Rothblum, 2010
The binary tree mechanism releases, at each time of a stream of bits, a private count of the ones seen so far. To add fresh Laplace noise to each count would cost privacy at every step. To add noise to each bit and sum gives error of order . The tree mechanism keeps noisy sums over dyadic blocks of time, the same blocks as a Fenwick tree. Each count is a sum of at most of them, and each bit is in at most of them. So the error is polylogarithmic in and the whole output stream is -differentially private. It is the base of continual release, and of the private optimizers that add noise to running sums of gradients.
In plain words
A counter at a door must post the number of visitors each minute, but no single visit may show. If it posts the true count plus new noise each minute, an observer can average the posts and remove the noise. If it adds noise to each visit and posts the sum, the noise piles up.
The tree mechanism groups the minutes into blocks: blocks of 1 minute, of 2, of 4, of 8, and so on. It adds noise one time to the total of each block when the block ends. To post the count at a minute, it adds the few block totals that cover the time so far. A visit is in only a few blocks, and each count uses only a few blocks. So the noise stays small and the privacy cost is small.
The problem
The input is a stream with and a known length . At each time the mechanism must output an estimate of the count , using only . Two streams are neighbors if they have the same length and differ at one time step (event-level privacy, replace one item). The goal is that the whole output sequence is -DP, with a small error .
is the Laplace distribution with density . It has variance , and .
The algorithm
Let be the number of bits of . The node closed at time is the interval , where is the lowest one bit of . The mechanism keeps one exact partial sum and one noisy partial sum for each level .
BINARY-TREE-COUNTER(σ(1..T), ε)- 1
L ← ⌊log₂ T⌋ + 1 ▷ the number of levels - 2
for t ← 1 to T do - 3
i ← the index of the lowest 1 bit of t - 4
aᵢ ← σ(t) + Σ_{j<i} aⱼ ▷ the node (t − 2ⁱ, t] closes now - 5
for j ← 0 to i − 1 do aⱼ ← 0, âⱼ ← 0 - 6
âᵢ ← aᵢ + Lap(L/ε) ▷ noise one time for each node - 7
output sₜ ← Σ_{j : bit j of t is 1} âⱼ
Line L3 finds the level of the node that closes at time . Line L4 merges the smaller nodes below it, which together cover , and adds the new item. Line L5 clears the merged levels. Line L6 adds the noise, one time for each node. Line L7 writes in binary and adds one noisy node for each one bit. For these are the nodes and .
Example
Take , and the stream . Then and each node gets noise. The run of the code with random.Random(1) gives the values below, rounded to two places.
| node | exact node | noisy node | nodes used in L7 | |||||
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 0 | 1 | 1 | ||||
| 2 | 0 | 1 | 1 | 5.75 | 5.75 | 1 | ||
| 3 | 1 | 0 | 1 | 4.00 | 9.75 | 2 | ||
| 4 | 1 | 2 | 3 | 0.31 | 0.31 | 3 | ||
| 5 | 0 | 0 | 0 | 0.27 | 3 | |||
| 6 | 1 | 1 | 1 | 0.57 | 0.88 | 4 | ||
| 7 | 1 | 0 | 1 | 2.45 | 3.33 | 5 | ||
| 8 | 1 | 3 | 6 | 9.45 | 9.45 | 6 |
The time step 1 is in the four nodes , , and , which is why the scale is . The release at uses three nodes, so its variance is . The other releases use one or two nodes, with variance 32 or 64. At this small the noise is larger than the counts. The method pays off for long streams: for the variance is at most , a standard error of about 136, while Laplace noise on each bit gives a variance of , about at .
Correctness
Exact sums (a theorem). With the noise set to 0, the output at time is . The invariant: after step , for each one bit of , is the exact sum over the node of level in the binary form of , and for each zero bit. Line L4 keeps it because the nodes of the low bits of partition .
Privacy (a theorem). Each time step lies in at most one node of each level, so in at most nodes. A change at one time step changes the vector of node values by at most in norm. So the vector of noisy nodes, with on each, is -DP by the Laplace mechanism. The outputs are sums of noisy nodes, so they are -DP by post-processing.
Error (a theorem). The error at time is a sum of independent draws. It has mean 0 and variance . By the union bound, all errors are at most with probability at least . The full proofs are in proofs/correctness.md.
Proof: The binary tree counter is exact without noise, epsilon-DP, and has polylog errorfull
We use the pseudocode of the page. The stream is with , and is the number of bits of . Two streams are neighbors if they have the same length and differ at one time step (event-level, replace one item). The stream is fixed before the run starts. For let be the value of the lowest one bit of , and let the node closed at time be the interval of time steps. Its exact value is .
Claim 1 (the count without noise). If the noise in line L6 is 0, the output at time is .
Proof. For and a bit of equal to 1, let be with its bits below set to 0. Then the intervals , for the one bits of , are disjoint and their union is : going from the highest one bit down, each starts where the one before it ends.
Invariant. After step (and before step 1 for ), for each : if bit of is 1, then ; if bit of is 0, then .
Base. For all bits are 0, and all start at 0.
Step. Let be the lowest one bit of (line L3). Then has bits equal to 1, bit equal to 0, and the same higher bits as . By the invariant at , the values are the exact values of the nodes for these low bits, and by the first paragraph their intervals partition . So line L4 sets , and . Line L5 sets for , where the bits of are 0. For the bits of and are the same, and so are and , so stays correct. This proves the invariant.
Line L7 sums over the one bits of , which is by the partition.
With noise, line L6 adds a fresh draw to the node closed at time , one time, and lines L5 and L7 only move or reuse these values. So by the same invariant, the output at time is
a sum of independent noise draws. Each output is a fixed function of the noisy node values for .
Claim 2 (privacy). With independent, the sequence of outputs is -DP for event-level neighbors.
Proof. Let . Fix a time . The nodes with have disjoint intervals of length , so lies in at most one node of each level . The levels that occur for are , because . So lies in at most nodes. If and differ only at time , then and
So has sensitivity at most . The vector is the Laplace mechanism with scale on a function of sensitivity . For each point , the triangle inequality gives
so the noisy node vector is -DP. The outputs are a fixed function of it (Claim 1), so they are -DP by post-processing.
The bound is reached: for the time lies in the nodes .
Claim 3 (error). The error has mean 0 and variance . For each :
- for one fixed , with probability at least ;
- for all at the same time, with probability at least .
Proof. The error is a sum of independent draws with , each of mean 0 and variance . This gives the mean and the variance. For a Laplace draw, . For item 1, take and the union bound over the at most draws in : with probability at least each of them is at most , and the sum is at most . For item 2, take and the union bound over all draws.
Chan, Shi and Song give the sharper bound for one time step, with a concentration bound for sums of Laplace variables in place of the union bound.
Cost. Line L4 adds at most values and line L7 adds at most values, so each step costs operations and one Laplace draw. The state is the values and , so the extra space is . Over the whole stream the time is .
Complexity
In the real-RAM model with one Laplace draw at unit cost:
- Each step adds at most values in line L4 and at most values in line L7. So a step costs , and the whole stream .
- The state is the values and , so the extra space is .
- Each step draws one Laplace value.
Line L4 adds values at time , and the sum of over all is less than . So line L4 costs amortized, and line L7 sets the cost of one step.
Properties
- Online. The release at time uses only nodes that are closed by time , so it uses only .
- Unbiased. Each has mean .
- Event-level privacy. The guarantee is for neighbors that differ at one time step. If one person adds many items to the stream, group privacy over that number of steps applies, and the cost grows with it.
- Consistent noise. A node's noise is drawn one time and reused. So the releases are correlated: for example is the noisy node .
- Pure DP. With Laplace noise the mechanism is -DP. With Gaussian noise of scale set by the sensitivity , it is -DP, as in the Gaussian mechanism.
Variants and improvements
- Unknown . The hybrid mechanism of Chan, Shi and Song runs a new tree for each block of length , and a separate counter over the block totals. It needs no bound on and keeps polylog error.
- Sharper error. Chan, Shi and Song prove the bound for one time step, with a concentration bound for sums of Laplace variables.
- Lower bound. Dwork, Naor, Pitassi and Rothblum show that any -DP continual counter has error of order at some step. So the polylog error is close to the best possible.
- Matrix view. The release is with the prefix-sum matrix and the 0-1 matrix of the tree nodes. The matrix mechanism searches over all strategies , and later work on factorization mechanisms finds strategies with smaller constants for prefix sums.
- Sums of vectors. The same tree releases running sums of vectors of bounded norm. Private online learning and the DP-FTRL optimizer of Kairouz and others (ICML 2021) use it to add noise to running sums of gradients.
When to use it
Use the binary tree mechanism when you must release a running count or a running sum at many time steps, and each item belongs to one event. Examples are counts of events posted each hour, and running gradient sums in private training. If you need only the final count, one draw of the Laplace mechanism is better. If you need all prefix sums of a fixed dataset at once, and not online, the matrix mechanism can choose a better strategy. If each person contributes many items, use a user-level bound and scale the noise to it.
Pitfalls
- Too few levels. Line L1 must use , the number of bits of . The common shorthand is one too small when is a power of two: for it gives 3, but the time step 1 lies in 4 nodes. Then line L6 adds and the mechanism is only -DP. The test file checks that the bound is reached for .
- Fresh noise at each release. Line L6 draws the noise of a node one time, and line L7 reuses it. Drawing new noise for each node each time it is used in line L7 gives many independent noisy copies of the same node. An observer averages them, and the privacy loss grows with the number of uses.
- Noise scaled to one node. The scale in line L6 is , not . With on each node, the noisy node vector is only -DP, because one change moves nodes.
- Items outside the range. The sensitivity bound needs . For real items, clip each item to (or scale the noise to the range) before line L4.
- Float noise. The code uses float Laplace noise from
random.Random, for tests only. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012; Canonne, Kamath and Steinke 2020); see the discrete Gaussian mechanism.
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
# Part of https://algorithm.tamnd.com/binary-tree-mechanism/. The authors are listed in prov/6G5Z3M.jsonl.
"""The binary tree mechanism for continual counting (Chan, Shi and Song 2010;
Dwork, Naor, Pitassi and Rothblum 2010), in its streaming form.
The input is a stream of bits sigma(1), ..., sigma(T). At each time t the
mechanism releases a noisy count of the ones seen so far. Neighbors are
event-level: two streams of the same length T that differ at one time step.
The code uses random.Random so that the tests can be repeated, and it adds
float noise. Both are fine for study and wrong for a deployment: a real
release needs a cryptographic source of randomness and an exact sampler
(Mironov 2012; Canonne, Kamath and Steinke 2020).
"""
from __future__ import annotations
import math
import random
from typing import Callable, Sequence
def laplace_noise(b: float, rng: random.Random) -> float:
"""One draw of Lap(b), the density (1/(2b)) exp(-|z|/b), by the inverse CDF.
Precondition: b > 0. Cost: one uniform draw and O(1) time.
"""
u = rng.random() - 0.5
while u == -0.5: # the open interval (-1/2, 1/2) excludes -1/2
u = rng.random() - 0.5
s = (u > 0) - (u < 0)
return -b * s * math.log(1.0 - 2.0 * abs(u))
def levels(T: int) -> int:
"""The number of levels L = floor(log2 T) + 1 of the dyadic tree over 1..T. Precondition: T >= 1."""
if T < 1:
raise ValueError("T must be at least 1")
return T.bit_length()
def node_interval(t: int) -> tuple[int, int]:
"""The dyadic interval (t - 2^i, t] of the node closed at time t, where 2^i is the lowest one bit of t.
Returned as the pair (first, last) of time steps. Precondition: t >= 1.
"""
low = t & -t
return (t - low + 1, t)
def binary_tree_counter_with_noise(
stream: Sequence[int],
noise: Callable[[int], float],
) -> tuple[list[float], list[float]]:
"""Run the streaming binary mechanism with a given noise source.
noise(t) is the noise added to the node closed at time t. The function
returns (outputs, nodes): outputs[t - 1] is the release at time t, and
nodes[t - 1] is the noisy value of the node closed at time t.
Precondition: the items are 0 or 1 (any reals work for the sums).
Cost: O(T log T) time in total, O(log T) per step, and O(log T) words
of state besides the returned lists.
"""
T = len(stream)
if T == 0:
return [], []
L = levels(T) # @line L1
a = [0.0] * L # exact p-sums, one per level
a_hat = [0.0] * L # their noisy values
outputs: list[float] = []
nodes: list[float] = []
for t in range(1, T + 1): # @line L2
i = ((t & -t).bit_length()) - 1 # @line L3
a[i] = stream[t - 1] + sum(a[:i]) # @line L4
for j in range(i): # @line L5
a[j] = 0.0
a_hat[j] = 0.0
a_hat[i] = a[i] + noise(t) # @line L6
nodes.append(a_hat[i])
outputs.append(sum(a_hat[j] for j in range(L) if (t >> j) & 1)) # @line L7
return outputs, nodes
def binary_tree_counter(stream: Sequence[int], epsilon: float, rng: random.Random) -> list[float]:
"""Release a noisy running count of a bit stream with the binary tree mechanism.
Each node gets Lap(L / epsilon) noise, with L = floor(log2 T) + 1. Every
time step lies in at most L nodes, so the vector of noisy nodes is
epsilon-DP for event-level neighbors, and the outputs, which are sums of
nodes, are epsilon-DP by post-processing.
Precondition: epsilon > 0 and the items are 0 or 1.
Cost: O(log T) time and one Laplace draw per step.
"""
if epsilon <= 0:
raise ValueError("epsilon must be positive")
if not stream:
return []
b = levels(len(stream)) / epsilon
outputs, _ = binary_tree_counter_with_noise(stream, lambda t: laplace_noise(b, rng))
return outputs
def node_vector(stream: Sequence[int]) -> list[int]:
"""The exact value of each node: nodes[t - 1] is the sum of the stream over node_interval(t). Cost: O(T log T)."""
out = []
for t in range(1, len(stream) + 1):
lo, hi = node_interval(t)
out.append(sum(stream[lo - 1:hi]))
return out
def error_variance(t: int, T: int, epsilon: float) -> float:
"""The exact variance of the release at time t: popcount(t) nodes, each with variance 2 (L / epsilon)^2."""
b = levels(T) / epsilon
return bin(t).count("1") * 2.0 * b * b
dpkit.py 208 lines
# 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
test_binary_tree_mechanism.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binary-tree-mechanism/. The authors are listed in prov/6G5Z3M.jsonl.
import itertools
import math
import random
import dpkit
from binary_tree_mechanism import (
binary_tree_counter,
binary_tree_counter_with_noise,
error_variance,
laplace_noise,
levels,
node_interval,
node_vector,
)
def _prefix(stream):
return list(itertools.accumulate(stream))
def test_levels_and_intervals() -> None:
assert [levels(T) for T in (1, 2, 3, 4, 7, 8, 9)] == [1, 2, 2, 3, 3, 4, 4]
assert [node_interval(t) for t in range(1, 9)] == [(1, 1), (1, 2), (3, 3), (1, 4), (5, 5), (5, 6), (7, 7), (1, 8)]
def test_zero_noise_gives_exact_prefix_sums_on_random_streams() -> None:
rng = random.Random(1)
for _ in range(600):
T = rng.randrange(1, 40)
stream = [rng.randrange(2) for _ in range(T)]
outputs, nodes = binary_tree_counter_with_noise(stream, lambda t: 0.0)
assert outputs == [float(c) for c in _prefix(stream)]
assert nodes == [float(v) for v in node_vector(stream)]
def test_each_release_sums_popcount_nodes() -> None:
# Tag the noise of node t with 1000^... style weights: give node t the noise 2^t.
stream = [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1]
outputs, _ = binary_tree_counter_with_noise(stream, lambda t: float(2 ** t))
for t, (o, c) in enumerate(zip(outputs, _prefix(stream)), start=1):
used = round(o - c)
nodes_used = [u for u in range(1, t + 1) if (used >> u) & 1]
# The nodes used at time t are the nodes closed at the prefixes of t's binary form.
want, rest = [], t
while rest:
want.append(rest)
rest -= rest & -rest
assert sorted(nodes_used) == sorted(want)
assert len(nodes_used) == bin(t).count("1") <= levels(len(stream))
def test_node_sensitivity_is_at_most_L_and_reached() -> None:
for T in range(1, 9):
L = levels(T)
worst = 0
for stream in itertools.product((0, 1), repeat=T):
base = node_vector(stream)
for s in range(T):
other = list(stream)
other[s] = 1 - other[s]
d = sum(abs(p - q) for p, q in zip(base, node_vector(other)))
worst = max(worst, d)
assert worst <= L
if T in (1, 2, 4, 8):
assert worst == L # time 1 lies in L nodes when T is a power of two
def _logpdf_nodes(point, centers, b):
return sum(-abs(z - c) / b - math.log(2 * b) for z, c in zip(point, centers))
def test_log_density_ratio_of_noisy_nodes_is_at_most_epsilon() -> None:
rng = random.Random(2)
T, epsilon = 8, 0.7
b = levels(T) / epsilon
for _ in range(40):
stream = [rng.randrange(2) for _ in range(T)]
s = rng.randrange(T)
other = list(stream)
other[s] = 1 - other[s]
cx, cy = node_vector(stream), node_vector(other)
base = [rng.uniform(-20, 20) for _ in range(T)]
direction = [rng.uniform(-1, 1) for _ in range(T)]
def fx(z):
return _logpdf_nodes([p + z * d for p, d in zip(base, direction)], cx, b)
def fy(z):
return _logpdf_nodes([p + z * d for p, d in zip(base, direction)], cy, b)
grid = [k / 4 for k in range(-400, 401)]
assert dpkit.log_ratio_grid(fx, fy, grid) <= epsilon + 1e-9
# Tightness: at time 1 with T = 8 the change hits all 4 nodes over (1, 1), (1, 2), (1, 4), (1, 8).
x = [0] * T
y = [1] + [0] * (T - 1)
cx, cy = node_vector(x), node_vector(y)
far = [-100.0] * T # far left of both centers, every coordinate moves the ratio the same way
assert math.isclose(_logpdf_nodes(far, cx, b) - _logpdf_nodes(far, cy, b), epsilon)
def test_mean_square_error_matches_formula() -> None:
rng = random.Random(3)
T, epsilon, runs = 8, 1.0, 2000
stream = [1, 0, 1, 1, 0, 1, 1, 1]
true = _prefix(stream)
sq = [0.0] * T
for _ in range(runs):
out = binary_tree_counter(stream, epsilon, rng)
for t in range(T):
sq[t] += (out[t] - true[t]) ** 2
for t in range(1, T + 1):
want = error_variance(t, T, epsilon)
assert abs(sq[t - 1] / runs - want) <= 0.25 * want # about 5 standard errors
def test_error_tail_within_chebyshev_bound() -> None:
rng = random.Random(4)
T, epsilon, runs, beta = 32, 1.0, 1000, 0.1
stream = [rng.randrange(2) for _ in range(T)]
true = _prefix(stream)
bad = 0
for _ in range(runs):
out = binary_tree_counter(stream, epsilon, rng)
t = T - 1 # popcount(31) = 5 nodes, the worst time for T = 32
bad += abs(out[t - 1] - true[t - 1]) > math.sqrt(error_variance(t, T, epsilon) / beta)
assert bad / runs <= beta + dpkit.hoeffding_margin(runs, 1e-6)
def test_laplace_tail_check_value() -> None:
rng = random.Random(5)
zs = [laplace_noise(2.0, rng) for _ in range(2000)]
frac = sum(1 for z in zs if abs(z) > 2 * math.log(10)) / len(zs)
assert abs(frac - 0.1) <= dpkit.hoeffding_margin(len(zs), 1e-6)
def test_edges() -> None:
rng = random.Random(6)
assert binary_tree_counter([], 1.0, rng) == []
assert len(binary_tree_counter([1], 1.0, rng)) == 1
try:
binary_tree_counter([1], 0.0, rng)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
Chan, Shi and Song (ICALP 2010) and Dwork, Naor, Pitassi and Rothblum (STOC 2010) found the mechanism at the same time. Chan, Shi and Song called it the binary mechanism, and also gave the hybrid mechanism for streams of unknown length. Dwork, Naor, Pitassi and Rothblum framed the problem as differential privacy under continual observation, and proved a lower bound of order on the error. The tree later became a standard tool for private online learning and, from 2021, for private training with noisy running sums of gradients.
References
- T.-H. Hubert Chan, Elaine Shi and Dawn Song, Private and continual release of statistics, ICALP 2010; full version in ACM Transactions on Information and System Security 14(3), 2011, the binary mechanism, its error bound, and the hybrid mechanism for streams of unknown length
- Cynthia Dwork, Moni Naor, Toniann Pitassi and Guy N. Rothblum, Differential privacy under continual observation, STOC 2010, pages 715 to 724, the tree counter for event-level privacy and the lower bound of order log T on the error
- Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point Laplace noise and the snapping defense
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 6G5Z3M Edit this page History Report an error Markdown