Algorithm Search⌘K

Algorithmadvanced

Objective perturbation

Also called Chaudhuri-Monteleoni-Sarwate perturbation.

Adds a random linear term to a strongly convex empirical risk before minimizing it, which gives differentially private learning.

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

Objective perturbation trains a model privately by changing the training problem, not the trained model. It adds a random linear term bTf/nb^{\mathsf T} f / n to a strongly convex regularized empirical risk, and releases the exact minimizer of the new objective. The noise vector bb has a density proportional to e−β∥b∥e^{-\beta\|b\|}. Since the minimizer and the noise determine each other one to one, the density of the output has a closed form, and one example can change it by at most a factor eεe^{\varepsilon}. Chaudhuri and Monteleoni (2008) introduced the method for logistic regression, and Chaudhuri, Monteleoni and Sarwate (2011) stated it for convex losses with a bounded second derivative as their Algorithm 2. For those losses it usually gives better accuracy than output perturbation at the same ε\varepsilon.

In plain words

Output perturbation trains a model and then shakes the result. Objective perturbation shakes the question instead. Before training, it tilts the training goal by a small random amount, and then it trains as usual on the tilted goal.

The tilt is chosen so that any trained model could have come from many different tilts. If one person's data changes, a slightly different tilt gives the same model, and that tilt is almost as likely. So an observer cannot tell whether that person was in the data.

