Algorithm Search⌘K

Algorithmresearch

Matrix mechanism

Also called strategy matrix mechanism.

Answers a workload of linear queries by adding Laplace noise to a chosen strategy set of queries and then deriving the workload answers by least squares.

Time
O(p n^2 + n^3 + m n) worst
Space
O(p n + m n) extra
Where
m = the number of workload queries; n = the number of cells; p = the number of strategy queries
Origin
Chao Li, Michael Hay, Vibhor Rastogi, Gerome Miklau, Andrew McGregor, 2010

The matrix mechanism answers a set of linear queries on a histogram, such as all range counts, by a detour. It picks a second set of linear queries, the strategy, and answers those with the Laplace mechanism. Then it finds the least squares estimate of the histogram from the noisy strategy answers, and computes the wanted queries from that estimate. The choice of strategy changes the error, often by a large factor, and the privacy cost stays ε\varepsilon. The identity strategy, the binary tree of ranges and wavelets are all special cases, and the mechanism gives one formula to compare them.

In plain words

You must publish many totals from one table of counts, for example the number of people in every age range. Many of the totals overlap, so each person affects many of them, and noise on each total must be large.

The matrix mechanism asks a different set of questions first. It picks them so that each person affects few of them, and so that the wanted totals can be built from them. It adds noise to those answers. Then it finds the table of counts that best fits the noisy answers, and computes all the wanted totals from that table. A good choice of the first questions gives much less noise in the totals.

The problem

The data is a histogram x∈Nnx \in \mathbb{N}^n: xjx_j is the number of records in cell jj. The workload is an m×nm \times n matrix WW, and the goal is to release an estimate of WxW x. Two histograms are neighbors if one is the other with one record added or removed: x′=x±ejx' = x \pm e_j. The release must be ε\varepsilon-DP, and the goal is a small expected total squared error E∥w^−Wx∥22\mathbb{E}\|\hat w - W x\|_2^2.

A strategy is a p×np \times n matrix AA of full column rank. Its sensitivity ΔA\Delta_A is the largest ℓ1\ell_1 norm of a column of AA, because a change in cell jj moves AxA x by the column AejA e_j.

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

  1. MATRIX-MECHANISM(W, A, x, ε)
  2. 1Δ_A ← max over columns j of Σᵢ |Aᵢⱼ| ▷ the l1 sensitivity of x ↦ Ax
  3. 2y ← A x + z, with zᵢ ~ Lap(Δ_A/ε) independent ▷ the Laplace mechanism on the strategy
  4. 3A⁺ ← (AᵀA)⁻¹ Aᵀ ▷ the pseudoinverse
  5. 4x̂ ← A⁺ y ▷ the least squares estimate of x
  6. 5output W x̂

Line L2 is the only step that reads the data. Lines L3 to L5 are post-processing, so they cost no privacy. Line L4 picks the x^\hat x that minimizes ∥Ax^−y∥2\|A \hat x - y\|_2, which also makes the answers consistent: they all come from one histogram. The pseudoinverse in line L3 can be computed by the normal equations as written, or more stably by a QR decomposition.

Example

Take n=4n = 4 cells with x=(3,0,5,2)x = (3, 0, 5, 2) and ε=1\varepsilon = 1. The workload WW is all 10 range queries xi+⋯+xjx_i + \cdots + x_j. The table compares three strategies by the error formula of the Correctness section. The values are exact and the test file checks them.

strategy AA rows pp ΔA\Delta_A total squared error over the 10 ranges
identity: one count per cell 4 1 40
hierarchical: the cells, the two halves and the total 7 3 876/7≈125.1876/7 \approx 125.1
the workload itself 10 6 288

Answering the 10 ranges directly is the worst choice, because a middle cell lies in 6 of them. At this small nn the identity is the best of the three. The run of the code with the hierarchical strategy and random.Random(1) draws the noisy strategy answers y=(−0.94,3.56,7.25,−0.02,2.97,6.68,11.08)y = (-0.94, 3.56, 7.25, -0.02, 2.97, 6.68, 11.08) for the true answers (3,0,5,2,3,7,10)(3, 0, 5, 2, 3, 7, 10). Least squares gives x^=(−0.63,3.87,7.26,−0.01)\hat x = (-0.63, 3.87, 7.26, -0.01), and the 10 range answers follow from x^\hat x.

The hierarchical strategy wins for large nn: its error for one range grows as (log⁡n)3(\log n)^3 (a theorem, from the binary tree bound), and the error of the identity grows as nn. The crossover is late. At n=64n = 64 the code gives a total error of 91520 for the identity and about 264672 for the hierarchical strategy (a measurement).

