Algorithm Search⌘K

Algorithmadvanced

Differentially private stochastic gradient descent

Also called DP-SGD, noisy SGD with clipping.

Clips each example's gradient to a fixed norm, adds Gaussian noise to the sum of a random batch, and tracks the privacy cost of training.

Time
O(T n d) worst
Space
O(d) extra
Where
T = the number of steps; d = the number of parameters; n = the number of examples
Properties
randomizedrandomized
Origin
Martín Abadi, Andy Chu, Ian Goodfellow, H. Brendan McMahan, Ilya Mironov, Kunal Talwar, Li Zhang, 2016

Differentially private stochastic gradient descent (DP-SGD) trains a model so that the trained parameters are (ε,δ)(\varepsilon, \delta)-differentially private with respect to each training example. At each step it samples a random batch, computes the gradient of each example on its own, clips each gradient to a fixed norm CC, sums them, and adds Gaussian noise with standard deviation σC\sigma C. Clipping bounds the effect of one example, the noise hides it, and the random batch amplifies the privacy (privacy amplification by subsampling). An accountant then adds up the privacy cost of all steps. Abadi et al. (2016) introduced this form and the moments accountant, and trained deep networks with it. It is the standard method for private deep learning.

In plain words

Normal training looks at a batch of examples, finds the direction that improves the model on them, and takes a small step. One unusual example can pull the model far toward itself, and the model may then remember that example.

DP-SGD limits the pull of each example. It measures how hard each example pulls, and cuts every pull down to a fixed limit. Then it adds random noise to the total pull, large enough to hide any one example. The batch itself is picked at random, so an observer does not even know which examples took part in each step.

A privacy ledger counts how much each step leaks. More steps or less noise give a larger total leak.

The problem

The data is a multiset DD of nn examples, and ℓ(θ,x)\ell(\theta, x) is the loss of the model with parameters θ∈Rd\theta \in \mathbb R^d on example xx. The goal is a θ\theta with a small average loss, such that the whole sequence of parameters is (ε,δ)(\varepsilon, \delta)-DP. The neighbor relation is add/remove: D′D' is DD with one example added or removed. The loss may be non-convex, and it may have no bound on its gradient; clipping makes the bound.

The algorithm

The inputs are the rate q∈(0,1]q \in (0, 1], the noise multiplier σ>0\sigma > 0, the clipping norm C>0C > 0, the step size η\eta and the number of steps TT.

  1. DP-SGD(D, q, sigma, C, eta, T)
  2. 1theta <- theta_0
  3. 2for t = 1 to T do
  4. 3B <- each example of D, independently with probability q ▷ Poisson sampling
  5. 4for each x in B: g_x <- grad of loss(theta, x)
  6. 5clip: g_x <- g_x / max(1, |g_x| / C) ▷ now |g_x| <= C
  7. 6G <- (sum over x in B of g_x) + N(0, sigma^2 C^2 I)
  8. 7theta <- theta - eta G / (q n) ▷ q n is the expected batch size
  9. 8return theta

Line L3 draws the batch by Poisson sampling: each example joins with probability qq, on its own. The size of the batch is random, with mean qnqn. Line L4 computes one gradient per example, not one gradient of the batch. Line L5 scales each gradient down to the norm CC if it is longer. Line L6 sums the clipped gradients and adds Gaussian noise in every coordinate. Adding or removing one example changes the sum by a vector of norm at most CC, so this is the Gaussian mechanism with the sensitivity CC on a random sample. Line L7 takes a step with the noisy average. It divides by the fixed number qnqn, not by the size of the batch, which is private.

The accountant computes the privacy of the TT steps. For an integer order α≥2\alpha \ge 2, one step is (α,ρα)(\alpha, \rho_\alpha)-Renyi DP with

ρα=1α−1ln⁡∑k=0α(αk)(1−q)α−kqkexp⁡ ⁣(k2−k2σ2),\rho_\alpha = \frac{1}{\alpha - 1} \ln \sum_{k=0}^{\alpha} \binom{\alpha}{k} (1 - q)^{\alpha - k} q^k \exp\!\left(\frac{k^2 - k}{2\sigma^2}\right),

the bound of Mironov, Talwar and Zhang for the sampled Gaussian. TT steps give TραT\rho_\alpha. The result is (ε,δ)(\varepsilon, \delta)-DP with ε=min⁡α(Tρα+ln⁡(1/δ)/(α−1))\varepsilon = \min_\alpha \big(T\rho_\alpha + \ln(1/\delta)/(\alpha - 1)\big). The code computes the sum in log space and takes the minimum over the orders 2 to 256. Other accountants use the same steps with a sharper conversion; see numerical privacy accounting.

The code trains logistic regression so that it needs no library, and it uses floats and a seeded generator. That shows the algorithm but is not a safe deployment: the analysis assumes real-valued Gaussian noise and exact Poisson sampling, 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.

