Algorithm Search⌘K

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
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 tt 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 t\sqrt{t}. 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 log⁡2T+1\log_2 T + 1 of them, and each bit is in at most log⁡2T+1\log_2 T + 1 of them. So the error is polylogarithmic in TT and the whole output stream is ε\varepsilon-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 σ(1),…,σ(T)\sigma(1), \ldots, \sigma(T) with σ(t)∈{0,1}\sigma(t) \in \{0, 1\} and a known length TT. At each time tt the mechanism must output an estimate sts_t of the count ct=∑s≤tσ(s)c_t = \sum_{s \le t} \sigma(s), using only σ(1),…,σ(t)\sigma(1), \ldots, \sigma(t). 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 (s1,…,sT)(s_1, \ldots, s_T) is ε\varepsilon-DP, with a small error max⁡t∣st−ct∣\max_t |s_t - c_t|.

Lap(b)\mathrm{Lap}(b) is the Laplace distribution with density 12be−∣z∣/b\frac{1}{2b} e^{-|z|/b}. It has variance 2b22b^2, and P(∣Z∣>t)=e−t/bP(|Z| > t) = e^{-t/b}.

The algorithm

Let L=⌊log⁡2T⌋+1L = \lfloor \log_2 T \rfloor + 1 be the number of bits of TT. The node closed at time uu is the interval (u−2i,u](u - 2^i, u], where 2i2^i is the lowest one bit of uu. The mechanism keeps one exact partial sum aja_j and one noisy partial sum a^j\hat a_j for each level j<Lj < L.

  1. BINARY-TREE-COUNTER(σ(1..T), ε)
  2. 1L ← ⌊log₂ T⌋ + 1 ▷ the number of levels
  3. 2for t ← 1 to T do
  4. 3i ← the index of the lowest 1 bit of t
  5. 4aᵢ ← σ(t) + Σ_{j<i} aⱼ ▷ the node (t − 2ⁱ, t] closes now
  6. 5for j ← 0 to i − 1 do aⱼ ← 0, âⱼ ← 0
  7. 6âᵢ ← aᵢ + Lap(L/ε) ▷ noise one time for each node
  8. 7output sₜ ← Σ_{j : bit j of t is 1} âⱼ

Line L3 finds the level of the node that closes at time tt. Line L4 merges the ii smaller nodes below it, which together cover (t−2i,t−1](t - 2^i, t - 1], and adds the new item. Line L5 clears the merged levels. Line L6 adds the noise, one time for each node. Line L7 writes tt in binary and adds one noisy node for each one bit. For t=6=1102t = 6 = 110_2 these are the nodes (0,4](0, 4] and (4,6](4, 6].

Example

Take T=8T = 8, ε=1\varepsilon = 1 and the stream 1,0,1,1,0,1,1,11, 0, 1, 1, 0, 1, 1, 1. Then L=4L = 4 and each node gets Lap(4)\mathrm{Lap}(4) noise. The run of the code with random.Random(1) gives the values below, rounded to two places.

tt σ(t)\sigma(t) ii node exact node noisy node nodes used in L7 sts_t ctc_t
1 1 0 (0,1](0, 1] 1 −4.26-4.26 (0,1](0,1] −4.26-4.26 1
2 0 1 (0,2](0, 2] 1 5.75 (0,2](0,2] 5.75 1
3 1 0 (2,3](2, 3] 1 4.00 (0,2],(2,3](0,2], (2,3] 9.75 2
4 1 2 (0,4](0, 4] 3 0.31 (0,4](0,4] 0.31 3
5 0 0 (4,5](4, 5] 0 −0.04-0.04 (0,4],(4,5](0,4], (4,5] 0.27 3
6 1 1 (4,6](4, 6] 1 0.57 (0,4],(4,6](0,4], (4,6] 0.88 4
7 1 0 (6,7](6, 7] 1 2.45 (0,4],(4,6],(6,7](0,4], (4,6], (6,7] 3.33 5
8 1 3 (0,8](0, 8] 6 9.45 (0,8](0,8] 9.45 6