Correctness

Privacy (a theorem). For neighbors x′=x±ejx' = x \pm e_j, ∥Ax−Ax′∥1\|A x - A x'\|_1 is the ℓ1\ell_1 norm of column jj, at most ΔA\Delta_A. So line L2 is the Laplace mechanism with the right scale, and yy is ε\varepsilon-DP. Lines L3 to L5 do not read xx, so the output is ε\varepsilon-DP by post-processing.

Unbiased (a theorem). A+A=IA^+ A = I for a strategy of full column rank, so E[Wx^]=Wx\mathbb{E}[W \hat x] = W x.

Error (a theorem, Li et al. 2010). The expected total squared error is

2ΔA2ε2tr⁡(W(A⊤A)−1W⊤).\frac{2\Delta_A^2}{\varepsilon^2} \operatorname{tr}\big(W (A^\top A)^{-1} W^\top\big).

The key step is A+(A+)⊤=(A⊤A)−1A^+ (A^+)^\top = (A^\top A)^{-1}. For a fixed AA, least squares is the best linear reconstruction, by the Gauss-Markov argument. The full proofs are in proofs/correctness.md.

Proof: The matrix mechanism is epsilon-DP and unbiased, with error 2 (Delta_A/epsilon)^2 trace(W (A^T A)^(-1) W^T)full

We use the pseudocode of the page. The data is a histogram x∈Nnx \in \mathbb{N}^n. Two histograms are neighbors if they differ by 1 in one cell: x′=x±ejx' = x \pm e_j (add/remove one record). The workload is an m×nm \times n matrix WW and the strategy is a p×np \times n matrix AA of full column rank nn. Let ΔA=max⁡j∑i∣Aij∣\Delta_A = \max_j \sum_i |A_{ij}|, b=ΔA/εb = \Delta_A/\varepsilon, and A+=(A⊤A)−1A⊤A^+ = (A^\top A)^{-1} A^\top. The noise z=(z1,…,zp)z = (z_1, \ldots, z_p) has independent Lap(b)\mathrm{Lap}(b) entries.

Claim 1 (privacy). The output WA+(Ax+z)W A^+ (A x + z) is ε\varepsilon-DP.

Proof. For neighbors x′=x±ejx' = x \pm e_j, Ax′−Ax=±AejA x' - A x = \pm A e_j, the jj-th column of AA up to sign. So ∥Ax−Ax′∥1=∑i∣Aij∣≤ΔA\|A x - A x'\|_1 = \sum_i |A_{ij}| \le \Delta_A, and ΔA\Delta_A is reached for the column with the largest ℓ1\ell_1 norm. The density of y=Ax+zy = A x + z at a point v∈Rpv \in \mathbb{R}^p is ∏i12be−∣vi−(Ax)i∣/b\prod_i \frac{1}{2b} e^{-|v_i - (Ax)_i|/b}. By the triangle inequality, for every vv,