Example

One step. Take logistic regression in the plane with θ=(0,0)\theta = (0, 0), four examples, q=1/2q = 1/2, σ=1\sigma = 1, C=1C = 1 and η=0.5\eta = 0.5. At θ=0\theta = 0 the gradient of the logistic loss of (x,y)(x, y) is −yx/2-yx/2.

example xx, yy gxg_x (line L4) ∣gx∣\lvert g_x \rvert clipped (line L5) in BB (line L3)
1 (2, 1), +1 (-1, -0.5) 1.118 (-0.8944, -0.4472) yes
2 (0.5, -1), -1 (0.25, -0.5) 0.559 (0.25, -0.5) no
3 (-3, 0), -1 (-1.5, 0) 1.5 (-1, 0) yes
4 (1, 1), +1 (-0.5, -0.5) 0.7071 (-0.5, -0.5) yes

The sum over the batch is (−2.3944,−0.9472)(-2.3944, -0.9472). Suppose line L6 draws the noise (0.31,−1.20)(0.31, -1.20). Then G=(−2.0844,−2.1472)G = (-2.0844, -2.1472), and line L7 gives θ=−0.5⋅G/2=(0.5211,0.5368)\theta = -0.5 \cdot G / 2 = (0.5211, 0.5368). The noise is as large as the signal here; with thousands of examples per batch it is small against the sum.

The privacy of training. The accountant of the code gives these values for δ=10−5\delta = 10^{-5}.

qq σ\sigma TT ε\varepsilon best order α\alpha
1 2 1 2.5263 11
0.01 1.0 1000 2.5383 8
0.01 1.0 10000 7.4692 4
0.01 1.1 10000 6.2798 5
0.01 2 10000 2.7354 10
0.01 4 10000 1.2586 20

The last row is the example of Abadi et al.: they report ε≈1.26\varepsilon \approx 1.26 with the moments accountant, against about 9.34 with the strong composition theorem. The first row is the Gaussian mechanism with no sampling, where ρα=α/8\rho_\alpha = \alpha/8. The best real order gives 2.5243, so the integer orders lose very little.

Correctness

Theorem (privacy). For every integer α≥2\alpha \ge 2, each step is (α,ρα)(\alpha, \rho_\alpha)-RDP under add/remove, TT steps are (α,Tρα)(\alpha, T\rho_\alpha)-RDP, and the output is (ε,δ)(\varepsilon, \delta)-DP for the ε\varepsilon above.

The proof has three parts. First, clipping bounds the change of the sum by CC. Second, the joint convexity of ∫pαq1−α\int p^\alpha q^{1 - \alpha} reduces the sampled Gaussian in dd dimensions to the mixture (1−q)N(0,σ2)+qN(1,σ2)(1 - q)\mathcal N(0, \sigma^2) + q\mathcal N(1, \sigma^2) on the line, whose divergence the binomial sum computes exactly. Third, Renyi DP composes by adding, and Markov's inequality converts it. The direction from DD to D∪{x}D \cup \{x\} needs a further fact, that the other mixture divergence is smaller, which is Theorem 5 of Mironov, Talwar and Zhang. The correctness proof of this page proves every step except that one, which it quotes.

Theorem (Abadi et al., Theorem 1). There are constants c1,c2c_1, c_2 such that for ε<c1q2T\varepsilon < c_1 q^2 T, the noise σ≥c2 qTln⁡(1/δ)/ε\sigma \ge c_2\, q\sqrt{T \ln(1/\delta)}/\varepsilon gives (ε,δ)(\varepsilon, \delta)-DP. So ε\varepsilon grows like qTq\sqrt T, not like qTqT.

What is not proved. Nothing above says that the model is accurate. For convex losses, Bassily, Smith and Thakurta (2014) bound the excess risk of noisy SGD. For deep networks, the accuracy is measured. The clipping norm CC and the other settings are tuned, and their choice is a heuristic.

Proof: DP-SGD with Poisson sampling is (epsilon, delta)-DP with the epsilon of the Renyi accountantpartial

The neighbor relation is add/remove: D′=D∪{x}D' = D \cup \{x\} for one example xx. One step of DP-SGD (lines L3 to L7) maps the current parameter θ\theta to a new one. The released output is the sequence of parameters. Write s=σCs = \sigma C, Nμ=N(μ,s2I)\mathcal N_\mu = \mathcal N(\mu, s^2 I) in Rd\mathbb R^d, and, for α>1\alpha > 1, the Renyi divergence

Dα(P ∥ Q)=1α−1ln⁡∫p(z)αq(z)1−α dz.D_\alpha(P \,\|\, Q) = \frac{1}{\alpha - 1} \ln \int p(z)^\alpha q(z)^{1 - \alpha}\, dz.