The time step 1 is in the four nodes (0,1](0,1], (0,2](0,2], (0,4](0,4] and (0,8](0,8], which is why the scale is L/ε=4L/\varepsilon = 4. The release at t=7t = 7 uses three nodes, so its variance is 3⋅2⋅42=963 \cdot 2 \cdot 4^2 = 96. The other releases use one or two nodes, with variance 32 or 64. At this small TT the noise is larger than the counts. The method pays off for long streams: for T=220T = 2^{20} the variance is at most 2⋅213=185222 \cdot 21^3 = 18522, a standard error of about 136, while Laplace noise on each bit gives a variance of 2t2t, about 2.1⋅1062.1 \cdot 10^6 at t=Tt = T.

Correctness

Exact sums (a theorem). With the noise set to 0, the output at time tt is ctc_t. The invariant: after step tt, for each one bit jj of tt, aja_j is the exact sum over the node of level jj in the binary form of tt, and aj=0a_j = 0 for each zero bit. Line L4 keeps it because the nodes of the low bits of t−1t - 1 partition (t−2i,t−1](t - 2^i, t - 1].

Privacy (a theorem). Each time step lies in at most one node of each level, so in at most LL nodes. A change at one time step changes the vector of node values by at most LL in ℓ1\ell_1 norm. So the vector of noisy nodes, with Lap(L/ε)\mathrm{Lap}(L/\varepsilon) on each, is ε\varepsilon-DP by the Laplace mechanism. The outputs are sums of noisy nodes, so they are ε\varepsilon-DP by post-processing.

Error (a theorem). The error at time tt is a sum of popcount(t)≤L\mathrm{popcount}(t) \le L independent Lap(L/ε)\mathrm{Lap}(L/\varepsilon) draws. It has mean 0 and variance 2 popcount(t) L2/ε22\,\mathrm{popcount}(t)\,L^2/\varepsilon^2. By the union bound, all TT errors are at most L2ln⁡(T/β)/εL^2 \ln(T/\beta)/\varepsilon with probability at least 1−β1 - \beta. 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 σ(1),…,σ(T)\sigma(1), \ldots, \sigma(T) with σ(t)∈{0,1}\sigma(t) \in \{0, 1\}, and L=⌊log⁡2T⌋+1L = \lfloor \log_2 T \rfloor + 1 is the number of bits of TT. Two streams are neighbors if they have the same length TT and differ at one time step (event-level, replace one item). The stream is fixed before the run starts. For u≥1u \ge 1 let low(u)\mathrm{low}(u) be the value of the lowest one bit of uu, and let the node closed at time uu be the interval I(u)=(u−low(u),u]I(u) = (u - \mathrm{low}(u), u] of time steps. Its exact value is nu=∑s∈I(u)σ(s)n_u = \sum_{s \in I(u)} \sigma(s).

Claim 1 (the count without noise). If the noise in line L6 is 0, the output at time tt is ct=∑s≤tσ(s)c_t = \sum_{s \le t} \sigma(s).

Proof. For t≥0t \ge 0 and a bit jj of tt equal to 1, let tjt_j be tt with its bits below jj set to 0. Then the intervals I(tj)I(t_j), for the one bits jj of tt, are disjoint and their union is (0,t](0, t]: going from the highest one bit down, each I(tj)I(t_j) starts where the one before it ends.

Invariant. After step tt (and before step 1 for t=0t = 0), for each j<Lj < L: if bit jj of tt is 1, then aj=ntja_j = n_{t_j}; if bit jj of tt is 0, then aj=0a_j = 0.

Base. For t=0t = 0 all bits are 0, and all aja_j start at 0.

Step. Let ii be the lowest one bit of tt (line L3). Then t−1t - 1 has bits 0,…,i−10, \ldots, i-1 equal to 1, bit ii equal to 0, and the same higher bits as tt. By the invariant at t−1t - 1, the values a0,…,ai−1a_0, \ldots, a_{i-1} are the exact values of the nodes for these low bits, and by the first paragraph their intervals partition (t−2i,t−1](t - 2^i, t - 1]. So line L4 sets ai=σ(t)+∑s∈(t−2i,t−1]σ(s)=nta_i = \sigma(t) + \sum_{s \in (t - 2^i, t-1]} \sigma(s) = n_t, and ti=tt_i = t. Line L5 sets aj=0a_j = 0 for j<ij < i, where the bits of tt are 0. For j>ij > i the bits of tt and t−1t - 1 are the same, and so are tjt_j and (t−1)j(t-1)_j, so aja_j stays correct. This proves the invariant.