px(v)px′(v)=exp⁡(1b∑i(∣vi−(Ax′)i∣−∣vi−(Ax)i∣))≤exp⁡(∥Ax−Ax′∥1b)≤eε.\frac{p_x(v)}{p_{x'}(v)} = \exp\Big(\frac{1}{b} \sum_i \big(|v_i - (Ax')_i| - |v_i - (Ax)_i|\big)\Big) \le \exp\Big(\frac{\|Ax - Ax'\|_1}{b}\Big) \le e^{\varepsilon}.

So yy is ε\varepsilon-DP. Lines L3 to L5 compute a fixed function of yy that does not look at xx, so the output is ε\varepsilon-DP by post-processing. □\square

Claim 2 (unbiased). E[WA+y]=Wx\mathbb{E}[W A^+ y] = W x.

Proof. A+A=(A⊤A)−1A⊤A=InA^+ A = (A^\top A)^{-1} A^\top A = I_n, and E[z]=0\mathbb{E}[z] = 0. So E[A+y]=A+Ax=x\mathbb{E}[A^+ y] = A^+ A x = x, and WW is linear. □\square

Claim 3 (error). The expected total squared error is

E ∥WA+y−Wx∥22=2b2tr⁡(W(A⊤A)−1W⊤)=2ΔA2ε2tr⁡(W(A⊤A)−1W⊤).\mathbb{E}\,\|W A^+ y - W x\|_2^2 = 2 b^2 \operatorname{tr}\big(W (A^\top A)^{-1} W^\top\big) = \frac{2\Delta_A^2}{\varepsilon^2} \operatorname{tr}\big(W (A^\top A)^{-1} W^\top\big).

Proof. The error is WA+zW A^+ z (Claim 2). The entries of zz are independent with mean 0 and variance 2b22b^2, so E[zz⊤]=2b2Ip\mathbb{E}[z z^\top] = 2b^2 I_p. Then

E ∥WA+z∥22=tr⁡(WA+ E[zz⊤] (A+)⊤W⊤)=2b2tr⁡(WA+(A+)⊤W⊤),\mathbb{E}\,\|W A^+ z\|_2^2 = \operatorname{tr}\big(W A^+ \,\mathbb{E}[z z^\top]\, (A^+)^\top W^\top\big) = 2b^2 \operatorname{tr}\big(W A^+ (A^+)^\top W^\top\big),

and A+(A+)⊤=(A⊤A)−1A⊤A(A⊤A)−1=(A⊤A)−1A^+ (A^+)^\top = (A^\top A)^{-1} A^\top A (A^\top A)^{-1} = (A^\top A)^{-1}. □\square

Claim 4 (least squares is the best linear reconstruction). Among all matrices BB with BA=WB A = W, the choice B=WA+B = W A^+ has the smallest expected total squared error E∥Bz∥22\mathbb{E}\|B z\|_2^2.

Proof. Each such BB gives an unbiased estimate ByB y of WxW x, with error E∥Bz∥2=2b2tr⁡(BB⊤)\mathbb{E}\|Bz\|^2 = 2b^2 \operatorname{tr}(B B^\top). Write B=WA++DB = W A^+ + D. Then DA=BA−WA+A=0D A = B A - W A^+ A = 0. So D(A+)⊤=DA(A⊤A)−1=0D (A^+)^\top = D A (A^\top A)^{-1} = 0, and

tr⁡(BB⊤)=tr⁡(WA+(A+)⊤W⊤)+2tr⁡(WA+D⊤)+tr⁡(DD⊤).\operatorname{tr}(B B^\top) = \operatorname{tr}(W A^+ (A^+)^\top W^\top) + 2 \operatorname{tr}(W A^+ D^\top) + \operatorname{tr}(D D^\top).

The middle term is 2tr⁡(D(A+)⊤W⊤)=02 \operatorname{tr}(D (A^+)^\top W^\top) = 0, and the last term is at least 0, with equality only for D=0D = 0. □\square

This is the Gauss-Markov theorem for independent noise of equal variance. It says that, for a fixed strategy AA, the only free choice left is AA itself.

Cost. Line L1 reads AA in O(pn)O(pn). Line L2 costs O(pn)O(pn) and pp Laplace draws. Line L3 forms A⊤AA^\top A in O(pn2)O(pn^2), inverts it in O(n3)O(n^3) and multiplies by A⊤A^\top in O(pn2)O(pn^2). Line L4 costs O(pn)O(pn) and line L5 costs O(mn)O(mn). The space is O(pn+mn)O(pn + mn) for the matrices. Lines L1 and L3 do not depend on the data, so for a fixed strategy they can be done one time and reused.

Complexity

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

  • Line L2 costs O(pn)O(pn) and pp draws.
  • Line L3 costs O(pn2+n3)O(pn^2 + n^3): it forms A⊤AA^\top A and inverts it.
  • Line L5 costs O(mn)O(mn).
  • The space is O(pn+mn)O(pn + mn) for the matrices.

Lines L1 and L3 do not depend on the data. For a fixed strategy they can be done one time and reused. The hard part in practice is not the mechanism but the choice of AA: the search for the best strategy is an optimization over matrices, and it is much more costly than one run.

Properties

  • Pure DP. With Laplace noise the output is (ε,0)(\varepsilon, 0)-DP.
  • Unbiased and consistent. The answers are unbiased, and they all come from one estimate x^\hat x, so overlapping answers agree.
  • Data independent. The error depends on WW, AA and ε\varepsilon, not on xx. So the error can be computed and compared before any data is touched.
  • Linear queries only. The workload must be linear in the histogram.
  • Negative estimates. The estimate x^\hat x can have negative cells, as in the example. Rounding or clipping it is post-processing, so it is still private, but it breaks the unbiased property.

Variants and improvements

  • Gaussian noise. For (ε,δ)(\varepsilon, \delta)-DP, use the Gaussian mechanism in line L2. The sensitivity becomes the largest ℓ2\ell_2 norm of a column, and the error has the same form with the Gaussian variance.
  • Strategy search. Li et al. give methods to search for a good AA for a given WW. HDMM (McKenna, Miklau, Hay and Machanavajjhala 2018) searches over strategies with a product structure, which scales to data with many attributes.
  • Known strategies. The identity, the hierarchical strategy of Hay, Rastogi, Miklau and Suciu (2010) and the wavelet strategy of Xiao, Wang and Gehrke (2010) are all instances. The binary tree mechanism for continual counting is the hierarchical strategy run online.
  • Factorization mechanisms. In general any factorization W=BAW = B A gives the release B(Ax+z)B(Ax + z). The matrix mechanism takes B=WA+B = W A^+, the best BB for a given AA. Later work on prefix sums and on private training searches over such factorizations directly.
  • Adaptive data methods. Methods that adapt the strategy to the data, such as MWEM, can do better on some data, but their error is no longer data independent.

When to use it

Use the matrix mechanism when the workload is a fixed, known set of linear queries on a histogram of moderate size, such as range queries, marginals of a few attributes, or the cells of a census table. It is best when many queries overlap, so that a good strategy shares the noise. For one query, or for queries on disjoint cells, the plain Laplace mechanism is already best. For a very large or unknown workload, see private query release.

Pitfalls

  • Sensitivity of the wrong matrix. Line L1 must use the strategy AA, not the workload WW. The noise is added to AxA x, so its scale is set by the columns of AA. Using ΔW\Delta_W is wrong in both directions: it gives too much noise when ΔW>ΔA\Delta_W > \Delta_A, and a privacy failure when ΔW<ΔA\Delta_W < \Delta_A.
  • Row norms in place of column norms. The sensitivity in line L1 is the largest column norm, because one record changes one cell. The largest row norm measures the size of one query, not the effect of one record. For the hierarchical strategy on nn cells it is nn, while ΔA=log⁡2n+1\Delta_A = \log_2 n + 1, and for a strategy with one long column it is smaller than ΔA\Delta_A.
  • A strategy without full column rank. Line L3 needs A⊤AA^\top A to be invertible. If AA does not have full column rank, some queries of WW cannot be built from AA. The code raises an error.
  • Unstable algebra. For large or badly conditioned AA, the normal equations in line L3 lose precision. Use a QR or Cholesky solve. The privacy proof does not depend on how line L3 is computed, but the error formula does.
  • 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.

dpkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Checkers for differential privacy on small finite examples.

A dataset is a tuple of records from a finite universe. A pmf is a dict from
outputs to probabilities; the probabilities may be fractions.Fraction (exact)
or float. A mechanism pmf is a function from a dataset to the pmf of the
output of the mechanism on that dataset.

This module holds the neighbor relations, the privacy loss, the hockey-stick
and Renyi divergences, the pure and approximate DP checks over a list of
neighbor pairs, an empirical pmf, the Hoeffding margin for Monte Carlo
checks, and a grid check of a log density ratio. It holds no mechanism, no
noise sampler and no accountant: those belong to the pages that define them.

Natural logarithms are used throughout, as in the DP literature.
"""

from __future__ import annotations

import math
from fractions import Fraction
from typing import Callable, Hashable, Iterable, Mapping, Sequence, Union

Number = Union[int, float, Fraction]
Pmf = Mapping[Hashable, Number]
Dataset = tuple
Pair = tuple[Dataset, Dataset]


def neighbors_add_remove(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
    """All datasets at add/remove distance 1 from dataset.

    A neighbor removes one record, or appends one record from the universe.
    Datasets are treated as multisets: a removal keeps the order of the other
    records, and equal results are listed once. Cost: O(n (n + |universe|)).
    """
    x = tuple(dataset)
    out: list[Dataset] = []
    seen: set[Dataset] = set()
    for i in range(len(x)):
        y = x[:i] + x[i + 1:]
        key = tuple(sorted(y, key=repr))
        if key not in seen:
            seen.add(key)
            out.append(y)
    for v in universe:
        y = x + (v,)
        key = tuple(sorted(y, key=repr))
        if key not in seen:
            seen.add(key)
            out.append(y)
    return out


def neighbors_replace(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
    """All datasets of the same size that differ from dataset in one record.

    The record at index i is replaced by a different value of the universe.
    Equal multisets are listed once. Cost: O(n^2 |universe|).
    """
    x = tuple(dataset)
    values = list(universe)
    out: list[Dataset] = []
    seen: set[Dataset] = set()
    for i in range(len(x)):
        for v in values:
            if v == x[i]:
                continue
            y = x[:i] + (v,) + x[i + 1:]
            key = tuple(sorted(y, key=repr))
            if key not in seen:
                seen.add(key)
                out.append(y)
    return out


def _ratio(a: Number, b: Number) -> Number:
    if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
        return Fraction(a) / Fraction(b)
    return float(a) / float(b)


def privacy_loss(p: Pmf, q: Pmf) -> dict[Hashable, float]:
    """The privacy loss ln(p(y) / q(y)) at each output y with p(y) > 0 or q(y) > 0.

    The value is +inf where q(y) = 0 < p(y) and -inf where p(y) = 0 < q(y).
    Outputs with p(y) = q(y) = 0 are left out. Cost: O(|support|).
    """
    out: dict[Hashable, float] = {}
    for y in set(p) | set(q):
        a, b = p.get(y, 0), q.get(y, 0)
        if a == 0 and b == 0:
            continue
        if b == 0:
            out[y] = math.inf
        elif a == 0:
            out[y] = -math.inf
        else:
            out[y] = math.log(_ratio(a, b))
    return out


def max_privacy_loss(p: Pmf, q: Pmf) -> float:
    """The largest privacy loss ln(p(y) / q(y)) over the outputs y with p(y) > 0.

    Returns -inf when p has no output of positive probability. Cost: O(|support|).
    """
    best = -math.inf
    for y, v in privacy_loss(p, q).items():
        if p.get(y, 0) > 0 and v > best:
            best = v
    return best


def hockey_stick(p: Pmf, q: Pmf, epsilon: float) -> float:
    """The hockey-stick divergence: the sum over y of max(0, p(y) - e^epsilon q(y)).

    It is sup over sets S of P(S) - e^epsilon Q(S). Cost: O(|support|).
    """
    a = math.exp(epsilon)
    total = 0.0
    for y in set(p) | set(q):
        d = float(p.get(y, 0)) - a * float(q.get(y, 0))
        if d > 0:
            total += d
    return total


def is_pure_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, tol: float = 1e-12) -> bool:
    """True if max privacy loss <= epsilon + tol for both orders of every pair.

    Precondition: mech_pmf returns the exact output pmf of the mechanism.
    Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
    """
    for x, y in pairs:
        p, q = mech_pmf(x), mech_pmf(y)
        if max_privacy_loss(p, q) > epsilon + tol or max_privacy_loss(q, p) > epsilon + tol:
            return False
    return True


def is_approx_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, delta: float, tol: float = 1e-12) -> bool:
    """True if the hockey-stick divergence at e^epsilon is <= delta + tol for both orders of every pair.

    Precondition: mech_pmf returns the exact output pmf of the mechanism.
    Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
    """
    for x, y in pairs:
        p, q = mech_pmf(x), mech_pmf(y)
        if hockey_stick(p, q, epsilon) > delta + tol or hockey_stick(q, p, epsilon) > delta + tol:
            return False
    return True


def renyi_divergence(p: Pmf, q: Pmf, alpha: float) -> float:
    """The Renyi divergence of order alpha > 1: ln(sum_y p(y)^alpha q(y)^(1 - alpha)) / (alpha - 1).

    Returns +inf when q(y) = 0 < p(y) for some y. Cost: O(|support|).
    """
    if alpha <= 1:
        raise ValueError("alpha must be greater than 1")
    s = 0.0
    for y in set(p) | set(q):
        a, b = float(p.get(y, 0)), float(q.get(y, 0))
        if a == 0:
            continue
        if b == 0:
            return math.inf
        s += a * (a / b) ** (alpha - 1)
    return math.log(s) / (alpha - 1)


def empirical_pmf(samples: Iterable[Hashable]) -> dict[Hashable, float]:
    """The fraction of the samples equal to each value. Cost: O(number of samples)."""
    counts: dict[Hashable, int] = {}
    n = 0
    for s in samples:
        counts[s] = counts.get(s, 0) + 1
        n += 1
    if n == 0:
        return {}
    return {k: c / n for k, c in counts.items()}


def hoeffding_margin(n: int, beta: float) -> float:
    """The margin t = sqrt(ln(2 / beta) / (2 n)).

    For n independent samples of a [0, 1] variable, the empirical mean is
    within t of the true mean with probability at least 1 - beta (Hoeffding).
    """
    if n <= 0 or not 0 < beta < 1:
        raise ValueError("need n >= 1 and 0 < beta < 1")
    return math.sqrt(math.log(2 / beta) / (2 * n))


def log_ratio_grid(logpdf_x: Callable[[float], float], logpdf_y: Callable[[float], float], grid: Iterable[float]) -> float:
    """The largest |logpdf_x(z) - logpdf_y(z)| over the points z of the grid.

    Use it to check the log density ratio of a continuous mechanism on two
    neighbors. Cost: O(|grid|) calls of each function.
    """
    best = 0.0
    for z in grid:
        d = abs(logpdf_x(z) - logpdf_y(z))
        if d > best:
            best = d
    return best
matrix_mechanism.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/matrix-mechanism/. The authors are listed in prov/73DA32.jsonl.
"""The matrix mechanism for a workload of linear counting queries
(Li, Hay, Rastogi, Miklau and McGregor 2010), with Laplace noise.

The data is a histogram x in N^n (one count per cell). The workload is an
m x n matrix W; the true answers are W x. The analyst picks a strategy, a
p x n matrix A of full column rank. The mechanism answers A x with Laplace
noise, finds the least squares estimate of x, and outputs W times it.

Neighbors are add/remove: x' = x + e_j or x - e_j for one cell j. Then the
l1 sensitivity of x -> A x is the largest l1 norm of a column of A.

The linear algebra works over any field type: pass Fraction entries for
exact results, or floats. The code uses random.Random so that the tests can
be repeated, and float noise. 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 fractions import Fraction
from typing import Sequence

Matrix = list[list]


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:
        u = rng.random() - 0.5
    s = (u > 0) - (u < 0)
    return -b * s * math.log(1.0 - 2.0 * abs(u))


def transpose(A: Sequence[Sequence]) -> Matrix:
    """The transpose of A. Cost: O(pn)."""
    return [list(col) for col in zip(*A)]


def matmul(A: Sequence[Sequence], B: Sequence[Sequence]) -> Matrix:
    """The product A B. Precondition: the inner sizes agree. Cost: O(m k n)."""
    Bt = transpose(B)
    return [[sum(a * b for a, b in zip(row, col)) for col in Bt] for row in A]


def matvec(A: Sequence[Sequence], x: Sequence) -> list:
    """The product A x. Cost: O(p n)."""
    return [sum(a * v for a, v in zip(row, x)) for row in A]


def inverse(M: Sequence[Sequence]) -> Matrix:
    """The inverse of a square matrix by Gauss-Jordan elimination with partial pivoting.

    Raises ValueError if M is singular (exactly for Fraction entries, to a
    tolerance of 1e-12 times the largest entry for floats). Cost: O(n^3).
    """
    n = len(M)
    exact = not any(isinstance(v, float) for row in M for v in row)
    one, zero = (Fraction(1), Fraction(0)) if exact else (1.0, 0.0)
    aug = [
        [Fraction(v) if exact else v for v in row] + [one if i == j else zero for j in range(n)]
        for i, row in enumerate(M)
    ]
    scale = max((abs(v) for row in M for v in row), default=0)
    tol = 0 if exact else 1e-12 * scale
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aug[r][c]))
        if abs(aug[p][c]) <= tol:
            raise ValueError("matrix is singular")
        aug[c], aug[p] = aug[p], aug[c]
        piv = aug[c][c]
        aug[c] = [v / piv for v in aug[c]]
        for r in range(n):
            if r != c and aug[r][c] != 0:
                f = aug[r][c]
                aug[r] = [a - f * b for a, b in zip(aug[r], aug[c])]
    return [row[n:] for row in aug]