The tilt is divided by the number of examples, so with more data it has less effect on the model.

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, and nn is public. The loss ℓ(yfTx)\ell(y f^{\mathsf T} x) is convex and twice differentiable with ∣ℓ′∣≤1|\ell'| \le 1 and 0≤ℓ′′≤c0 \le \ell'' \le c; the code uses the logistic loss, with c=1/4c = 1/4. 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. OBJECTIVE-PERTURBATION(D, Lambda, epsilon, c)
  2. 1epsilon' <- epsilon - ln(1 + 2c/(n Lambda) + c^2/(n^2 Lambda^2))
  3. 2if epsilon' > 0 then Delta <- 0
  4. 3else Delta <- c / (n (e^(epsilon/4) - 1)) - Lambda; epsilon' <- epsilon / 2
  5. 4b <- a vector with density proportional to exp(-(epsilon'/2) |b|)
  6. 5f_priv <- argmin over f of J_D(f) + (1/n) b.f + (Delta/2) |f|^2
  7. 6return f_priv

Lines L1 to L3 split the budget ε\varepsilon between two sources of privacy loss. The noise term pays ε′\varepsilon'. The curvature of the loss pays the rest: one example changes the Hessian of the objective by a rank-one matrix, and that changes the density of the output by the factor ln⁡(1+c/(nΛ))\ln(1 + c/(n\Lambda)) or less. Line L1 reserves twice that factor, as in the analysis of Chaudhuri, Monteleoni and Sarwate. When nΛn\Lambda is too small for that, ε′\varepsilon' is not positive, and line L3 adds the extra regularizer Δ>0\Delta > 0, chosen so that the curvature part costs at most ε/2\varepsilon/2 and the noise gets the other half.

Line L4 draws the noise as in output perturbation: the norm is a sum of dd exponential draws of rate β=ε′/2\beta = \varepsilon'/2 and the direction is uniform. Line L5 is a normal training run. The objective is (Λ+Δ)(\Lambda + \Delta)-strongly convex, so the minimizer is unique; the code finds it by gradient descent with the step 1/(1/4+Λ+Δ)1/(1/4 + \Lambda + \Delta) and stops at a gradient norm of 10−1110^{-11}. The noise in line L5 enters through its gradient: the minimizer is the point where the gradient of JD+(Δ/2)∥f∥2J_D + (\Delta/2)\|f\|^2 equals −b/n-b/n.

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

Example

Take the data of the output perturbation page: 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 ε′=1−2ln⁡1.125=0.7644\varepsilon' = 1 - 2\ln 1.125 = 0.7644, so line L2 sets Δ=0\Delta = 0, and line L4 uses β=0.3822\beta = 0.3822. With the seed 9 the code draws b=(1.8363,2.1787)b = (1.8363, 2.1787), of norm 2.84942.8494. Line L5 then gives fpriv=(−0.2786,−0.5192)f_{\mathrm{priv}} = (-0.2786, -0.5192), against the non-private minimizer (0.4368,0.3532)(0.4368, 0.3532). With four examples the tilt b/nb/n is large, and the model even changes sign.

Replace example 4 by ((0,1),−1)((0, 1), -1). On a grid of models ff, the largest log ratio of the two output densities is 0.38220.3822, below ε=1\varepsilon = 1. The table shows the budget split for other settings, with c=1/4c = 1/4.

nn Λ\Lambda ε\varepsilon branch ε′\varepsilon' Δ\Delta
4 0.5 1 L2 0.7644 0
4 0.05 0.5 L3 0.25 0.4194
1000 0.01 0.1 L2 0.0506 0
1000 0.001 0.1 L3 0.05 0.0089

Correctness

Theorem (Chaudhuri, Monteleoni and Sarwate, Theorem 9). Lines L1 to L6 are ε\varepsilon-DP under replace.

The proof has three steps. First, for each bb the objective has one minimizer, and bb can be recovered from it: b=bD(f)=−n(∇JD(f)+Δf)b = b_D(f) = -n(\nabla J_D(f) + \Delta f). So f↦bD(f)f \mapsto b_D(f) is a bijection, and the change of variables formula gives the output density pD(f)=ν(bD(f))det⁡AD(f)p_D(f) = \nu(b_D(f)) \det A_D(f), where AD(f)=∑iℓ′′(yifTxi)xixiT+n(Λ+Δ)IA_D(f) = \sum_i \ell''(y_i f^{\mathsf T} x_i) x_i x_i^{\mathsf T} + n(\Lambda + \Delta) I. Second, one example changes bD(f)b_D(f) by a vector of norm at most 2, since ∣ℓ′∣≤1|\ell'| \le 1, so the factor ν\nu changes by at most e2β=eε′e^{2\beta} = e^{\varepsilon'}. Third, one example changes AD(f)A_D(f) by a rank-one term, and the matrix determinant lemma bounds the ratio of the determinants by 1+c/(n(Λ+Δ))1 + c/(n(\Lambda + \Delta)). Lines L1 to L3 make the two factors multiply to at most eεe^{\varepsilon}.

The correctness proof of this page gives all the steps. It bounds the determinant ratio by one factor of 1+c/(n(Λ+Δ))1 + c/(n(\Lambda + \Delta)), which is sharper than the squared factor of the paper, so the algorithm as stated has some slack. The tests check the minimizer against bisection in one dimension, the recovery of bb from the output, the density formula against the exact law in one dimension, and the density ratio on a grid in both branches.

Proof: Objective 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∈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' differs from DD in one example, and nn is public. The loss ℓ:R→R\ell : \mathbb R \to \mathbb R is convex and twice continuously differentiable with ∣ℓ′(z)∣≤1|\ell'(z)| \le 1 and 0≤ℓ′′(z)≤c0 \le \ell''(z) \le c for all zz. The logistic loss ℓ(z)=ln⁡(1+e−z)\ell(z) = \ln(1 + e^{-z}) has ℓ′(z)=−σ(−z)\ell'(z) = -\sigma(-z) and ℓ′′(z)=σ(z)σ(−z)≤1/4\ell''(z) = \sigma(z)\sigma(-z) \le 1/4, where σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), so c=1/4c = 1/4. Let Λ>0\Lambda > 0 and

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.

Lines L1 to L3 compute ε′\varepsilon' and Δ≥0\Delta \ge 0, line L4 draws bb with the density ν(b)=e−β∥b∥/Z\nu(b) = e^{-\beta\|b\|}/Z for β=ε′/2\beta = \varepsilon'/2, and line L5 returns the minimizer of

JDpriv(f;b)=JD(f)+1nbTf+Δ2∥f∥2.J^{\mathrm{priv}}_D(f; b) = J_D(f) + \frac1n b^{\mathsf T} f + \frac{\Delta}{2}\|f\|^2.

Lemma 1 (the noise determines the output, and back). For every bb, JDpriv(⋅ ;b)J^{\mathrm{priv}}_D(\cdot\,; b) has a unique minimizer fD(b)f_D(b). Define

bD(f)=−n(∇JD(f)+Δf)=−∑i=1nyi ℓ′(yifTxi) xi−n(Λ+Δ)f.b_D(f) = -n\big(\nabla J_D(f) + \Delta f\big) = -\sum_{i=1}^n y_i\,\ell'(y_i f^{\mathsf T} x_i)\,x_i - n(\Lambda + \Delta) f.

Then f=fD(b)f = f_D(b) if and only if b=bD(f)b = b_D(f). So bDb_D is a bijection of Rd\mathbb R^d with the inverse fDf_D.

Proof. JDpriv(⋅ ;b)J^{\mathrm{priv}}_D(\cdot\,; b) is (Λ+Δ)(\Lambda + \Delta)-strongly convex and differentiable, so it has exactly one minimizer, and it is the only point where the gradient ∇JD(f)+b/n+Δf\nabla J_D(f) + b/n + \Delta f is zero. That gradient is zero exactly when b=bD(f)b = b_D(f). Every bb has the minimizer fD(b)f_D(b) with bD(fD(b))=bb_D(f_D(b)) = b, so bDb_D is onto. If bD(f1)=bD(f2)=bb_D(f_1) = b_D(f_2) = b, both points minimize the same function, so f1=f2f_1 = f_2. □\square

Lemma 2 (the density of the output). Let AD(f)=∑i=1nℓ′′(yifTxi) xixiT+n(Λ+Δ)IA_D(f) = \sum_{i=1}^n \ell''(y_i f^{\mathsf T} x_i)\,x_i x_i^{\mathsf T} + n(\Lambda + \Delta) I. The output fD(b)f_D(b) has the density

pD(f)=ν(bD(f)) det⁡AD(f).p_D(f) = \nu(b_D(f))\,\det A_D(f).

Proof. bDb_D is continuously differentiable with the Jacobian matrix −AD(f)-A_D(f), since yi2=1y_i^2 = 1. AD(f)A_D(f) is symmetric and AD(f)⪰n(Λ+Δ)I≻0A_D(f) \succeq n(\Lambda + \Delta) I \succ 0, so the Jacobian is invertible everywhere. By Lemma 1 and the inverse function theorem, bDb_D is a C1C^1 bijection with a C1C^1 inverse. The change of variables formula gives, for every event SS,

Pr⁡[fD(b)∈S]=Pr⁡[b∈bD(S)]=∫bD(S)ν(b) db=∫Sν(bD(f)) ∣det⁡(−AD(f))∣ df,\Pr[f_D(b) \in S] = \Pr[b \in b_D(S)] = \int_{b_D(S)} \nu(b)\,db = \int_S \nu(b_D(f))\,|\det(-A_D(f))|\,df,

and ∣det⁡(−AD(f))∣=det⁡AD(f)|\det(-A_D(f))| = \det A_D(f) because AD(f)A_D(f) is positive definite. □\square

Lemma 3 (the noise moves little). For replace neighbors and every ff, ∥bD(f)−bD′(f)∥≤2\|b_D(f) - b_{D'}(f)\| \le 2.

Proof. Say D′D' replaces (xn,yn)(x_n, y_n) by (x′,y′)(x', y'). The sums for DD and D′D' share all terms but one, and the term n(Λ+Δ)fn(\Lambda + \Delta) f is the same. So bD(f)−bD′(f)=y′ℓ′(y′fTx′) x′−ynℓ′(ynfTxn) xnb_D(f) - b_{D'}(f) = y'\ell'(y' f^{\mathsf T} x')\,x' - y_n\ell'(y_n f^{\mathsf T} x_n)\,x_n. Each of the two vectors has norm at most ∣ℓ′∣⋅∥x∥≤1|\ell'| \cdot \|x\| \le 1. □\square

Lemma 4 (the determinant moves little). For replace neighbors and every ff, det⁡AD(f)/det⁡AD′(f)≤1+c/(n(Λ+Δ))\det A_D(f) / \det A_{D'}(f) \le 1 + c/(n(\Lambda + \Delta)).

Proof. Let M=∑i<nℓ′′(yifTxi) xixiT+n(Λ+Δ)IM = \sum_{i<n} \ell''(y_i f^{\mathsf T} x_i)\,x_i x_i^{\mathsf T} + n(\Lambda + \Delta) I, so M⪰n(Λ+Δ)IM \succeq n(\Lambda + \Delta) I. With u=ℓ′′(ynfTxn) xnu = \sqrt{\ell''(y_n f^{\mathsf T} x_n)}\,x_n and v=ℓ′′(y′fTx′) x′v = \sqrt{\ell''(y' f^{\mathsf T} x')}\,x', we have AD=M+uuTA_D = M + uu^{\mathsf T} and AD′=M+vvTA_{D'} = M + vv^{\mathsf T}. The matrix determinant lemma gives det⁡(M+uuT)=det⁡M (1+uTM−1u)\det(M + uu^{\mathsf T}) = \det M\,(1 + u^{\mathsf T}M^{-1}u), and the same for vv. So

det⁡AD(f)det⁡AD′(f)=1+uTM−1u1+vTM−1v≤1+uTM−1u≤1+∥u∥2n(Λ+Δ)≤1+cn(Λ+Δ),\frac{\det A_D(f)}{\det A_{D'}(f)} = \frac{1 + u^{\mathsf T}M^{-1}u}{1 + v^{\mathsf T}M^{-1}v} \le 1 + u^{\mathsf T}M^{-1}u \le 1 + \frac{\|u\|^2}{n(\Lambda + \Delta)} \le 1 + \frac{c}{n(\Lambda + \Delta)},

since vTM−1v≥0v^{\mathsf T}M^{-1}v \ge 0, the largest eigenvalue of M−1M^{-1} is at most 1/(n(Λ+Δ))1/(n(\Lambda + \Delta)), and ∥u∥2=ℓ′′ ∥xn∥2≤c\|u\|^2 = \ell''\,\|x_n\|^2 \le c. □\square

Chaudhuri, Monteleoni and Sarwate bound the same ratio by (1+c/(n(Λ+Δ)))2(1 + c/(n(\Lambda + \Delta)))^2 in the proof of their Theorem 9, with their Lemma 10 on the eigenvalues of a rank-two update. Lemma 4 is sharper by one factor. Algorithm 2 is set for the weaker bound, so it stays correct, and the proof below shows the slack.

Theorem (privacy). Lines L1 to L6 are ε\varepsilon-DP under replace.

Proof. By Lemma 2, for every ff,

pD(f)pD′(f)=exp⁡(β(∥bD′(f)∥−∥bD(f)∥))⋅det⁡AD(f)det⁡AD′(f)≤e2β(1+cn(Λ+Δ))=eε′(1+cn(Λ+Δ)),\frac{p_D(f)}{p_{D'}(f)} = \exp\big(\beta(\|b_{D'}(f)\| - \|b_D(f)\|)\big)\cdot\frac{\det A_D(f)}{\det A_{D'}(f)} \le e^{2\beta}\left(1 + \frac{c}{n(\Lambda + \Delta)}\right) = e^{\varepsilon'}\left(1 + \frac{c}{n(\Lambda + \Delta)}\right),

by the triangle inequality, Lemma 3 and Lemma 4. Note that 1+2c/(nΛ)+c2/(n2Λ2)=(1+c/(nΛ))21 + 2c/(n\Lambda) + c^2/(n^2\Lambda^2) = (1 + c/(n\Lambda))^2, so line L1 sets ε′=ε−2ln⁡(1+c/(nΛ))\varepsilon' = \varepsilon - 2\ln(1 + c/(n\Lambda)). There are two cases.

  • Line L2, ε′>0\varepsilon' > 0 and Δ=0\Delta = 0. The bound is exp⁡(ε−2ln⁡(1+c/(nΛ))+ln⁡(1+c/(nΛ)))≤eε\exp(\varepsilon - 2\ln(1 + c/(n\Lambda)) + \ln(1 + c/(n\Lambda))) \le e^{\varepsilon}.
  • Line L3, ε′≤0\varepsilon' \le 0. Then (1+c/(nΛ))2≥eε(1 + c/(n\Lambda))^2 \ge e^{\varepsilon}, so c/(nΛ)≥eε/2−1>eε/4−1c/(n\Lambda) \ge e^{\varepsilon/2} - 1 > e^{\varepsilon/4} - 1, and Δ=c/(n(eε/4−1))−Λ>0\Delta = c/(n(e^{\varepsilon/4} - 1)) - \Lambda > 0. Now Λ+Δ=c/(n(eε/4−1))\Lambda + \Delta = c/(n(e^{\varepsilon/4} - 1)), so 1+c/(n(Λ+Δ))=eε/41 + c/(n(\Lambda + \Delta)) = e^{\varepsilon/4}. The new ε′=ε/2\varepsilon' = \varepsilon/2 gives the bound eε/2+ε/4≤eεe^{\varepsilon/2 + \varepsilon/4} \le e^{\varepsilon}.

In both cases pD(f)≤eεpD′(f)p_D(f) \le e^{\varepsilon} p_{D'}(f) for every ff, and integrating over an event SS gives Pr⁡[output∈S∣D]≤eεPr⁡[output∈S∣D′]\Pr[\text{output} \in S \mid D] \le e^{\varepsilon}\Pr[\text{output} \in S \mid D']. □\square

What the proof needs. The proof uses the exact minimizer of line L5: it is a bijection of the noise, and its density has the closed form of Lemma 2. A solver that stops early returns a different random variable, and the theorem does not cover it. The code stops at a gradient norm of 10−1110^{-11} and samples with floats, so it follows the analysis only up to these numerical effects. The proof also needs ℓ\ell to be twice differentiable with a bounded ℓ′′\ell'', which rules out the hinge loss, and ∥xi∥≤1\|x_i\| \le 1. ■\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). The objective of line L5 is (Λ+Δ)(\Lambda + \Delta)-strongly convex and (c+Λ+Δ)(c + \Lambda + \Delta)-smooth, so gradient descent needs K=O((1+c/(Λ+Δ))ln⁡(1/t))K = O((1 + c/(\Lambda + \Delta)) \ln(1/t)) steps to reach the gradient norm tt, and line L5 costs O(Knd)O(Knd).
  • The rest. Lines L1 to L3 cost O(1)O(1) and line L4 costs O(d)O(d).
  • Space. The extra space is O(d)O(d) beyond the data.

The cost is the cost of one non-private training run.

Properties

  • Pure DP. The guarantee is ε\varepsilon-DP with δ=0\delta = 0, under replace neighbors with a public nn.
  • Needs a smooth loss. The proof needs ℓ′′\ell'' to exist and be bounded. The logistic loss and the Huber loss qualify; the hinge loss of the standard support vector machine does not. Chaudhuri, Monteleoni and Sarwate use a Huber version of the SVM for this reason.
  • Needs the exact minimizer. The density formula holds only for the exact minimizer of line L5. A solver that stops early, or a constrained problem, changes the output law and is not covered.
  • Better accuracy than output perturbation. Chaudhuri, Monteleoni and Sarwate prove bounds on the number of examples needed for a given generalization error, and the bound for objective perturbation is smaller than the bound for output perturbation. Their experiments on real data show the same order.
  • The regularizer is part of the privacy. Λ\Lambda must be fixed in advance. Picking it on the private data leaks, and the paper gives a private tuning method that uses held-out parts of the data.

Variants and improvements

  • Gaussian noise. Kifer, Smith and Thakurta (2012) gave an (ε,δ)(\varepsilon, \delta) version with Gaussian noise and support for convex constraints and some non-smooth regularizers. Its noise norm grows like d\sqrt d, not dd.
  • Approximate minimizers. Iyengar et al. (2019) studied versions that allow an approximate solver for line L5, at the cost of extra noise on the output.
  • Other regularizers. The analysis of Chaudhuri, Monteleoni and Sarwate allows any 1-strongly convex, twice differentiable regularizer N(f)N(f) in place of ∥f∥2/2\|f\|^2/2.
  • Kernels. The paper also handles kernel methods by first mapping the data to random features, then running objective perturbation on them.
  • No convexity. For non-convex models, DP-SGD is the usual choice.

When to use it

Use objective perturbation for a convex model with a smooth loss and an L2L_2 regularizer, such as regularized logistic regression, when a pure ε\varepsilon guarantee is required and the solver can reach the minimizer to high precision. It usually beats output perturbation in accuracy. Use output perturbation when the training code cannot be changed, and DP-SGD when the model is not convex or the data is too large to solve to high precision.

Pitfalls

  • Skipping the budget split. Line L4 with β=ε/2\beta = \varepsilon/2 in place of ε′/2\varepsilon'/2 ignores the loss through the determinant, and the result is not ε\varepsilon-DP. Lines L1 to L3 must run, and line L4 must use ε′\varepsilon'.
  • A negative budget. Line L2 run when ε′≤0\varepsilon' \le 0 gives a noise rate of zero or below, which has no meaning. Line L3 must replace ε′\varepsilon' by ε/2\varepsilon/2 and add Δ\Delta in that case.
  • Forgetting the extra regularizer. Line L5 without the term (Δ/2)∥f∥2(\Delta/2)\|f\|^2 after line L3 has set Δ>0\Delta > 0 breaks the bound of the determinant. Line L5 must use the same Δ\Delta.
  • Scaling the noise wrong. Line L5 with the term bTfb^{\mathsf T} f in place of bTf/nb^{\mathsf T} f / n uses an objective whose risk part has a different scale from the one in the analysis. Keep the factor 1/n1/n that matches JDJ_D, or rescale both.
  • A non-smooth loss. Line L5 with the hinge loss has no bounded ℓ′′\ell'', and the determinant bound fails. Use a smooth loss, such as the Huber loss, with its cc in line L1.
  • Early stopping. Line L5 run for a fixed small number of steps does not return the minimizer that the proof needs. Run the solver to a tight tolerance, or use a variant built for approximate solvers.

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
objective_perturbation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/objective-perturbation/. The authors are listed in prov/HFPG7H.jsonl.
"""Objective perturbation for regularized logistic regression (Chaudhuri, Monteleoni and Sarwate, Algorithm 2).

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}. The logistic loss l(z) = ln(1 + e^(-z))
has |l'| <= 1 and 0 < l'' <= c = 1/4. The algorithm draws a noise vector b
with density proportional to exp(-beta |b|) and returns the minimizer of

    J(f, D) + (1/n) b.f + (Delta/2) |f|^2,

which is epsilon-DP under replace neighbors.

The minimizer is found by gradient descent, 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]

C_LOGISTIC = 0.25  # the bound on the second derivative of the logistic loss


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 perturbed_objective(f: Sequence[float], data: Sequence[Example], lam: float, b: Sequence[float], extra: float) -> float:
    """J(f, D) + (1/n) b.f + (extra/2) |f|^2, the objective of line L5."""
    return risk(f, data, lam) + dot(b, f) / len(data) + extra / 2 * dot(f, f)


def perturbed_gradient(f: Sequence[float], data: Sequence[Example], lam: float, b: Sequence[float], extra: float) -> Vector:
    """The gradient of the objective of line L5."""
    n = len(data)
    return [g + bi / n + extra * fi for g, bi, fi in zip(risk_gradient(f, data, lam), b, f)]


def minimize_perturbed(data: Sequence[Example], lam: float, b: Sequence[float], extra: float,
                       tol: float = 1e-11, max_steps: int = 200000) -> Vector:
    """The minimizer of the objective of line L5 by gradient descent with step 1/(1/4 + lam + extra).

    The objective is (lam + extra)-strongly convex and (1/4 + lam + extra)-smooth
    when |x_i| <= 1, so the iteration converges linearly. It stops when the
    gradient norm is at most tol. Cost: O(n d) per iteration.
    """
    f = [0.0] * len(b)
    step = 1 / (C_LOGISTIC + lam + extra)
    for _ in range(max_steps):
        g = perturbed_gradient(f, data, lam, b, extra)
        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 privacy_parameters(n: int, lam: float, epsilon: float, c: float = C_LOGISTIC) -> tuple[float, float]:
    """The pair (epsilon', Delta) of lines L1 to L3. Cost: O(1)."""
    eps_prime = epsilon - math.log(1 + 2 * c / (n * lam) + c * c / (n * n * lam * lam))  # @line L1
    if eps_prime > 0:
        extra = 0.0  # @line L2
    else:
        extra = c / (n * (math.exp(epsilon / 4) - 1)) - lam  # @line L3
        eps_prime = epsilon / 2
    return eps_prime, extra


def objective_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 not data or any(norm(x) > 1 + 1e-12 or y not in (-1, 1) for x, y in data):
        raise ValueError("need n >= 1, |x| <= 1 and y in {-1, +1}")
    n, d = len(data), len(data[0][0])
    eps_prime, extra = privacy_parameters(n, lam, epsilon)
    b = sample_noise(d, eps_prime / 2, rng)  # @line L4
    f_priv = minimize_perturbed(data, lam, b, extra)  # @line L5
    return f_priv  # @line L6


def noise_of(f: Sequence[float], data: Sequence[Example], lam: float, extra: float) -> Vector:
    """The unique b for which f minimizes the objective of line L5: b = -n (grad J(f) + extra f)."""
    n = len(data)
    return [-n * (g + extra * fi) for g, fi in zip(risk_gradient(f, data, lam), f)]


def jacobian_matrix(f: Sequence[float], data: Sequence[Example], lam: float, extra: float) -> list[Vector]:
    """A(f) = sum_i l''(y_i f.x_i) x_i x_i^T + n (lam + extra) I, minus the Jacobian of noise_of."""
    n, d = len(data), len(f)
    a = [[n * (lam + extra) if i == j else 0.0 for j in range(d)] for i in range(d)]
    for x, y in data:
        s = _sigmoid(y * dot(f, x))
        w = s * (1 - s)
        for i in range(d):
            for j in range(d):
                a[i][j] += w * x[i] * x[j]
    return a


def log_det(a: Sequence[Sequence[float]]) -> float:
    """ln det a for a symmetric positive definite matrix, by Gaussian elimination. Cost: O(d^3)."""
    m = [list(row) for row in a]
    d = len(m)
    total = 0.0
    for k in range(d):
        p = max(range(k, d), key=lambda i: abs(m[i][k]))
        m[k], m[p] = m[p], m[k]
        pivot = m[k][k]
        if pivot <= 0:
            raise ValueError("matrix is not positive definite")
        total += math.log(pivot)
        for i in range(k + 1, d):
            r = m[i][k] / pivot
            for j in range(k, d):
                m[i][j] -= r * m[k][j]
    return total


def output_log_density(f: Sequence[float], data: Sequence[Example], lam: float, epsilon: float) -> float:
    """The log density of the output of objective_perturbation at f, normalizer included.

    By the change of variables b = noise_of(f), the density is
    nu(noise_of(f)) det A(f), with nu(b) = exp(-beta |b|) / Z.
    """
    n, d = len(data), len(f)
    eps_prime, extra = privacy_parameters(n, lam, epsilon)
    beta = eps_prime / 2
    log_z = math.log(2) + d / 2 * math.log(math.pi) + math.lgamma(d) - math.lgamma(d / 2) - d * math.log(beta)
    b = noise_of(f, data, lam, extra)
    return -beta * norm(b) - log_z + log_det(jacobian_matrix(f, data, lam, extra))
test_objective_perturbation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/objective-perturbation/. The authors are listed in prov/HFPG7H.jsonl.

import math
import random

import pytest

import dpkit
from objective_perturbation import (
    C_LOGISTIC,
    jacobian_matrix,
    log_det,
    minimize_perturbed,
    noise_of,
    norm,
    objective_perturbation,
    output_log_density,
    perturbed_gradient,
    perturbed_objective,
    privacy_parameters,
    sample_noise,
)


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():
    eps_prime, extra = privacy_parameters(4, 0.5, 1.0)
    assert eps_prime == pytest.approx(1 - 2 * math.log(1.125)) and extra == 0.0
    assert eps_prime == pytest.approx(0.764434, abs=1e-6)
    eps_prime, extra = privacy_parameters(4, 0.05, 0.5)
    assert eps_prime == 0.25 and extra == pytest.approx(0.419401, abs=1e-6)
    f = minimize_perturbed(EXAMPLE, 0.5, [0.0, 0.0], 0.0)
    assert abs(f[0] - 0.4368) < 1e-4 and abs(f[1] - 0.3532) < 1e-4
    g = objective_perturbation(EXAMPLE, 0.5, 1.0, random.Random(9))
    assert abs(g[0] + 0.2786) < 1e-4 and abs(g[1] + 0.5192) < 1e-4


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


def test_extra_regularizer_is_nonnegative_and_balances_the_budget():
    rng = random.Random(1)
    for _ in range(500):
        n = rng.randint(1, 50)
        lam = rng.uniform(0.001, 1.0)
        eps = rng.uniform(0.05, 3.0)
        eps_prime, extra = privacy_parameters(n, lam, eps)
        assert eps_prime > 0 and extra >= 0
        # The two parts of the privacy loss add up to at most epsilon.
        assert eps_prime + 2 * math.log(1 + C_LOGISTIC / (n * (lam + extra))) <= eps + 1e-12


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


def test_minimizer_against_bisection():
    rng = random.Random(2)
    for _ in range(500):
        n = rng.randint(1, 8)
        lam = rng.uniform(0.2, 1.0)
        extra = rng.choice((0.0, rng.uniform(0.0, 0.5)))
        data = random_data(n, 1, rng)
        b = rng.uniform(-5, 5)
        f = minimize_perturbed(data, lam, [b], extra)
        assert abs(f[0] - bisect_1d(data, lam, b, extra)) < 1e-9


def test_noise_is_recovered_from_the_output():
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(1, 6)
        d = rng.randint(1, 3)
        lam = rng.uniform(0.2, 1.0)
        extra = rng.choice((0.0, 0.3))
        data = random_data(n, d, rng)
        b = sample_noise(d, rng.uniform(0.3, 2.0), rng)
        f = minimize_perturbed(data, lam, b, extra)
        back = noise_of(f, data, lam, extra)
        assert norm([u - v for u, v in zip(back, b)]) < 1e-8
        for _ in range(5):
            g = [fi + rng.uniform(-0.1, 0.1) for fi in f]
            assert perturbed_objective(g, data, lam, b, extra) >= perturbed_objective(f, data, lam, b, extra)


def test_log_det_against_closed_form():
    rng = random.Random(4)
    for _ in range(100):
        a, c = rng.uniform(1, 3), rng.uniform(1, 3)
        b = rng.uniform(-0.9, 0.9)
        assert log_det([[a, b], [b, c]]) == pytest.approx(math.log(a * c - b * b))


@pytest.mark.parametrize("lam, eps", [(0.5, 1.0), (0.05, 0.5)])
def test_output_density_ratio_is_at_most_epsilon(lam, eps):
    """Both branches: Delta = 0 for (0.5, 1.0) and Delta > 0 for (0.05, 0.5), with n = 4."""
    rng = random.Random(5)
    grid = [(i / 4, j / 4) for i in range(-12, 13) for j in range(-12, 13)]
    worst = 0.0
    for _ in range(10):
        data = random_data(4, 2, rng)
        other = list(data)
        other[rng.randrange(4)] = (random_point(2, rng), rng.choice((-1, 1)))
        loss = dpkit.log_ratio_grid(
            lambda f: output_log_density(f, data, lam, eps),
            lambda f: output_log_density(f, other, lam, eps),
            grid,
        )
        assert loss <= eps + 1e-9
        worst = max(worst, loss)
    assert worst > 0.1 * eps


def test_density_matches_the_exact_law_in_one_dimension():
    """In one dimension, f_priv <= t exactly when b >= noise_of(t), and b is Laplace."""
    rng = random.Random(6)
    data = random_data(5, 1, rng)
    lam, eps = 0.3, 1.0
    eps_prime, extra = privacy_parameters(5, lam, eps)
    beta = eps_prime / 2

    def exact_cdf(t):
        u = noise_of([t], data, lam, extra)[0]
        return 0.5 * math.exp(-beta * u) if u >= 0 else 1 - 0.5 * math.exp(beta * u)

    # The integral of the density, by the trapezoid rule, matches the exact law.
    lo, h = -60.0, 0.005
    total, prev, t = 0.0, math.exp(output_log_density([lo], data, lam, eps)), lo
    checks = {-2.0: None, -0.5: None, 0.0: None, 0.5: None, 2.0: None}
    while t < 2.0 - 1e-12:
        t += h
        cur = math.exp(output_log_density([t], data, lam, eps))
        total += (prev + cur) * h / 2
        prev = cur
        for key in checks:
            if abs(t - key) < h / 2:
                checks[key] = total
    for key, value in checks.items():
        assert value == pytest.approx(exact_cdf(key), abs=1e-3)
    # The sampler matches the exact law.
    m = 2000
    samples = [objective_perturbation(data, lam, eps, rng)[0] for _ in range(m)]
    margin = dpkit.hoeffding_margin(m, 1e-6)
    for key in checks:
        emp = sum(1 for s in samples if s <= key) / m
        assert abs(emp - exact_cdf(key)) <= margin


def test_jacobian_matches_finite_differences():
    rng = random.Random(7)
    data = random_data(4, 2, rng)
    f = [0.3, -0.2]
    a = jacobian_matrix(f, data, 0.4, 0.1)
    h = 1e-6
    for j in range(2):
        fp = list(f)
        fp[j] += h
        fm = list(f)
        fm[j] -= h
        col = [(u - v) / (2 * h) for u, v in zip(noise_of(fp, data, 0.4, 0.1), noise_of(fm, data, 0.4, 0.1))]
        for i in range(2):
            assert -col[i] == pytest.approx(a[i][j], abs=1e-5)

History

Chaudhuri and Monteleoni (NIPS 2008) studied private logistic regression. They bounded the sensitivity of the regularized minimizer for output perturbation, and they introduced objective perturbation as a new method with better accuracy. Chaudhuri, Monteleoni and Sarwate (JMLR 2011) extended it to convex losses with a bounded second derivative, added the extra regularizer Δ\Delta for small nΛn\Lambda, gave a private method to tune Λ\Lambda, extended it to kernels, and compared both methods on real data. Kifer, Smith and Thakurta (2012) extended it to constraints and to Gaussian noise.

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 2 (Section 3.2) and Theorem 9 (its privacy, with Lemma 10 on the determinant), the logistic loss with c = 1/4, and the comparison with Algorithm 1
  2. Kamalika Chaudhuri and Claire Monteleoni, Privacy-preserving logistic regression, Advances in Neural Information Processing Systems 21 (NIPS 2008), the new method that perturbs the objective of regularized logistic regression

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
  • at least three sources
  • a scene preset for the example