Line L7 sums aja_j over the one bits jj of tt, which is ∑jntj=ct\sum_j n_{t_j} = c_t by the partition. □\square

With noise, line L6 adds a fresh draw ηt\eta_t to the node closed at time tt, one time, and lines L5 and L7 only move or reuse these values. So by the same invariant, the output at time tt is

st=ct+∑j:bit j of t is 1ηtj,s_t = c_t + \sum_{j : \text{bit } j \text{ of } t \text{ is } 1} \eta_{t_j},

a sum of popcount(t)\mathrm{popcount}(t) independent noise draws. Each output is a fixed function of the noisy node values n^u=nu+ηu\hat n_u = n_u + \eta_u for u≤tu \le t.

Claim 2 (privacy). With ηu∼Lap(L/ε)\eta_u \sim \mathrm{Lap}(L/\varepsilon) independent, the sequence of outputs (s1,…,sT)(s_1, \ldots, s_T) is ε\varepsilon-DP for event-level neighbors.

Proof. Let N(σ)=(n1,…,nT)N(\sigma) = (n_1, \ldots, n_T). Fix a time ss. The nodes uu with low(u)=2i\mathrm{low}(u) = 2^i have disjoint intervals of length 2i2^i, so ss lies in at most one node of each level ii. The levels that occur for u≤Tu \le T are i=0,…,L−1i = 0, \ldots, L - 1, because 2i≤T2^i \le T. So ss lies in at most LL nodes. If σ\sigma and σ′\sigma' differ only at time ss, then ∣σ(s)−σ′(s)∣≤1|\sigma(s) - \sigma'(s)| \le 1 and