def pseudoinverse(A: Sequence[Sequence]) -> Matrix:
    """The left inverse A^+ = (A^T A)^(-1) A^T of a matrix of full column rank.

    A^+ y is the least squares solution of A x = y. Raises ValueError if A
    does not have full column rank. Cost: O(p n^2 + n^3).
    """
    At = transpose(A)
    return matmul(inverse(matmul(At, A)), At)


def sensitivity(A: Sequence[Sequence]) -> float:
    """The l1 sensitivity of x -> A x under add/remove: the largest column l1 norm. Cost: O(p n)."""
    return max(sum(abs(v) for v in col) for col in zip(*A))


def matrix_mechanism(
    W: Sequence[Sequence],
    A: Sequence[Sequence],
    x: Sequence[int],
    epsilon: float,
    rng: random.Random,
) -> list[float]:
    """Answer the workload W on the histogram x through the strategy A, with epsilon-DP.

    Precondition: epsilon > 0, A has full column rank, and W and A have
    len(x) columns. Cost: O(p n^2 + n^3 + m n) arithmetic and p Laplace draws.
    """
    if epsilon <= 0:
        raise ValueError("epsilon must be positive")
    delta_a = sensitivity(A)  # @line L1
    b = delta_a / epsilon
    y = [v + laplace_noise(b, rng) for v in matvec(A, x)]  # @line L2
    A_plus = pseudoinverse([[float(v) for v in row] for row in A])  # @line L3
    x_hat = matvec(A_plus, y)  # @line L4
    return matvec(W, x_hat)  # @line L5