A mechanism is (α,ρ)(\alpha, \rho)-RDP when Dα(M(D) ∥ M(D′))≤ρD_\alpha(M(D) \,\|\, M(D')) \le \rho for both orders of every pair of neighbors.

The proof is complete except for Lemma 4, which is quoted from Mironov, Talwar and Zhang (2019, Section 3.1, Theorem 5). The status is partial for that reason.

Lemma 1 (clipping). For every g∈Rdg \in \mathbb R^d, the vector gˉ=g/max⁡(1,∥g∥/C)\bar g = g/\max(1, \|g\|/C) of line L5 has ∥gˉ∥≤C\|\bar g\| \le C, and gˉ=g\bar g = g when ∥g∥≤C\|g\| \le C.

Proof. If ∥g∥≤C\|g\| \le C the divisor is 1. Otherwise the divisor is ∥g∥/C\|g\|/C and ∥gˉ∥=C\|\bar g\| = C. □\square

Lemma 2 (the Gaussian at a shift). For μ0=N(0,σ2)\mu_0 = \mathcal N(0, \sigma^2) and μ1=N(r,σ2)\mu_1 = \mathcal N(r, \sigma^2) on R\mathbb R and every integer k≥0k \ge 0, Ez∼μ0[(μ1(z)/μ0(z))k]=exp⁡(k(k−1)r2/(2σ2))\mathbb E_{z \sim \mu_0}[(\mu_1(z)/\mu_0(z))^k] = \exp\big(k(k - 1) r^2/(2\sigma^2)\big).

Proof. The ratio is exp⁡((2rz−r2)/(2σ2))\exp((2rz - r^2)/(2\sigma^2)). For z∼N(0,σ2)z \sim \mathcal N(0, \sigma^2), E[etz]=et2σ2/2\mathbb E[e^{tz}] = e^{t^2\sigma^2/2}. With t=kr/σ2t = kr/\sigma^2 this gives exp⁡(k2r2/(2σ2)−kr2/(2σ2))\exp(k^2 r^2/(2\sigma^2) - k r^2/(2\sigma^2)). □\square

Lemma 3 (one step, from D′D' to DD). Fix θ\theta and an integer α≥2\alpha \ge 2, and let PP and P′P' be the laws of the noisy sum GG of line L6 on DD and on D′D'. Then ∫p′αp1−α≤Aα\int p'^\alpha p^{1 - \alpha} \le A_\alpha, where

Aα=∑k=0α(αk)(1−q)α−kqkexp⁡ ⁣(k2−k2σ2).A_\alpha = \sum_{k=0}^{\alpha} \binom{\alpha}{k} (1 - q)^{\alpha - k} q^k \exp\!\left(\frac{k^2 - k}{2\sigma^2}\right).

Proof. Line L3 draws a Poisson sample. On D′D' it is a sample TT of DD, plus xx with probability qq, independently. Let STS_T be the sum of the clipped gradients of TT and vv the clipped gradient of xx, so ∥v∥≤C\|v\| \le C by Lemma 1. Then

P=ET[NST],P′=ET[(1−q)NST+q NST+v].P = \mathbb E_T\big[\mathcal N_{S_T}\big], \qquad P' = \mathbb E_T\big[(1 - q)\mathcal N_{S_T} + q\,\mathcal N_{S_T + v}\big].

The map (a,b)↦aαb1−α(a, b) \mapsto a^\alpha b^{1 - \alpha} on a≥0a \ge 0, b>0b > 0 is the perspective b ϕ(a/b)b\,\phi(a/b) of the convex function ϕ(u)=uα\phi(u) = u^\alpha, so it is jointly convex. By Jensen's inequality over TT, pointwise in zz, and then by Fubini,

∫p′αp1−α≤ET∫((1−q)NST+q NST+v)αNST1−α.\int p'^\alpha p^{1 - \alpha} \le \mathbb E_T \int \big((1 - q)\mathcal N_{S_T} + q\,\mathcal N_{S_T + v}\big)^\alpha \mathcal N_{S_T}^{1 - \alpha}.

Each inner integral does not change under the shift by −ST-S_T and under a rotation that maps vv to (∥v∥,0,…,0)(\|v\|, 0, \ldots, 0). After that, the coordinates other than the first have the same law under both terms and integrate to 1. Divide the first coordinate by CC; this changes the variance to σ2\sigma^2 and the shift to r=∥v∥/C≤1r = \|v\|/C \le 1, and it does not change the integral. Expanding the α\alpha-th power by the binomial theorem and using Lemma 2 gives

∑k=0α(αk)(1−q)α−kqkexp⁡ ⁣((k2−k)r22σ2)≤Aα,\sum_{k=0}^{\alpha} \binom{\alpha}{k}(1 - q)^{\alpha - k} q^k \exp\!\left(\frac{(k^2 - k) r^2}{2\sigma^2}\right) \le A_\alpha,

because k2−k≥0k^2 - k \ge 0 and r≤1r \le 1. □\square

Lemma 4 (the other order; Mironov, Talwar and Zhang, Theorem 5). With μ0=N(0,σ2)\mu_0 = \mathcal N(0, \sigma^2) and μ=(1−q)μ0+q N(r,σ2)\mu = (1 - q)\mu_0 + q\,\mathcal N(r, \sigma^2), Bα=Eμ[(μ0/μ)α]≤Aα=Eμ0[(μ/μ0)α]B_\alpha = \mathbb E_{\mu}[(\mu_0/\mu)^{\alpha}] \le A_\alpha = \mathbb E_{\mu_0}[(\mu/\mu_0)^{\alpha}] for every integer α≥2\alpha \ge 2.

The same convexity and reduction steps as in Lemma 3 bound ∫pαp′1−α\int p^\alpha p'^{1 - \alpha} by BαB_\alpha at a shift r=∥v∥/Cr = \|v\|/C. By Lemma 4, this is at most AαA_\alpha at the same rr, and the binomial form shows that AαA_\alpha grows with rr, so it is at most AαA_\alpha at r=1r = 1.

Theorem 1 (one step). For every integer α≥2\alpha \ge 2 and every fixed θ\theta, one step is (α,ρα)(\alpha, \rho_\alpha)-RDP with ρα=ln⁡(Aα)/(α−1)\rho_\alpha = \ln(A_\alpha)/(\alpha - 1), the value of rdp_sampled_gaussian. For q=1q = 1, ρα=α/(2σ2)\rho_\alpha = \alpha/(2\sigma^2).

Proof. Lemmas 3 and 4 bound both orders. Line L7 is a fixed function of GG and θ\theta, and the Renyi divergence does not grow under a fixed function (the data-processing inequality), so the bound holds for the new θ\theta. For q=1q = 1, only the term k=αk = \alpha is left, and it is exp⁡((α2−α)/(2σ2))\exp((\alpha^2 - \alpha)/(2\sigma^2)). □\square

Theorem 2 (T steps). The sequence θ1,…,θT\theta_1, \ldots, \theta_T is (α,Tρα)(\alpha, T\rho_\alpha)-RDP.

Proof. By induction on TT. Let YY be the first T−1T - 1 outputs and ZZ the last, with densities p(y)p(z∣y)p(y)p(z \mid y) on DD and p′(y)p′(z∣y)p'(y)p'(z \mid y) on D′D'. For each yy, Theorem 1 at θ=θT−1(y)\theta = \theta_{T-1}(y) gives ∫p(z∣y)αp′(z∣y)1−αdz≤e(α−1)ρα\int p(z \mid y)^\alpha p'(z \mid y)^{1 - \alpha} dz \le e^{(\alpha - 1)\rho_\alpha}. So

∫ ⁣ ⁣∫(p(y)p(z∣y))α(p′(y)p′(z∣y))1−α≤e(α−1)ρα∫p(y)αp′(y)1−α≤e(α−1)Tρα,\int\!\!\int (p(y)p(z \mid y))^\alpha (p'(y)p'(z \mid y))^{1 - \alpha} \le e^{(\alpha - 1)\rho_\alpha} \int p(y)^\alpha p'(y)^{1 - \alpha} \le e^{(\alpha - 1)T\rho_\alpha},

by the induction hypothesis. The other order is the same. □\square

Theorem 3 (conversion; Mironov 2017). If a mechanism is (α,ρ)(\alpha, \rho)-RDP, then for every δ∈(0,1)\delta \in (0, 1) it is (ρ+ln⁡(1/δ)/(α−1),δ)(\rho + \ln(1/\delta)/(\alpha - 1), \delta)-DP. So DP-SGD is (ε,δ)(\varepsilon, \delta)-DP under add/remove for the ε\varepsilon that epsilon_for returns, which is the smallest such value over the listed orders.

Proof. Let PP, QQ be the output laws on two neighbors, ε=ρ+ln⁡(1/δ)/(α−1)\varepsilon = \rho + \ln(1/\delta)/(\alpha - 1), and L={z:p(z)>eεq(z)}L = \{z : p(z) > e^{\varepsilon} q(z)\}. For every event SS, P(S)≤eεQ(S)+P(L)P(S) \le e^{\varepsilon} Q(S) + P(L). On LL, (p/q)α−1>e(α−1)ε(p/q)^{\alpha - 1} > e^{(\alpha - 1)\varepsilon}, so by Markov's inequality

P(L)≤e−(α−1)ε EP[(p/q)α−1]=e−(α−1)εe(α−1)ρ=δ.P(L) \le e^{-(\alpha - 1)\varepsilon}\, \mathbb E_P\big[(p/q)^{\alpha - 1}\big] = e^{-(\alpha - 1)\varepsilon} e^{(\alpha - 1)\rho} = \delta.

The other order is the same. Each order of the list gives a valid ε\varepsilon, so the smallest one is valid. □\square

Theorems 1 to 3 give the privacy claim of the code for the step count, rate, noise and δ\delta passed to epsilon_for. They do not say anything about the accuracy of the model, which is measured, not proved. They need the real-valued Gaussian noise and the exact Poisson sampling of the analysis; the floats and the seeded generator of the code do not give this, so the code is a model of the algorithm and not a safe deployment. ■\blacksquare

Complexity

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

  • One step. Line L3 makes nn coin flips. Lines L4 and L5 cost O(d)O(d) for each example of the batch, and the batch has qnqn examples on average and nn at most. Line L6 costs O(d)O(d) for the noise and line L7 costs O(d)O(d). So a step costs O(nd)O(n d) in the worst case and O(n+qnd)O(n + qnd) on average.
  • Training. TT steps cost O(Tnd)O(T n d) in the worst case. The extra space is O(d)O(d) for the sum and the noise.
  • Accountant. One order costs O(α)O(\alpha), so all orders up to αmax⁡\alpha_{\max} cost O(αmax⁡2)O(\alpha_{\max}^2), which does not depend on nn or dd.
  • In practice. The cost of per-example gradients is the main overhead in deep learning frameworks, since a normal step computes only the batch gradient.

Properties

  • Any loss. The privacy proof does not need convexity or a bound on the gradient: clipping makes the bound. This is why DP-SGD works for deep networks.
  • All steps are released. The theorem covers the whole sequence of parameters, so the intermediate models may be published. Releasing only the last model can leak less, but the theorem above does not show that.
  • Bias from clipping. Clipping changes the gradient when many examples have norms above CC, so DP-SGD does not minimize the true loss in general. A small CC means less noise relative to the signal, but more bias.
  • The neighbor relation. The accountant above is for add/remove with Poisson sampling. Under replace, one example changes the sum by up to 2C2C, and the bounds change.
  • Utility costs. For a fixed ε\varepsilon, a larger batch rate qq needs fewer steps per epoch but more noise per step. The trade-off is tuned, not proved.

Variants and improvements

  • Other accountants. The moments accountant of Abadi et al. computes the same log moments at integer orders. Numerical accountants based on the privacy loss distribution, and the bound of Gaussian DP, give tighter values of ε\varepsilon for the same training.
  • Per-layer clipping and adaptive clipping. Clip each layer to its own norm, or set CC from a private quantile of the gradient norms during training.
  • Private convex optimization. For convex losses with a bounded gradient, noisy SGD reaches the optimal excess risk (Bassily, Smith and Thakurta 2014). Objective perturbation and output perturbation are other private methods for convex ERM.
  • Public data. Pretraining on public data and private fine-tuning with DP-SGD often gives much better accuracy. PATE is a different route, which uses public unlabeled data.
  • Federated learning. The same clip and noise steps can run per user, not per example, so that the guarantee protects all the data of one user.

When to use it

Use DP-SGD to train a model on sensitive data held by a trusted curator, when the model is a neural network or another model with a non-convex loss. For a convex model with a bounded loss gradient, objective perturbation can give better accuracy for the same ε\varepsilon. When public unlabeled data from the same distribution exists, PATE may be a better choice. Report the neighbor relation, the sampling method, ε\varepsilon, δ\delta and the accountant with the model.

Pitfalls

  • Clipping the batch gradient. Line L5 applied to the sum, after line L6 or in place of the per-example clip, does not bound the effect of one example by CC, and the noise of line L6 is then too small for the claimed ε\varepsilon. Line L5 must clip each gradient of line L4 before the sum.
  • Noise without the norm. Line L6 with noise N(0,σ2I)\mathcal N(0, \sigma^2 I) in place of N(0,σ2C2I)\mathcal N(0, \sigma^2 C^2 I) gives the claimed privacy only when C=1C = 1. The standard deviation must be σC\sigma C.
  • Shuffled batches with a Poisson accountant. Line L3 replaced by fixed-size batches from a shuffle of the data is common in code, but the accountant above assumes Poisson sampling. Chua et al. (2024) showed that the gap can be large. Line L3 must match the sampling that the accountant assumes.
  • Dividing by the batch size. Line L7 with the true size ∣B∣|B| in place of qnqn uses a private number that the noise of line L6 does not cover. Divide by the fixed qnqn.
  • Tuning on the private data. Running many trainings with different CC, η\eta or σ\sigma and keeping the best one leaks more than one training. The tuning must be counted in the budget or done on public data.
  • Float samplers. Lines L3 and L6 with random() and a float Gaussian, as in this code, do not give the exact distributions of the analysis. A deployment must use samplers built for DP.

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.

dp_sgd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dp-sgd/. The authors are listed in prov/X5S7AN.jsonl.
"""Differentially private stochastic gradient descent (Abadi et al., CCS 2016).

Each step samples a batch by Poisson sampling with rate q, computes the
gradient of each example in the batch, clips each gradient to the L2 norm C,
sums the clipped gradients, adds Gaussian noise with standard deviation
sigma * C in each coordinate, and takes a step. The privacy cost of T steps is
computed with the Renyi divergence of the sampled Gaussian mechanism at
integer orders (Mironov, Talwar and Zhang 2019), converted to (epsilon, delta).

The model here is logistic regression with labels in {-1, +1}, so that the
code needs no library. Floats and random.Random are used for the sampling
and the noise, so this code shows the algorithm and is not a safe deployment:
a deployment needs a cryptographic source of randomness and an exact sampler.
The neighbor relation is add/remove of one example.
"""

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 logistic_loss(theta: Sequence[float], x: Sequence[float], y: int) -> float:
    """ln(1 + exp(-y theta.x)), computed without overflow."""
    z = -y * dot(theta, x)
    return z + math.log1p(math.exp(-z)) if z > 0 else math.log1p(math.exp(z))


def logistic_gradient(theta: Sequence[float], x: Sequence[float], y: int) -> Vector:
    """The gradient of the logistic loss in theta: -y x / (1 + exp(y theta.x))."""
    m = y * dot(theta, x)
    s = math.exp(-m) / (1 + math.exp(-m)) if m >= 0 else 1 / (1 + math.exp(m))
    return [-y * s * xi for xi in x]


def clip(g: Sequence[float], c: float) -> Vector:
    """g / max(1, |g| / c): the vector itself if its norm is at most c, else scaled to norm c."""
    scale = max(1.0, norm(g) / c)
    return [gi / scale for gi in g]


def dp_sgd(data: Sequence[Example], q: float, sigma: float, c: float, eta: float, steps: int, rng: random.Random) -> Vector:
    """Train logistic regression with DP-SGD and return the last parameter vector.

    Precondition: 0 < q <= 1, sigma > 0, c > 0, eta > 0 and all x of the same
    dimension d. The output is (epsilon, delta)-DP under add/remove with the
    epsilon of epsilon_for(q, sigma, steps, delta). Cost: O(T n d) time for
    T steps over n examples, and O(d) extra space.
    """
    if not (0 < q <= 1 and sigma > 0 and c > 0 and eta > 0):
        raise ValueError("need 0 < q <= 1 and positive sigma, c and eta")
    n = len(data)
    d = len(data[0][0])
    theta = [0.0] * d  # @line L1
    for _ in range(steps):  # @line L2
        total = [0.0] * d
        for x, y in data:
            if rng.random() < q:  # @line L3
                g = logistic_gradient(theta, x, y)  # @line L4
                gc = clip(g, c)  # @line L5
                total = [a + b for a, b in zip(total, gc)]
        noisy = [a + rng.gauss(0.0, sigma * c) for a in total]  # @line L6
        theta = [t - eta * gi / (q * n) for t, gi in zip(theta, noisy)]  # @line L7
    return theta  # @line L8


def _log_add(a: float, b: float) -> float:
    if a == -math.inf:
        return b
    if b == -math.inf:
        return a
    m = max(a, b)
    return m + math.log(math.exp(a - m) + math.exp(b - m))


def log_a(q: float, sigma: float, alpha: int) -> float:
    """ln A_alpha with A_alpha = sum_k C(alpha, k) (1 - q)^(alpha - k) q^k exp((k^2 - k) / (2 sigma^2)).

    A_alpha is E[(mu(z) / mu0(z))^alpha] for mu0 = N(0, sigma^2) and
    mu = (1 - q) mu0 + q N(1, sigma^2). Precondition: alpha >= 2 is an integer.
    """
    if alpha < 2 or int(alpha) != alpha:
        raise ValueError("alpha must be an integer at least 2")
    if q == 1:
        return alpha * (alpha - 1) / (2 * sigma ** 2)
    total = -math.inf
    for k in range(alpha + 1):
        term = math.lgamma(alpha + 1) - math.lgamma(k + 1) - math.lgamma(alpha - k + 1)
        term += k * math.log(q) + (alpha - k) * math.log1p(-q)
        term += (k * k - k) / (2 * sigma ** 2)
        total = _log_add(total, term)
    return total


def rdp_sampled_gaussian(q: float, sigma: float, alpha: int) -> float:
    """The Renyi DP of one step at order alpha: ln(A_alpha) / (alpha - 1).

    It is a bound for Poisson sampling with add/remove neighbors (Mironov,
    Talwar and Zhang, Theorem 5 shows that A_alpha is the larger of the two
    directions). Cost: O(alpha).
    """
    return log_a(q, sigma, alpha) / (alpha - 1)


def epsilon_for(q: float, sigma: float, steps: int, delta: float, orders: Sequence[int] = tuple(range(2, 257))) -> tuple[float, int]:
    """(epsilon, alpha): the smallest T rdp(alpha) + ln(1/delta) / (alpha - 1) over the orders.

    This converts Renyi DP to (epsilon, delta)-DP (Mironov 2017) after T steps
    of composition. Precondition: 0 < delta < 1. Cost: O(sum of the orders).
    """
    if not 0 < delta < 1:
        raise ValueError("need 0 < delta < 1")
    best = (math.inf, orders[0])
    for a in orders:
        eps = steps * rdp_sampled_gaussian(q, sigma, a) + math.log(1 / delta) / (a - 1)
        if eps < best[0]:
            best = (eps, a)
    return best
test_dp_sgd.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dp-sgd/. The authors are listed in prov/X5S7AN.jsonl.

import math
import random

import pytest

from dp_sgd import (
    clip,
    dp_sgd,
    epsilon_for,
    log_a,
    logistic_gradient,
    logistic_loss,
    norm,
    rdp_sampled_gaussian,
)


def blobs(n, rng):
    """Two Gaussian blobs in the plane with a bias coordinate; labels -1 and +1."""
    data = []
    for i in range(n):
        y = 1 if i % 2 == 0 else -1
        data.append(((rng.gauss(1.5 * y, 1.0), rng.gauss(0.5 * y, 1.0), 1.0), y))
    return data


def mean_loss(theta, data):
    return sum(logistic_loss(theta, x, y) for x, y in data) / len(data)


def test_check_values():
    eps, order = epsilon_for(1, 2, 1, 1e-5)
    assert abs(eps - 2.52629) < 1e-5 and order == 11
    # The bound at integer orders is above the best real order, 2.5243.
    best_real = min(a / 8 + math.log(1e5) / (a - 1) for a in (1 + i / 1000 for i in range(1, 60000)))
    assert abs(best_real - 2.5243) < 1e-4 and eps >= best_real
    # Abadi et al. report epsilon = 1.26 for q = 0.01, sigma = 4, delta = 1e-5 and 10000 steps.
    eps, order = epsilon_for(0.01, 4, 10000, 1e-5)
    assert abs(eps - 1.26) < 0.01 and order == 20
    assert abs(epsilon_for(0.01, 1.0, 1000, 1e-5)[0] - 2.5383) < 1e-4
    assert abs(epsilon_for(0.01, 1.1, 10000, 1e-5)[0] - 6.2798) < 1e-4


def test_full_batch_is_the_gaussian_mechanism():
    for sigma in (0.5, 1.0, 2.0, 5.0):
        for alpha in range(2, 30):
            assert abs(rdp_sampled_gaussian(1, sigma, alpha) - alpha / (2 * sigma ** 2)) < 1e-12


def test_bad_input():
    with pytest.raises(ValueError):
        log_a(0.1, 1.0, 1)
    with pytest.raises(ValueError):
        epsilon_for(0.1, 1.0, 10, 0.0)
    with pytest.raises(ValueError):
        dp_sgd([((1.0,), 1)], 0.0, 1.0, 1.0, 0.1, 1, random.Random(0))


def test_clipping_bounds_the_add_remove_sensitivity():
    rng = random.Random(2)
    for _ in range(500):
        d = rng.randint(1, 8)
        c = rng.uniform(0.1, 3.0)
        theta = [rng.uniform(-3, 3) for _ in range(d)]
        data = [([rng.uniform(-4, 4) for _ in range(d)], rng.choice((-1, 1))) for _ in range(rng.randint(0, 10))]
        extra = ([rng.uniform(-4, 4) for _ in range(d)], rng.choice((-1, 1)))
        g = logistic_gradient(theta, *extra)
        gc = clip(g, c)
        assert norm(gc) <= c * (1 + 1e-12)
        if norm(g) <= c:
            assert gc == g
        s1 = [0.0] * d
        for x, y in data:
            s1 = [a + b for a, b in zip(s1, clip(logistic_gradient(theta, x, y), c))]
        s2 = [a + b for a, b in zip(s1, gc)]
        assert norm([a - b for a, b in zip(s2, s1)]) <= c * (1 + 1e-9)


def test_gradient_against_finite_differences():
    rng = random.Random(3)
    for _ in range(500):
        d = rng.randint(1, 8)
        theta = [rng.uniform(-2, 2) for _ in range(d)]
        x = [rng.uniform(-2, 2) for _ in range(d)]
        y = rng.choice((-1, 1))
        g = logistic_gradient(theta, x, y)
        for i in range(d):
            h = 1e-6
            up = theta[:]
            dn = theta[:]
            up[i] += h
            dn[i] -= h
            fd = (logistic_loss(up, x, y) - logistic_loss(dn, x, y)) / (2 * h)
            assert abs(fd - g[i]) < 1e-6


def simpson_a(q, sigma, alpha, steps=1200):
    """Independent oracle: A_alpha = E_{z ~ N(0, sigma^2)} [((1 - q) + q exp((2z - 1) / (2 sigma^2)))^alpha]."""
    lo, hi = -12 * sigma, 12 * sigma + 2 * alpha
    h = (hi - lo) / steps

    def f(z):
        dens = math.exp(-z * z / (2 * sigma ** 2)) / (sigma * math.sqrt(2 * math.pi))
        return dens * ((1 - q) + q * math.exp((2 * z - 1) / (2 * sigma ** 2))) ** alpha

    s = f(lo) + f(hi)
    for i in range(1, steps):
        s += (4 if i % 2 else 2) * f(lo + i * h)
    return s * h / 3


def test_binomial_formula_against_numerical_integration():
    rng = random.Random(4)
    for _ in range(500):
        q = rng.uniform(0.001, 0.5)
        sigma = rng.uniform(0.9, 3.0)
        alpha = rng.randint(2, 8)
        exact = math.exp(log_a(q, sigma, alpha))
        assert abs(simpson_a(q, sigma, alpha) - exact) <= 1e-6 * exact


def test_epsilon_is_monotone():
    e = [epsilon_for(0.02, 1.2, t, 1e-5)[0] for t in (10, 100, 1000, 5000)]
    assert e == sorted(e)
    e = [epsilon_for(0.02, s, 1000, 1e-5)[0] for s in (0.8, 1.0, 2.0, 4.0)]
    assert e == sorted(e, reverse=True)
    e = [epsilon_for(0.02, 1.2, 1000, dl)[0] for dl in (1e-3, 1e-5, 1e-7)]
    assert e == sorted(e)
    e = [epsilon_for(q, 1.2, 1000, 1e-5)[0] for q in (0.001, 0.01, 0.1, 1.0)]
    assert e == sorted(e)


def test_training_lowers_the_loss():
    rng = random.Random(5)
    data = blobs(200, rng)
    start = mean_loss([0.0, 0.0, 0.0], data)
    theta = dp_sgd(data, q=0.1, sigma=1.0, c=1.0, eta=0.5, steps=200, rng=rng)
    assert mean_loss(theta, data) < start - 0.2
    # The same seed gives the same model.
    a = dp_sgd(data, 0.1, 1.0, 1.0, 0.5, 20, random.Random(7))
    b = dp_sgd(data, 0.1, 1.0, 1.0, 0.5, 20, random.Random(7))
    assert a == b

History

Song, Chaudhuri and Sarwate (2013) studied SGD with differentially private updates for convex learning. Bassily, Smith and Thakurta (FOCS 2014) analyzed noisy SGD for private empirical risk minimization and proved optimal excess risk bounds, using amplification by subsampling and advanced composition. Abadi, Chu, Goodfellow, McMahan, Mironov, Talwar and Zhang (CCS 2016) added per-example clipping for deep networks and the moments accountant, which gave much smaller values of ε\varepsilon than the composition theorems. Mironov (2017) defined Renyi differential privacy, and Mironov, Talwar and Zhang (2019) gave the exact Renyi bound of the sampled Gaussian at integer orders, which libraries now use.

References

  1. Martín Abadi, Andy Chu, Ian Goodfellow, H. Brendan McMahan, Ilya Mironov, Kunal Talwar and Li Zhang, Deep learning with differential privacy, ACM CCS 2016, pages 308 to 318, Algorithm 1 and Theorem 1 (Section 3.1), the moments accountant and its Theorem 2 (Section 3.2), and the example with q = 0.01, sigma = 4, delta = 1e-5 and 10000 steps
  2. Ilya Mironov, Kunal Talwar and Li Zhang, Renyi differential privacy of the sampled Gaussian mechanism, arXiv 1908.10530, 2019, Theorem 4 (Section 2, the reduction to one dimension), the quantities A_alpha and B_alpha and Theorem 5 (Section 3.1), and the computation at integer orders
  3. Shuang Song, Kamalika Chaudhuri and Anand D. Sarwate, Stochastic gradient descent with differentially private updates, IEEE GlobalSIP 2013, pages 245 to 248, the noisy stochastic gradient update with a bounded gradient and its privacy
  4. Raef Bassily, Adam Smith and Abhradeep Thakurta, Private empirical risk minimization: efficient algorithms and tight error bounds, IEEE FOCS 2014, pages 464 to 473, the noisy stochastic gradient method for private convex empirical risk minimization and its excess risk bounds
  5. Ilya Mironov, Renyi differential privacy, IEEE Computer Security Foundations Symposium 2017, the composition of Renyi DP and its conversion to (epsilon, delta)-DP

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 correctness
  • 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