∥N(σ)−N(σ′)∥1=∑u:s∈I(u)∣σ(s)−σ′(s)∣≤L.\|N(\sigma) - N(\sigma')\|_1 = \sum_{u : s \in I(u)} |\sigma(s) - \sigma'(s)| \le L.

So NN has ℓ1\ell_1 sensitivity at most LL. The vector N(σ)+(η1,…,ηT)N(\sigma) + (\eta_1, \ldots, \eta_T) is the Laplace mechanism with scale L/εL/\varepsilon on a function of sensitivity LL. For each point z∈RTz \in \mathbb{R}^T, the triangle inequality gives

∏uexp⁡(−∣zu−nu(σ)∣ε/L)∏uexp⁡(−∣zu−nu(σ′)∣ε/L)≤exp⁡(εL∥N(σ)−N(σ′)∥1)≤eε,\frac{\prod_u \exp(-|z_u - n_u(\sigma)| \varepsilon / L)}{\prod_u \exp(-|z_u - n_u(\sigma')| \varepsilon / L)} \le \exp\Big(\frac{\varepsilon}{L} \|N(\sigma) - N(\sigma')\|_1\Big) \le e^{\varepsilon},

so the noisy node vector is ε\varepsilon-DP. The outputs are a fixed function of it (Claim 1), so they are ε\varepsilon-DP by post-processing. □\square

The bound LL is reached: for T=2mT = 2^m the time s=1s = 1 lies in the L=m+1L = m + 1 nodes I(1),I(2),I(4),…,I(2m)I(1), I(2), I(4), \ldots, I(2^m).

Claim 3 (error). The error st−cts_t - c_t has mean 0 and variance 2 popcount(t) L2/ε2≤2L3/ε22\,\mathrm{popcount}(t)\,L^2/\varepsilon^2 \le 2L^3/\varepsilon^2. For each β∈(0,1)\beta \in (0, 1):

  1. for one fixed tt, ∣st−ct∣≤L2ln⁡(L/β)/ε|s_t - c_t| \le L^2 \ln(L/\beta)/\varepsilon with probability at least 1−β1 - \beta;
  2. for all t≤Tt \le T at the same time, ∣st−ct∣≤L2ln⁡(T/β)/ε|s_t - c_t| \le L^2 \ln(T/\beta)/\varepsilon with probability at least 1−β1 - \beta.

Proof. The error is a sum of popcount(t)≤L\mathrm{popcount}(t) \le L independent Lap(b)\mathrm{Lap}(b) draws with b=L/εb = L/\varepsilon, each of mean 0 and variance 2b22b^2. This gives the mean and the variance. For a Laplace draw, P(∣η∣>bln⁡(1/p))=pP(|\eta| > b \ln(1/p)) = p. For item 1, take p=β/Lp = \beta/L and the union bound over the at most LL draws in sts_t: with probability at least 1−β1 - \beta each of them is at most bln⁡(L/β)b \ln(L/\beta), and the sum is at most Lbln⁡(L/β)L b \ln(L/\beta). For item 2, take p=β/Tp = \beta/T and the union bound over all TT draws. □\square

Chan, Shi and Song give the sharper bound O(ε−1(log⁡T)1.5log⁡(1/β))O(\varepsilon^{-1} (\log T)^{1.5} \log(1/\beta)) 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 LL values and line L7 adds at most LL values, so each step costs O(L)=O(log⁡T)O(L) = O(\log T) operations and one Laplace draw. The state is the 2L2L values aja_j and a^j\hat a_j, so the extra space is O(log⁡T)O(\log T). Over the whole stream the time is O(Tlog⁡T)O(T \log T).

Complexity

In the real-RAM model with one Laplace draw at unit cost:

  • Each step adds at most LL values in line L4 and at most LL values in line L7. So a step costs O(log⁡T)O(\log T), and the whole stream O(Tlog⁡T)O(T \log T).
  • The state is the 2L2L values aja_j and a^j\hat a_j, so the extra space is O(log⁡T)O(\log T).
  • Each step draws one Laplace value.

Line L4 adds ii values at time tt, and the sum of ii over all t≤Tt \le T is less than TT. So line L4 costs O(1)O(1) amortized, and line L7 sets the O(log⁡T)O(\log T) cost of one step.

Properties

  • Online. The release at time tt uses only nodes that are closed by time tt, so it uses only σ(1),…,σ(t)\sigma(1), \ldots, \sigma(t).
  • Unbiased. Each sts_t has mean ctc_t.
  • 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 s5−s4s_5 - s_4 is the noisy node (4,5](4, 5].
  • Pure DP. With Laplace noise the mechanism is (ε,0)(\varepsilon, 0)-DP. With Gaussian noise of scale set by the ℓ2\ell_2 sensitivity L\sqrt{L}, it is (ε,δ)(\varepsilon, \delta)-DP, as in the Gaussian mechanism.

Variants and improvements

  • Unknown TT. The hybrid mechanism of Chan, Shi and Song runs a new tree for each block of length 2k2^k, and a separate counter over the block totals. It needs no bound on TT and keeps polylog error.
  • Sharper error. Chan, Shi and Song prove the bound O(ε−1(log⁡T)1.5log⁡(1/β))O(\varepsilon^{-1} (\log T)^{1.5} \log(1/\beta)) for one time step, with a concentration bound for sums of Laplace variables.
  • Lower bound. Dwork, Naor, Pitassi and Rothblum show that any ε\varepsilon-DP continual counter has error of order log⁡T\log T at some step. So the polylog error is close to the best possible.
  • Matrix view. The release is WA+(Aσ+z)W A^{+}(A\sigma + z) with WW the prefix-sum matrix and AA the 0-1 matrix of the tree nodes. The matrix mechanism searches over all strategies AA, 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 L=⌊log⁡2T⌋+1L = \lfloor \log_2 T \rfloor + 1, the number of bits of TT. The common shorthand ⌈log⁡2T⌉\lceil \log_2 T \rceil is one too small when TT is a power of two: for T=8T = 8 it gives 3, but the time step 1 lies in 4 nodes. Then line L6 adds Lap(3/ε)\mathrm{Lap}(3/\varepsilon) and the mechanism is only 43ε\frac{4}{3}\varepsilon-DP. The test file checks that the bound LL is reached for T=1,2,4,8T = 1, 2, 4, 8.
  • 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 L/εL/\varepsilon, not 1/ε1/\varepsilon. With Lap(1/ε)\mathrm{Lap}(1/\varepsilon) on each node, the noisy node vector is only LεL\varepsilon-DP, because one change moves LL nodes.
  • Items outside the range. The sensitivity bound needs ∣σ(t)−σ′(t)∣≤1|\sigma(t) - \sigma'(t)| \le 1. For real items, clip each item to [0,1][0, 1] (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.

binary_tree_mechanism.pyI0RawGitHub
# 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 log⁡T\log T 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

  1. 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
  2. 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
  3. 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.

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