def total_squared_error(W: Sequence[Sequence], A: Sequence[Sequence], epsilon: float):
    """The expected total squared error 2 (Delta_A / epsilon)^2 trace(W (A^T A)^(-1) W^T).

    Exact if the entries are Fraction and epsilon is 1. Cost: O(p n^2 + n^3 + m n^2).
    """
    At = transpose(A)
    G = inverse(matmul(At, A))
    WG = matmul(W, G)
    tr = sum(sum(a * b for a, b in zip(WG[i], W[i])) for i in range(len(W)))
    d = sensitivity(A)
    return 2 * d * d * tr / (epsilon * epsilon)


def identity(n: int) -> Matrix:
    """The n x n identity strategy: one noisy count per cell."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def all_range_queries(n: int) -> Matrix:
    """The workload of all n(n+1)/2 range queries x[i] + ... + x[j] over n cells."""
    return [[1 if i <= k <= j else 0 for k in range(n)] for i in range(n) for j in range(i, n)]


def hierarchical_strategy(n: int) -> Matrix:
    """The binary hierarchical strategy: the sum over each dyadic block of cells.

    Precondition: n is a power of two. It has 2n - 1 rows and each cell lies
    in log2(n) + 1 of them, so its sensitivity is log2(n) + 1.
    """
    if n < 1 or n & (n - 1):
        raise ValueError("n must be a power of two")
    rows = []
    size = 1
    while size <= n:
        for start in range(0, n, size):
            rows.append([1 if start <= k < start + size else 0 for k in range(n)])
        size *= 2
    return rows
test_matrix_mechanism.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/matrix-mechanism/. The authors are listed in prov/73DA32.jsonl.

import math
import random
from fractions import Fraction

import dpkit
from matrix_mechanism import (
    all_range_queries,
    hierarchical_strategy,
    identity,
    inverse,
    laplace_noise,
    matmul,
    matrix_mechanism,
    matvec,
    pseudoinverse,
    sensitivity,
    total_squared_error,
    transpose,
)


def _random_full_rank(rng: random.Random, p: int, n: int) -> list:
    while True:
        A = [[rng.randrange(-2, 3) for _ in range(n)] for _ in range(p)]
        try:
            inverse(matmul(transpose(A), A))
            return A
        except ValueError:
            continue


def test_pseudoinverse_meets_penrose_conditions_exactly() -> None:
    # The oracle is the four Penrose equations, checked in exact arithmetic.
    rng = random.Random(1)
    for _ in range(500):
        n = rng.randrange(1, 4)
        p = rng.randrange(n, n + 3)
        A = _random_full_rank(rng, p, n)
        P = pseudoinverse(A)
        assert matmul(matmul(A, P), A) == [[Fraction(v) for v in row] for row in A]
        assert matmul(matmul(P, A), P) == P
        AP = matmul(A, P)
        assert AP == transpose(AP)
        PA = matmul(P, A)
        assert PA == [[1 if i == j else 0 for j in range(n)] for i in range(n)]
        # Least squares: the residual of A^+ y is orthogonal to the columns of A.
        y = [rng.randrange(-5, 6) for _ in range(p)]
        r = [a - b for a, b in zip(matvec(A, matvec(P, y)), y)]
        assert matvec(transpose(A), r) == [0] * n


def test_noise_free_answers_are_exact() -> None:
    rng = random.Random(2)
    for _ in range(200):
        n = rng.randrange(1, 4)
        A = _random_full_rank(rng, rng.randrange(n, n + 3), n)
        W = [[rng.randrange(0, 2) for _ in range(n)] for _ in range(rng.randrange(1, 5))]
        x = [rng.randrange(0, 10) for _ in range(n)]
        assert matvec(W, matvec(pseudoinverse(A), matvec(A, x))) == matvec(W, x)


def test_rank_deficient_strategy_is_rejected() -> None:
    try:
        pseudoinverse([[1, 1], [2, 2]])
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")


def test_sensitivity_is_the_largest_change_over_all_neighbors() -> None:
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randrange(1, 5)
        A = [[rng.randrange(-3, 4) for _ in range(n)] for _ in range(rng.randrange(1, 6))]
        x = [rng.randrange(0, 5) for _ in range(n)]
        worst = 0
        for j in range(n):
            for sign in (1, -1):
                x2 = list(x)
                x2[j] += sign
                worst = max(worst, sum(abs(a - b) for a, b in zip(matvec(A, x), matvec(A, x2))))
        assert worst == sensitivity(A)
    assert sensitivity(hierarchical_strategy(8)) == 4


def _logpdf(point, centers, b):
    return sum(-abs(z - c) / b - math.log(2 * b) for z, c in zip(point, centers))


def test_noisy_strategy_answers_are_epsilon_dp() -> None:
    rng = random.Random(4)
    A, epsilon = hierarchical_strategy(4), 0.5
    b = sensitivity(A) / epsilon
    for _ in range(40):
        x = [rng.randrange(0, 6) for _ in range(4)]
        j = rng.randrange(4)
        x2 = list(x)
        x2[j] += 1
        cx, cy = matvec(A, x), matvec(A, x2)
        base = [rng.uniform(-10, 20) for _ in cx]
        d = [rng.uniform(-1, 1) for _ in cx]
        grid = [k / 4 for k in range(-300, 301)]
        f = lambda z, c: _logpdf([p + z * e for p, e in zip(base, d)], c, b)
        assert dpkit.log_ratio_grid(lambda z: f(z, cx), lambda z: f(z, cy), grid) <= epsilon + 1e-9
    # Tight: far below all centers, the three rows that hold cell 0 each move the ratio by 1/b.
    far = [-100.0] * 7
    x = [1, 1, 1, 1]
    assert math.isclose(_logpdf(far, matvec(A, [0, 1, 1, 1]), b) - _logpdf(far, matvec(A, x), b), epsilon)


def test_example_errors() -> None:
    W = all_range_queries(4)
    assert total_squared_error(W, identity(4), 1) == 40
    assert total_squared_error(W, hierarchical_strategy(4), 1) == Fraction(876, 7)
    assert total_squared_error(W, W, 1) == 288  # answering the workload itself
    for n in (2, 4, 8):
        # The identity strategy has total error 2 * (sum of range lengths) = n(n+1)(n+2)/3.
        assert total_squared_error(all_range_queries(n), identity(n), 1) == n * (n + 1) * (n + 2) // 3


def test_monte_carlo_error_and_bias_match_formula() -> None:
    rng = random.Random(5)
    W, x, epsilon, runs = all_range_queries(4), [3, 0, 5, 2], 1.0, 1500
    true = matvec(W, x)
    for A in (identity(4), hierarchical_strategy(4)):
        want = float(total_squared_error(W, A, epsilon))
        sq, mean = 0.0, [0.0] * len(W)
        for _ in range(runs):
            out = matrix_mechanism(W, A, x, epsilon, rng)
            sq += sum((o - t) ** 2 for o, t in zip(out, true))
            mean = [m + o / runs for m, o in zip(mean, out)]
        assert abs(sq / runs - want) <= 0.15 * want
        # Unbiased: each mean is within 6 standard errors of the true answer.
        assert all(abs(m - t) <= 6 * math.sqrt(want / runs) for m, t in zip(mean, true))


def test_laplace_tail_check_value() -> None:
    rng = random.Random(6)
    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_bad_parameters() -> None:
    rng = random.Random(7)
    try:
        matrix_mechanism(identity(2), identity(2), [1, 1], 0.0, rng)
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")
    try:
        hierarchical_strategy(6)
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")

History

In 2010 two groups gave strategies for range queries that beat noise on each cell: Hay, Rastogi, Miklau and Suciu with a hierarchy of intervals and a least squares step, and Xiao, Wang and Gehrke with wavelets. Li, Hay, Rastogi, Miklau and McGregor (PODS 2010) showed that both are instances of one mechanism, gave its error formula, and studied the search for the best strategy. The journal version appeared in The VLDB Journal in 2015. HDMM (2018) made the strategy search practical for data with many attributes.

References

  1. Chao Li, Michael Hay, Vibhor Rastogi, Gerome Miklau and Andrew McGregor, Optimizing linear counting queries under differential privacy, PODS 2010, the definition of the matrix mechanism, its error formula, and the search for good strategies
  2. Chao Li, Gerome Miklau, Michael Hay, Andrew McGregor and Vibhor Rastogi, The matrix mechanism, optimizing linear counting queries under differential privacy, The VLDB Journal, 2015, the journal version, with the (epsilon, delta) form
  3. Michael Hay, Vibhor Rastogi, Gerome Miklau and Dan Suciu, Boosting the accuracy of differentially private histograms through consistency, PVLDB 3(1), 2010, the hierarchical strategy for range queries and the least squares step
  4. Xiaokui Xiao, Guozhang Wang and Johannes Gehrke, Differential privacy via wavelet transforms, ICDE 2010, the wavelet strategy for range queries
  5. Ryan McKenna, Gerome Miklau, Michael Hay and Ashwin Machanavajjhala, Optimizing error of high-dimensional statistical queries under differential privacy, PVLDB 2018, HDMM, the search for strategies over data with many attributes
  6. 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