Algorithm Search⌘K

Algorithmcore

Output perturbation

Also called sensitivity-based model perturbation.

Trains a model by regularized empirical risk minimization and adds noise scaled to the sensitivity of the minimizer.

Time
O(K n d) worst
Space
O(d) extra
Where
K = the number of solver iterations; d = the dimension; n = the number of examples
Properties
randomizedrandomized
Origin
Kamalika Chaudhuri, Claire Monteleoni, Anand D. Sarwate, 2008

Output perturbation trains a model in the normal way and then adds random noise to the trained parameters. The training is regularized empirical risk minimization: minimize the average loss plus (Λ/2)∥f∥2(\Lambda/2)\|f\|^2. The regularizer makes the minimizer stable, so that it moves by at most 2/(nΛ)2/(n\Lambda) when one of the nn examples changes. Noise scaled to that sensitivity then makes the released model ε\varepsilon-differentially private. Chaudhuri and Monteleoni (2008) used it for logistic regression, and Chaudhuri, Monteleoni and Sarwate (2011) stated it for strongly convex losses as their Algorithm 1. It is the simplest private learner for convex models, and the baseline that objective perturbation improves on.

In plain words

Train the model on the private data as usual, but with a penalty on large weights. That penalty has a side effect: changing one example can move the trained weights only a little, and we can compute how much at most.

So add random noise to the weights, large enough to cover that small move. An observer who sees the noisy weights cannot tell whether any one example was in the data.

More data or a larger penalty makes the possible move smaller, and so the noise smaller. With few examples the noise can be larger than the weights.

The problem

The data is D=((x1,y1),…,(xn,yn))D = ((x_1, y_1), \ldots, (x_n, y_n)) with xi∈Rdx_i \in \mathbb R^d, ∥xi∥≤1\|x_i\| \le 1 and yi∈{−1,+1}y_i \in \{-1, +1\}. The neighbor relation is replace: D′D' is DD with one example changed to another, and nn is public. The loss is ℓ(yfTx)\ell(y f^{\mathsf T} x) for a convex differentiable ℓ\ell with ∣ℓ′∣≤1|\ell'| \le 1; the code uses the logistic loss ℓ(z)=ln⁡(1+e−z)\ell(z) = \ln(1 + e^{-z}). The goal is an ε\varepsilon-DP vector ff with a small regularized risk

JD(f)=1n∑i=1nℓ(yifTxi)+Λ2∥f∥2.J_D(f) = \frac1n \sum_{i=1}^n \ell(y_i f^{\mathsf T} x_i) + \frac{\Lambda}{2}\|f\|^2.

The algorithm

  1. OUTPUT-PERTURBATION(D, Lambda, epsilon)
  2. 1f* <- argmin over f of J_D(f) ▷ exact minimizer, unique since J_D is strongly convex
  3. 2beta <- n Lambda epsilon / 2 ▷ 2/(n Lambda) is the L2 sensitivity of f*
  4. 3b <- a vector with density proportional to exp(-beta |b|)
  5. 4return f* + b

Line L1 is the non-private training. The code runs gradient descent with the step 1/(1/4+Λ)1/(1/4 + \Lambda), since the logistic risk is (1/4+Λ)(1/4 + \Lambda)-smooth, and stops when the gradient norm is at most 10−1110^{-11}. Line L2 sets the rate of the noise from the sensitivity bound 2/(nΛ)2/(n\Lambda) of Lemma 7 and Corollary 8 of Chaudhuri, Monteleoni and Sarwate. Line L3 draws the noise in two parts: the norm ∥b∥\|b\| is a sum of dd independent exponential draws of rate β\beta, which is the Gamma law of shape dd, and the direction is a Gaussian vector divided by its norm. In one dimension this is the Laplace mechanism with scale 1/β1/\beta. In dd dimensions it is not the same as Laplace noise in each coordinate: the noise is a function of the L2 norm, to match the L2 sensitivity. Line L4 releases the noisy model. Any use of it afterwards is private by post-processing.

The code uses floats and a seeded generator, which shows the algorithm but is not a safe deployment. The analysis assumes exact real noise, and floating-point samplers can leak (Mironov 2012). A deployment needs a cryptographic source of randomness and a sampler built for DP, such as the discrete Gaussian for the Gaussian variant.

Example

Take n=4n = 4 examples in the plane, Λ=0.5\Lambda = 0.5 and ε=1\varepsilon = 1.

ii xix_i yiy_i
1 (0.6, 0.8) +1
2 (1, 0) +1
3 (-0.6, 0) -1
4 (0, -1) -1

Line L1 gives f∗=(0.4368,0.3532)f^* = (0.4368, 0.3532), with JD(f∗)=0.5935J_D(f^*) = 0.5935. Replace example 4 by ((0,1),−1)((0, 1), -1): the minimizer becomes (0.4568,−0.0642)(0.4568, -0.0642), at distance 0.41780.4178 from f∗f^*, below the bound 2/(nΛ)=12/(n\Lambda) = 1. Line L2 gives β=4⋅0.5⋅1/2=1\beta = 4 \cdot 0.5 \cdot 1/2 = 1. With the seed 9 the code draws b=(0.7019,0.8327)b = (0.7019, 0.8327), of norm 1.08911.0891, and returns (1.1387,1.1859)(1.1387, 1.1859).

The noise here is larger than the model, whose norm is 0.56180.5618. The table shows how the noise shrinks with nn for Λ=0.5\Lambda = 0.5, ε=1\varepsilon = 1 and d=2d = 2; the mean norm of bb is d/βd/\beta.

nn sensitivity 2/(nΛ)2/(n\Lambda) β\beta mean ∥b∥\lVert b \rVert
4 1 1 2
100 0.04 25 0.08
1000 0.004 250 0.008
10000 0.0004 2500 0.0008

Correctness

Lemma (sensitivity). For replace neighbors, ∥fD∗−fD′∗∥≤2/(nΛ)\|f^*_D - f^*_{D'}\| \le 2/(n\Lambda). The proof uses only the Λ\Lambda-strong convexity of JDJ_D and the bound ∥∇fℓ(yfTx)∥≤1\|\nabla_f \ell(y f^{\mathsf T} x)\| \le 1.

Theorem (privacy). The output of line L4 is ε\varepsilon-DP under replace. The output density on DD is ν(z−fD∗)\nu(z - f^*_D) with ν(b)∝e−β∥b∥\nu(b) \propto e^{-\beta\|b\|}, and the triangle inequality bounds the log ratio of the two densities by β∥fD∗−fD′∗∥≤ε\beta\|f^*_D - f^*_{D'}\| \le \varepsilon.

An inexact solver. If line L1 returns a point within τ\tau of the minimizer for every input, the same proof gives ε(1+nΛτ)\varepsilon(1 + n\Lambda\tau). The stopping rule of the code gives τ=10−11/Λ\tau = 10^{-11}/\Lambda. A solver that stops after a fixed number of steps with no such bound gives no proved guarantee.

The correctness proof of this page proves all three claims. The tests check the minimizer against bisection in one dimension, the sensitivity bound on 500 random replace pairs, the log density ratio on a grid, and the law of the noise norm.

Proof: Output perturbation of regularized ERM is epsilon-DPfull

The data is D=((x1,y1),…,(xn,yn))D = ((x_1, y_1), \ldots, (x_n, y_n)) with ∥xi∥≤1\|x_i\| \le 1 and yi∈{−1,+1}y_i \in \{-1, +1\}. The neighbor relation is replace: D′D' differs from DD in one example. The loss ℓ:R→R\ell : \mathbb R \to \mathbb R is convex and differentiable with ∣ℓ′(z)∣≤1|\ell'(z)| \le 1 for all zz; the logistic loss ℓ(z)=ln⁡(1+e−z)\ell(z) = \ln(1 + e^{-z}) has ℓ′(z)=−1/(1+ez)∈(−1,0)\ell'(z) = -1/(1 + e^{z}) \in (-1, 0). Let

JD(f)=1n∑i=1nℓ(yifTxi)+Λ2∥f∥2,Λ>0,J_D(f) = \frac1n \sum_{i=1}^n \ell(y_i f^{\mathsf T} x_i) + \frac{\Lambda}{2}\|f\|^2, \qquad \Lambda > 0,

and fD=arg⁡min⁡fJD(f)f_D = \arg\min_f J_D(f) (line L1). JDJ_D is Λ\Lambda-strongly convex, so fDf_D exists and is unique.

Lemma 1 (sensitivity; Chaudhuri, Monteleoni and Sarwate, Corollary 8). For replace neighbors D,D′D, D', ∥fD−fD′∥≤2/(nΛ)\|f_D - f_{D'}\| \le 2/(n\Lambda).

Proof. Say D′D' replaces example nn by (x′,y′)(x', y'). Write h(f)=ℓ(y′fTx′)−ℓ(ynfTxn)h(f) = \ell(y' f^{\mathsf T} x') - \ell(y_n f^{\mathsf T} x_n), so JD′=JD+h/nJ_{D'} = J_D + h/n. The gradient of f↦ℓ(yfTx)f \mapsto \ell(y f^{\mathsf T} x) is y ℓ′(yfTx) xy\,\ell'(y f^{\mathsf T} x)\,x, of norm at most ∥x∥≤1\|x\| \le 1. So ∥∇h(f)∥≤2\|\nabla h(f)\| \le 2 for all ff.

Let f1=fDf_1 = f_D and f2=fD′f_2 = f_{D'}. Then ∇JD(f1)=0\nabla J_D(f_1) = 0 and ∇JD(f2)=∇JD′(f2)−∇h(f2)/n=−∇h(f2)/n\nabla J_D(f_2) = \nabla J_{D'}(f_2) - \nabla h(f_2)/n = -\nabla h(f_2)/n. A Λ\Lambda-strongly convex differentiable function satisfies (∇JD(f2)−∇JD(f1))T(f2−f1)≥Λ∥f2−f1∥2(\nabla J_D(f_2) - \nabla J_D(f_1))^{\mathsf T}(f_2 - f_1) \ge \Lambda\|f_2 - f_1\|^2. With the Cauchy-Schwarz inequality,

Λ∥f2−f1∥2≤1n∥∇h(f2)∥ ∥f2−f1∥≤2n∥f2−f1∥,\Lambda\|f_2 - f_1\|^2 \le \frac{1}{n}\|\nabla h(f_2)\|\,\|f_2 - f_1\| \le \frac{2}{n}\|f_2 - f_1\|,

which gives the claim (it is trivial when f1=f2f_1 = f_2). □\square

Lemma 2 (the noise). Let β>0\beta > 0. If rr is a sum of dd independent Exp(β)\mathrm{Exp}(\beta) variables and uu is an independent uniform unit vector in Rd\mathbb R^d, then b=rub = r u has the density ν(b)=exp⁡(−β∥b∥)/Z\nu(b) = \exp(-\beta\|b\|)/Z with Z=2πd/2Γ(d)/(Γ(d/2)βd)Z = 2\pi^{d/2}\Gamma(d)/(\Gamma(d/2)\beta^d). A Gaussian vector divided by its norm is a uniform unit vector.

Proof. A sum of dd independent Exp(β)\mathrm{Exp}(\beta) variables has the Gamma density βdrd−1e−βr/Γ(d)\beta^d r^{d-1} e^{-\beta r}/\Gamma(d) on r>0r > 0. In polar coordinates, the density ν\nu is a function of ∥b∥\|b\| only, so its direction is uniform and independent of the norm, and the norm has the density ∝rd−1e−βr\propto r^{d-1} e^{-\beta r}, since the sphere of radius rr has area rd−1⋅2πd/2/Γ(d/2)r^{d-1} \cdot 2\pi^{d/2}/\Gamma(d/2). The two laws match. Integrating e−βre^{-\beta r} against this area gives ZZ. The standard Gaussian density on Rd\mathbb R^d depends only on the norm, so the direction of a Gaussian vector is uniform. □\square

Theorem 1 (privacy). With β=nΛε/2\beta = n\Lambda\varepsilon/2 (line L2), the output fD+bf_D + b (lines L3 and L4) is ε\varepsilon-DP under replace.

Proof. By Lemma 2 the output has the density ν(z−fD)\nu(z - f_D) on DD and ν(z−fD′)\nu(z - f_{D'}) on D′D'. For every zz, by the triangle inequality and Lemma 1,

ν(z−fD)ν(z−fD′)=exp⁡(β(∥z−fD′∥−∥z−fD∥))≤exp⁡(β∥fD−fD′∥)≤exp⁡ ⁣(nΛε2⋅2nΛ)=eε.\frac{\nu(z - f_D)}{\nu(z - f_{D'})} = \exp\big(\beta(\|z - f_{D'}\| - \|z - f_D\|)\big) \le \exp(\beta\|f_D - f_{D'}\|) \le \exp\!\left(\frac{n\Lambda\varepsilon}{2}\cdot\frac{2}{n\Lambda}\right) = e^{\varepsilon}.

Integrating over an event SS gives Pr⁡[fD+b∈S]≤eεPr⁡[fD′+b∈S]\Pr[f_D + b \in S] \le e^{\varepsilon}\Pr[f_{D'} + b \in S]. □\square

Theorem 2 (an approximate minimizer). Suppose line L1 is a deterministic solver whose output f^D\hat f_D satisfies ∥f^D−fD∥≤τ\|\hat f_D - f_D\| \le \tau for every DD. Then the mechanism with f^D\hat f_D in place of fDf_D is ε(1+nΛτ)\varepsilon(1 + n\Lambda\tau)-DP. The gradient descent of the code stops at ∥∇JD(f^D)∥≤t\|\nabla J_D(\hat f_D)\| \le t, which gives τ=t/Λ\tau = t/\Lambda.

Proof. The triangle inequality gives ∥f^D−f^D′∥≤2/(nΛ)+2τ\|\hat f_D - \hat f_{D'}\| \le 2/(n\Lambda) + 2\tau, and the proof of Theorem 1 then gives β(2/(nΛ)+2τ)=ε+nΛετ\beta(2/(n\Lambda) + 2\tau) = \varepsilon + n\Lambda\varepsilon\tau. For the stopping rule, strong convexity gives Λ∥f^D−fD∥2≤(∇JD(f^D)−∇JD(fD))T(f^D−fD)≤t∥f^D−fD∥\Lambda\|\hat f_D - f_D\|^2 \le (\nabla J_D(\hat f_D) - \nabla J_D(f_D))^{\mathsf T}(\hat f_D - f_D) \le t\|\hat f_D - f_D\|. □\square

Theorem 3 (the size of the noise). E∥b∥=d/β=2d/(nΛε)\mathbb E\|b\| = d/\beta = 2d/(n\Lambda\varepsilon).

Proof. By Lemma 2, ∥b∥\|b\| is a sum of dd variables of mean 1/β1/\beta. □\square

Theorem 1 is the privacy claim of the page. Theorem 2 shows that the claim survives an inexact solver only with a larger ε\varepsilon, and Theorem 3 gives the cost in accuracy. The code samples from floats, so it follows the analysis only up to floating-point effects; that is a limit of the code, not of the theorem. ■\blacksquare

Complexity

The model is the real RAM, with one exponential or Gaussian draw counted as O(1)O(1).

  • Training. One gradient costs O(nd)O(nd). Gradient descent on a Λ\Lambda-strongly convex and (1/4+Λ)(1/4 + \Lambda)-smooth risk needs K=O((1+1/(4Λ))ln⁡(1/t))K = O((1 + 1/(4\Lambda)) \ln(1/t)) steps to reach the gradient norm tt, so line L1 costs O(Knd)O(Knd).
  • Noise. Line L3 costs O(d)O(d) draws, and line L4 costs O(d)O(d).
  • Space. The extra space is O(d)O(d) beyond the data.

The private part adds almost nothing to the cost of training.

Properties

  • A black box. Any solver can be used for line L1, as long as it returns the exact minimizer or a point with a known distance bound. The private step only touches the output.
  • Pure DP. The guarantee is ε\varepsilon-DP with δ=0\delta = 0, under replace neighbors.
  • Needs strong convexity. Without the regularizer, the minimizer can jump far when one example changes, and the sensitivity has no bound. The noise grows like 1/Λ1/\Lambda, so a small Λ\Lambda costs accuracy through the noise and a large Λ\Lambda costs accuracy through the bias.
  • Noise of order d/(nΛε)d/(n\Lambda\varepsilon). The expected norm of bb is 2d/(nΛε)2d/(n\Lambda\varepsilon). Chaudhuri, Monteleoni and Sarwate prove learning bounds for it and show that objective perturbation needs fewer examples for the same accuracy in their bounds and experiments.
  • The hypotheses matter. The bound 2/(nΛ)2/(n\Lambda) needs ∥xi∥≤1\|x_i\| \le 1 and ∣ℓ′∣≤1|\ell'| \le 1. The squared loss has no such bound on ℓ′\ell', so linear regression needs bounded labels and a bounded domain for ff before the method applies.

Variants and improvements

  • Gaussian noise. With b∼N(0,σ2I)b \sim \mathcal N(0, \sigma^2 I) and σ=(2/(nΛ))2ln⁡(1.25/δ)/ε\sigma = (2/(n\Lambda))\sqrt{2\ln(1.25/\delta)}/\varepsilon for ε<1\varepsilon < 1, the Gaussian mechanism gives (ε,δ)(\varepsilon, \delta)-DP. Its noise norm grows like d\sqrt d, not dd.
  • Objective perturbation. Put the noise into the objective before minimizing it, not into the minimizer. It needs a twice differentiable loss and usually gives better accuracy.
  • Output perturbation of SGD. For a fixed number of passes of SGD on a strongly convex loss, the sensitivity of the final iterate can be bounded directly, and the same noise applies. Wu et al. (SIGMOD 2017) built a system on this idea.
  • Other models. The same step applies to any statistic with a known sensitivity, for example a private mean. When the sensitivity is not known in advance, subsample and aggregate gives a bound by design.
  • Noisy training. DP-SGD adds noise during training, so it does not need convexity or an exact minimizer.

When to use it

Use output perturbation for a convex model with a strongly convex regularizer, such as L2L_2-regularized logistic regression or a support vector machine with a smooth loss, when the training code must stay as it is. It is simple to audit: the only private step is one line of noise. When accuracy matters more, try objective perturbation first. For non-convex models it does not apply, and DP-SGD is the usual choice.

Pitfalls

  • Noise per coordinate. Line L3 with independent Laplace noise of scale 2/(nΛε)2/(n\Lambda\varepsilon) in each coordinate is calibrated to the L1 sensitivity, which can be d\sqrt d times the L2 bound, so it does not give ε\varepsilon-DP for d>1d > 1. Line L3 must draw the norm from the Gamma law and a uniform direction, or use the L1 sensitivity 2d/(nΛ)2\sqrt d/(n\Lambda).
  • A stopped solver. Line L1 run for a fixed number of steps with no bound on the distance to the minimizer breaks the sensitivity bound. Line L1 must stop at a known gradient norm tt, and line L2 must then use ε/(1+nt)\varepsilon/(1 + nt) in place of ε\varepsilon to keep the total at ε\varepsilon.
  • Features out of the ball. Line L1 run on data with ∥xi∥>1\|x_i\| > 1 breaks the bound 2/(nΛ)2/(n\Lambda) of line L2. Scale or clip each xix_i to the unit ball with a rule that does not depend on the data, before line L1.
  • A data-dependent Λ\Lambda. Line L2 with Λ\Lambda picked by cross-validation on the private data leaks through the choice. Line L2 must use a Λ\Lambda fixed in advance, or the tuning must be private and counted in the budget.
  • Add/remove neighbors. Line L2 assumes replace neighbors with a public nn. Under add/remove the size changes, and the bound must be recomputed for that relation.

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
output_perturbation.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/output-perturbation/. The authors are listed in prov/DE6SYB.jsonl.
"""Output perturbation for regularized logistic regression (Chaudhuri, Monteleoni and Sarwate, Algorithm 1).

The regularized empirical risk is

    J(f, D) = (1/n) sum_i ln(1 + exp(-y_i f.x_i)) + (Lambda/2) |f|^2,

with |x_i| <= 1 and y_i in {-1, +1}. Its minimizer moves by at most 2/(n Lambda)
in L2 norm when one example is replaced. The algorithm releases the minimizer
plus a noise vector b with density proportional to exp(-beta |b|), with
beta = n Lambda epsilon / 2, which is epsilon-DP under replace neighbors.

The minimizer is found by gradient descent with the step 1/(1/4 + Lambda), so
it is exact only up to the tolerance. Floats and random.Random are used for
the noise, so this code shows the algorithm and is not a safe deployment.
"""

from __future__ import annotations

import math
import random
from typing import Sequence

Vector = list[float]
Example = tuple[Sequence[float], int]


def dot(a: Sequence[float], b: Sequence[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


def norm(a: Sequence[float]) -> float:
    return math.sqrt(dot(a, a))


def _sigmoid(z: float) -> float:
    if z >= 0:
        return 1 / (1 + math.exp(-z))
    e = math.exp(z)
    return e / (1 + e)


def risk(f: Sequence[float], data: Sequence[Example], lam: float) -> float:
    """J(f, D): the mean logistic loss plus (lam/2) |f|^2."""
    total = 0.0
    for x, y in data:
        z = -y * dot(f, x)
        total += z + math.log1p(math.exp(-z)) if z > 0 else math.log1p(math.exp(z))
    return total / len(data) + lam / 2 * dot(f, f)


def risk_gradient(f: Sequence[float], data: Sequence[Example], lam: float) -> Vector:
    """The gradient of J: (1/n) sum_i -y_i x_i sigmoid(-y_i f.x_i) + lam f."""
    n = len(data)
    g = [lam * fi for fi in f]
    for x, y in data:
        s = _sigmoid(-y * dot(f, x))
        for j, xj in enumerate(x):
            g[j] -= y * xj * s / n
    return g


def minimize_risk(data: Sequence[Example], lam: float, tol: float = 1e-11, max_steps: int = 100000) -> Vector:
    """The minimizer of J by gradient descent with step 1/(1/4 + lam).

    J is lam-strongly convex and (1/4 + lam)-smooth when |x_i| <= 1, so the
    iteration converges linearly. It stops when |grad J| <= tol, which puts the
    iterate within tol/lam of the minimizer. Cost: O(n d) per iteration.
    """
    d = len(data[0][0])
    f = [0.0] * d
    step = 1 / (0.25 + lam)
    for _ in range(max_steps):
        g = risk_gradient(f, data, lam)
        if norm(g) <= tol:
            return f
        f = [fi - step * gi for fi, gi in zip(f, g)]
    return f


def sample_noise(d: int, beta: float, rng: random.Random) -> Vector:
    """A vector b in R^d with density proportional to exp(-beta |b|).

    The norm |b| has the Gamma(d, 1/beta) law, the sum of d Exp(beta) draws,
    and the direction is uniform on the sphere. Cost: O(d) draws.
    """
    r = sum(rng.expovariate(beta) for _ in range(d))
    while True:
        u = [rng.gauss(0.0, 1.0) for _ in range(d)]
        s = norm(u)
        if s > 0:
            return [r * ui / s for ui in u]


def output_perturbation(data: Sequence[Example], lam: float, epsilon: float, rng: random.Random) -> Vector:
    """An epsilon-DP model for regularized logistic regression (replace neighbors).

    Precondition: n >= 1, |x_i| <= 1, y_i in {-1, +1}, lam > 0, epsilon > 0.
    Cost: O(n d) per iteration of the minimizer plus O(d) for the noise.
    """
    if lam <= 0 or epsilon <= 0:
        raise ValueError("need lam > 0 and epsilon > 0")
    if any(norm(x) > 1 + 1e-12 or y not in (-1, 1) for x, y in data):
        raise ValueError("need |x| <= 1 and y in {-1, +1}")
    n = len(data)
    f_star = minimize_risk(data, lam)  # @line L1
    beta = n * lam * epsilon / 2  # @line L2
    b = sample_noise(len(f_star), beta, rng)  # @line L3
    return [fi + bi for fi, bi in zip(f_star, b)]  # @line L4


def sensitivity_bound(n: int, lam: float) -> float:
    """2 / (n lam), the L2 sensitivity of the minimizer under replace (CMS Corollary 8)."""
    return 2 / (n * lam)


def output_log_density(z: Sequence[float], center: Sequence[float], beta: float) -> float:
    """The log density of the output at z, given the minimizer center; the normalizer is included."""
    d = len(z)
    # The normalizer of exp(-beta |b|) in R^d is 2 pi^(d/2) Gamma(d) / (Gamma(d/2) beta^d).
    log_norm = math.log(2) + d / 2 * math.log(math.pi) + math.lgamma(d) - math.lgamma(d / 2) - d * math.log(beta)
    return -beta * norm([a - b for a, b in zip(z, center)]) - log_norm
test_output_perturbation.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/output-perturbation/. The authors are listed in prov/DE6SYB.jsonl.

import math
import random

import pytest

import dpkit
from output_perturbation import (
    minimize_risk,
    norm,
    output_log_density,
    output_perturbation,
    risk,
    risk_gradient,
    sample_noise,
    sensitivity_bound,
)


def random_point(d, rng):
    """A point of the unit ball."""
    while True:
        x = [rng.uniform(-1, 1) for _ in range(d)]
        if norm(x) <= 1:
            return x


def random_data(n, d, rng):
    return [(random_point(d, rng), rng.choice((-1, 1))) for _ in range(n)]


EXAMPLE = [((0.6, 0.8), 1), ((1.0, 0.0), 1), ((-0.6, 0.0), -1), ((0.0, -1.0), -1)]


def test_check_values():
    f = minimize_risk(EXAMPLE, 0.5)
    assert abs(f[0] - 0.4368) < 1e-4 and abs(f[1] - 0.3532) < 1e-4
    other = EXAMPLE[:3] + [((0.0, 1.0), -1)]
    g = minimize_risk(other, 0.5)
    assert abs(g[0] - 0.4568) < 1e-4 and abs(g[1] + 0.0642) < 1e-4
    assert abs(norm([a - b for a, b in zip(f, g)]) - 0.4178) < 1e-4
    assert sensitivity_bound(4, 0.5) == 1.0
    assert sensitivity_bound(100, 0.1) == pytest.approx(0.2)


def test_bad_input():
    with pytest.raises(ValueError):
        output_perturbation(EXAMPLE, 0.0, 1.0, random.Random(0))
    with pytest.raises(ValueError):
        output_perturbation([((2.0, 0.0), 1)], 0.5, 1.0, random.Random(0))


def bisect_1d(data, lam):
    """Independent oracle in one dimension: the zero of the increasing derivative of J, by bisection."""
    lo, hi = -10.0, 10.0
    for _ in range(200):
        mid = (lo + hi) / 2
        if risk_gradient([mid], data, lam)[0] > 0:
            hi = mid
        else:
            lo = mid
    return (lo + hi) / 2


def test_minimizer_against_bisection():
    rng = random.Random(1)
    for _ in range(500):
        n = rng.randint(1, 8)
        lam = rng.uniform(0.2, 1.0)
        data = random_data(n, 1, rng)
        assert abs(minimize_risk(data, lam)[0] - bisect_1d(data, lam)) < 1e-9


def test_sensitivity_bound_on_random_replace_pairs():
    rng = random.Random(2)
    worst = 0.0
    for _ in range(500):
        n = rng.randint(1, 8)
        d = rng.randint(1, 2)
        lam = rng.uniform(0.2, 1.0)
        data = random_data(n, d, rng)
        other = list(data)
        other[rng.randrange(n)] = (random_point(d, rng), rng.choice((-1, 1)))
        f1 = minimize_risk(data, lam)
        f2 = minimize_risk(other, lam)
        gap = norm([a - b for a, b in zip(f1, f2)])
        assert gap <= sensitivity_bound(n, lam) + 1e-9
        worst = max(worst, gap * n * lam / 2)
    assert worst > 0.3


def test_minimizer_is_stationary_and_minimal():
    rng = random.Random(3)
    data = random_data(10, 3, rng)
    f = minimize_risk(data, 0.3)
    assert norm(risk_gradient(f, data, 0.3)) < 1e-10
    for _ in range(50):
        g = [fi + rng.uniform(-0.1, 0.1) for fi in f]
        assert risk(g, data, 0.3) >= risk(f, data, 0.3)


def test_output_density_ratio_is_at_most_epsilon():
    rng = random.Random(4)
    for _ in range(20):
        n = rng.randint(2, 6)
        lam = rng.uniform(0.2, 1.0)
        eps = rng.uniform(0.2, 2.0)
        data = random_data(n, 2, rng)
        other = list(data)
        other[0] = (random_point(2, rng), -other[0][1])
        f1, f2 = minimize_risk(data, lam), minimize_risk(other, lam)
        beta = n * lam * eps / 2
        grid = [(i / 4, j / 4) for i in range(-24, 25) for j in range(-24, 25)]
        loss = dpkit.log_ratio_grid(
            lambda z: output_log_density(z, f1, beta),
            lambda z: output_log_density(z, f2, beta),
            grid,
        )
        assert loss <= eps + 1e-9
        assert loss <= beta * norm([a - b for a, b in zip(f1, f2)]) + 1e-9


def gamma_cdf_integer_shape(t, d, beta):
    s = sum((beta * t) ** k / math.factorial(k) for k in range(d))
    return 1 - math.exp(-beta * t) * s


def test_noise_norm_and_direction():
    rng = random.Random(5)
    n = 2000
    d, beta = 3, 2.0
    samples = [sample_noise(d, beta, rng) for _ in range(n)]
    margin = dpkit.hoeffding_margin(n, 1e-6)
    for t in (0.5, 1.0, 1.5, 2.5):
        emp = sum(1 for b in samples if norm(b) <= t) / n
        assert abs(emp - gamma_cdf_integer_shape(t, d, beta)) <= margin
    for j in range(d):
        emp = sum(1 for b in samples if b[j] > 0) / n
        assert abs(emp - 0.5) <= margin


def test_private_model_runs_and_is_reproducible():
    a = output_perturbation(EXAMPLE, 0.5, 1.0, random.Random(9))
    b = output_perturbation(EXAMPLE, 0.5, 1.0, random.Random(9))
    assert a == b and len(a) == 2

History

Dwork, McSherry, Nissim and Smith (TCC 2006) defined the sensitivity method: add noise scaled to how much one record can change the output. Chaudhuri and Monteleoni (NIPS 2008) applied it to regularized logistic regression, bounded the sensitivity of the minimizer, and proposed objective perturbation as a better method. Chaudhuri, Monteleoni and Sarwate (JMLR 2011) extended both methods to general strongly convex ERM and to kernels, proved generalization bounds, and compared the methods on real data.

References

  1. Kamalika Chaudhuri, Claire Monteleoni and Anand D. Sarwate, Differentially private empirical risk minimization, Journal of Machine Learning Research 12, 2011, pages 1069 to 1109, Algorithm 1 (Section 3.1), Theorem 6 (its privacy), Lemma 7 (the sensitivity of a strongly convex minimizer) and Corollary 8 (the bound 2/(n Lambda))
  2. Kamalika Chaudhuri and Claire Monteleoni, Privacy-preserving logistic regression, Advances in Neural Information Processing Systems 21 (NIPS 2008), the sensitivity method for regularized logistic regression and its comparison with objective perturbation
  3. Cynthia Dwork, Frank McSherry, Kobbi Nissim and Adam Smith, Calibrating noise to sensitivity in private data analysis, TCC 2006, adding noise scaled to the sensitivity of a function

Where this leads

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