Algorithm Search⌘K

Algorithmresearch

Private aggregation of teacher ensembles

Also called PATE.

Trains teachers on disjoint data, labels public data by a noisy vote among them, and trains a student model on those labels.

Time
O(n d + Q k m d) worst
Space
O(k m d) extra
Where
Q = the number of public queries; d = the dimension; k = the number of teachers; m = the number of classes; n = the number of private examples
Properties
randomizedrandomized
Origin
Nicolas Papernot, Martín Abadi, ��lfar Erlingsson, Ian Goodfellow, Kunal Talwar, 2017

Private aggregation of teacher ensembles (PATE) trains a model on private labeled data without the model ever seeing that data. The private data is split into kk disjoint parts, and a teacher model is trained on each part. A student model then learns from public unlabeled data: each public point is labeled by a vote of the teachers, with Laplace noise added to the vote counts. Changing one private example changes only one teacher and so moves at most one vote, which makes each noisy label 2γ2\gamma-differentially private for the noise scale 1/γ1/\gamma. The student sees only the public points and the noisy labels, so it is private by post-processing. Papernot, Abadi, Erlingsson, Goodfellow and Talwar (2017) introduced it. It is an instance of subsample and aggregate with report noisy max as the aggregator.

In plain words

Split the private data into many small piles, and train one teacher on each pile. No teacher has seen more than its own pile.

Then take public examples that have no labels. For each one, ask all teachers for a label and count the votes. Add some random noise to the counts, and use the winner as the label. When most teachers agree, the noise rarely changes the winner.

Any one person's data is in one pile only, so it can change at most one vote. The noise hides one vote. Finally a student model learns from the public examples and their noisy labels, and only the student is published.

The problem

The private data is a sequence DD of nn labeled examples with labels in {0,…,m−1}\{0, \ldots, m - 1\}. A public set of unlabeled points x1,…,xQx_1, \ldots, x_Q from a similar distribution is also available, and it is fixed before the run. The neighbor relation is replace: one private example changes, at the same position. The goal is a classifier that is ε\varepsilon-DP with respect to the private data and is accurate on new points.

The algorithm

  1. PATE(D, x_1..x_Q, k, gamma)
  2. 1split D into k disjoint parts: example i goes to part i mod k
  3. 2train teacher j on part j, for j = 0..k-1
  4. 3for t = 1 to Q do
  5. 4n_c <- the number of teachers that predict class c at x_t, for each class c
  6. 5label_t <- argmax over c of (n_c + Lap(1/gamma)) ▷ LNMax
  7. 6train the student on (x_1, label_1), ..., (x_Q, label_Q)
  8. 7return the student

Line L1 splits the data by a rule that does not look at the data, so each example is in exactly one part. Line L2 trains the teachers with any non-private method; in the paper they are deep networks, and in the code they are nearest-centroid classifiers. Line L4 counts the votes at one public point. Line L5 is the Laplace noisy max (LNMax) of the paper: add independent Laplace noise of scale 1/γ1/\gamma to each count and take the largest. The code draws each Laplace value as the difference of two exponential draws. Line L6 trains the student on public data only; the paper uses semi-supervised learning to make use of the public points that it does not query. Only the student of line L7 is released, never the teachers.

The code uses floats and a seeded generator, so it shows the algorithm but is not a safe deployment. Floating-point Laplace samplers can leak (Mironov 2012). A deployment needs a cryptographic source of randomness and exact samplers, such as the discrete Gaussian for the Gaussian version.

Example

Take n=20n = 20 private points in the plane, ten of class 0 near (−1,0)(-1, 0) and ten of class 1 near (1,0)(1, 0), in alternate order. With k=5k = 5, each teacher gets two points of each class and stores the two class means.

teacher mean of class 0 mean of class 1
0 (-0.85, 0.15) (1.05, -0.15)
1 (-0.75, 0.15) (0.85, 0.05)
2 (-1.05, 0) (0.7, 0.15)
3 (-1.15, 0) (1.1, 0)
4 (-1.1, -0.15) (1.15, 0.1)

Three public points get votes and noisy labels with γ=0.5\gamma = 0.5, so each answer is 11-DP. The probability of class 0 is exact, from the noisy max law; the label is the draw of the code with the seed 2.

public point votes (class 0, class 1) P(label 0) label
(-0.5, 0) (5, 0) 0.9077 0
(0.02, 0) (3, 2) 0.6209 0
(0.9, 0) (0, 5) 0.0923 1

The student stores the class means of the labeled public points: (−0.24,0)(-0.24, 0) for class 0 and (0.9,0)(0.9, 0) for class 1. The three labels are 33-DP by basic composition. When the teachers agree, the noisy label is right with high probability; when they split 3 to 2, the noise often flips the label. With the seeds 4 and 5, the code labels the middle point 1.

For the paper, basic composition gives 2γQ=0.1⋅100=102\gamma Q = 0.1 \cdot 100 = 10 for the MNIST student with 100 queries and γ=0.05\gamma = 0.05. The paper reports (2.04,10−5)(2.04, 10^{-5}) for it, with an accuracy of 98.00%, from its data-dependent accountant. For SVHN with 1000 queries, the bounds are 100100 and (8.19,10−6)(8.19, 10^{-6}), with 90.66%.

Correctness

Theorem (privacy). Under replace, the QQ labels are 2γQ2\gamma Q-DP, and so is the student.

The proof has three steps. First, the split of line L1 does not depend on the data, so a changed example changes one part and one teacher. Second, so at every public point at most one vote moves from one class to another, and every count changes by at most 1. Third, for report noisy max with Lap(1/γ)\mathrm{Lap}(1/\gamma) noise, a change of at most 1 in every count changes the probability of each winner by at most e2γe^{2\gamma}. The QQ answers use independent noise, so the factors multiply, and the student is post-processing. The correctness proof of this page gives all the steps and shows that the factor 2γ2\gamma is reached in the limit.

What the paper proves in addition. Papernot et al. use the moments accountant with a bound that depends on the vote counts. When the teachers agree strongly, a query costs much less than 2γ2\gamma. That bound is computed from the private votes, so its value is itself private; the theorem above does not cover the release of that number. The tests check the vote counts against an independent oracle, the noisy max law against a closed form with two classes, the sampler against that law, and the bound 2γ2\gamma for moved votes.

Proof: PATE with the Laplace noisy max is 2 gamma Q-DPfull

The private data is a sequence D=(e1,…,en)D = (e_1, \ldots, e_n) of labeled examples with labels in {0,…,m−1}\{0, \ldots, m - 1\}. The neighbor relation is replace: D′D' has a different example at one position ii, and the same examples at all other positions. The public points x1,…,xQx_1, \ldots, x_Q are fixed before the run and do not depend on DD. The training rule of a teacher is any deterministic function from a sequence of examples to a classifier. Line L1 puts example ii into part i mod ki \bmod k, and line L2 trains teacher jj on part jj. For a point xx, nc(x)n_c(x) is the number of teachers that predict the class cc. Line L5 outputs arg⁡max⁡c(nc(x)+Zc)\arg\max_c (n_c(x) + Z_c), where Z0,…,Zm−1Z_0, \ldots, Z_{m-1} are independent Lap(1/γ)\mathrm{Lap}(1/\gamma) variables. Ties among the noisy counts have probability zero, since the ZcZ_c have densities.

Lemma 1 (one teacher changes). If DD and D′D' differ at position ii, then the parts of lines L1 differ only in part i mod ki \bmod k, and only teacher i mod ki \bmod k can change.

Proof. The part of each position depends only on the position, not on the data. So every part j≠i mod kj \ne i \bmod k holds the same examples in the same order under DD and D′D', and line L2 trains the same teacher on it. □\square

Lemma 2 (one vote moves). For every xx, the vote vectors n(x)n(x) under DD and n′(x)n'(x) under D′D' satisfy n′=nn' = n or n′=n−ea+ebn' = n - \mathbf e_a + \mathbf e_b for two classes a≠ba \ne b. In both cases ∣nc−nc′∣≤1|n_c - n'_c| \le 1 for every cc.

Proof. By Lemma 1 one teacher can change its prediction at xx, from aa to bb. All other votes stay. □\square

Lemma 3 (the Laplace tail). Let S(t)=Pr⁡[Z>t]S(t) = \Pr[Z > t] for Z∼Lap(1/γ)Z \sim \mathrm{Lap}(1/\gamma). For all tt and s≥0s \ge 0, S(t+s)≥e−γsS(t)S(t + s) \ge e^{-\gamma s} S(t).

Proof. S(t)=12e−γtS(t) = \tfrac12 e^{-\gamma t} for t≥0t \ge 0 and S(t)=1−12eγtS(t) = 1 - \tfrac12 e^{\gamma t} for t<0t < 0. The function g=−ln⁡Sg = -\ln S is differentiable. For t>0t > 0, g′(t)=γg'(t) = \gamma. For t<0t < 0, g′(t)=γ 12eγt/(1−12eγt)≤γg'(t) = \gamma\,\tfrac12 e^{\gamma t}/(1 - \tfrac12 e^{\gamma t}) \le \gamma, since 12eγt≤12≤1−12eγt\tfrac12 e^{\gamma t} \le \tfrac12 \le 1 - \tfrac12 e^{\gamma t}. So g(t+s)−g(t)≤γsg(t + s) - g(t) \le \gamma s. □\square

Lemma 4 (one answer). If ∣nc−nc′∣≤1|n_c - n'_c| \le 1 for all cc, then for every class cc,

Pr⁡[L5 outputs c on n]≤e2γPr⁡[L5 outputs c on n′].\Pr[\text{L5 outputs } c \text{ on } n] \le e^{2\gamma}\Pr[\text{L5 outputs } c \text{ on } n'].

Proof. Fix cc and fix the values zjz_j of the other noises ZjZ_j, j≠cj \ne c. Let M=max⁡j≠c(nj+zj)M = \max_{j \ne c}(n_j + z_j) and M′=max⁡j≠c(nj′+zj)M' = \max_{j \ne c}(n'_j + z_j); then ∣M−M′∣≤1|M - M'| \le 1. Up to an event of probability zero, cc wins on nn exactly when Zc>t=M−ncZ_c > t = M - n_c, and on n′n' exactly when Zc>t′=M′−nc′Z_c > t' = M' - n'_c. Now t′≤t+2t' \le t + 2, so by Lemma 3 and since SS is decreasing,

S(t′)≥S(t+2)≥e−2γS(t).S(t') \ge S(t + 2) \ge e^{-2\gamma} S(t).

ZcZ_c is independent of the other noises, so taking the expectation over them gives Pr⁡[c on n′]≥e−2γPr⁡[c on n]\Pr[c \text{ on } n'] \ge e^{-2\gamma}\Pr[c \text{ on } n]. □\square

Theorem (privacy). The labels of lines L3 to L5 for QQ public points are 2γQ2\gamma Q-DP under replace, and so is the student of line L6.

Proof. Fix the data DD and the public points. The QQ answers use independent noise, so the probability of a label sequence (c1,…,cQ)(c_1, \ldots, c_Q) is the product of the QQ answer probabilities. By Lemma 2 each vote vector moves by at most one vote between DD and D′D', and Lemma 4 bounds each factor by e2γe^{2\gamma}. So the probability of every label sequence changes by at most the factor e2γQe^{2\gamma Q}, and summing over the sequences in an event gives the claim. Line L6 is a function of the public points and the labels only, so the student is 2γQ2\gamma Q-DP by the post-processing theorem. □\square

Tightness. With m=2m = 2, let the votes be (0,v)(0, v) under DD and (1,v−1)(1, v - 1) under D′D'. Class 0 wins when Z1−Z0<n0−n1Z_1 - Z_0 < n_0 - n_1, and Pr⁡[Z1−Z0<−t]=12e−γt(1+γt/2)\Pr[Z_1 - Z_0 < -t] = \tfrac12 e^{-\gamma t}(1 + \gamma t/2) for t≥0t \ge 0. The ratio of this at t=v−2t = v - 2 and at t=vt = v tends to e2γe^{2\gamma} as vv grows. So the factor 2γ2\gamma of Lemma 4 cannot be lowered in general.

What is not proved here. The bound 2γQ2\gamma Q is a worst case over all data sets. Papernot et al. use the moments accountant with a bound that depends on the vote counts, which is much smaller when the teachers agree. That bound is a function of the private data, so publishing its value is not covered by the theorem above. The proof does not say anything about the accuracy of the student. The code samples from floats, so it follows the analysis only up to floating-point effects. ■\blacksquare

Complexity

The model is the real RAM, with one exponential draw counted as O(1)O(1). The costs are for the nearest-centroid teachers of the code.

  • Teachers. Lines L1 and L2 cost O(nd)O(nd), since each example is used by one teacher.
  • Queries. Line L4 costs O(kmd)O(kmd) for one point and line L5 costs O(m)O(m), so the QQ queries cost O(Qkmd)O(Qkmd).
  • Student. Line L6 costs O(Qd)O(Qd).
  • Space. The teachers take O(kmd)O(kmd).

With deep networks the cost is that of training kk models on n/kn/k examples each, plus QkQk predictions.

Properties

  • Any learner. The privacy proof treats the teachers as black boxes. They need not be convex or even trained by a known method, as long as each sees only its own part.
  • Privacy does not depend on nn. The bound 2γQ2\gamma Q is the same for every nn and kk. More data helps only accuracy: more teachers make the votes larger, so the same noise flips fewer labels.
  • The cost grows with the number of queries. Each label costs privacy, so the student should learn from few labels. This is why the paper uses semi-supervised learning for the student.
  • Needs public data. PATE needs unlabeled public data from a distribution close to the private one. Without it, the method does not apply.
  • Strong agreement is cheap. In the data-dependent analysis, a query where almost all teachers agree costs much less than 2γ2\gamma. This is the regime where PATE works well.

Variants and improvements

  • Gaussian noisy max (GNMax). Papernot et al. (2018) add Gaussian noise to the counts. With Renyi DP accounting this gives smaller ε\varepsilon for many queries.
  • Confident GNMax. The same paper first checks, with noise, whether the largest count is above a threshold, and answers only those queries. Queries where the teachers disagree are skipped, so they cost little privacy.
  • Other students. Any learner can be the student, including knowledge distillation of soft labels, as long as it uses only the public points and the noisy labels.

When to use it

Use PATE when the model is a classifier, public unlabeled data from a similar distribution is available, and the private data is large enough to train many good teachers. It is a good choice when the teachers must be trained by methods that are hard to make private, since they need no private training. When there is no public data, or when the task is not classification, use DP-SGD instead.

Pitfalls

  • A data-dependent split. Line L1 with parts chosen by clustering or by the labels lets one example move many others between parts. Line L1 must use a fixed rule, such as the position or a random assignment made before the data is seen.
  • Positions under add/remove. Line L1 by position i mod ki \bmod k protects only under replace: removing one example shifts every later example to another part. Under add/remove, line L1 must assign each example by a key that does not change, such as a random draw or a hash of its identifier.
  • Counting gamma per answer. The budget for line L5 counted as γ\gamma per answer, as for report noisy max on counting queries under add/remove, is too small here: a moved vote lowers one count and raises another. Count 2γ2\gamma for each answer of line L5.
  • Releasing the votes. Line L5 that also returns the noisy counts, or line L7 that releases the teachers, is not covered by the theorem. Only the winning label of line L5 and the student of line L7 may leave.
  • Publishing the data-dependent epsilon. A report of the ε\varepsilon from the vote counts after line L5 uses the private data. Publish the worst-case bound, or a private version of the data-dependent one.
  • Too many queries. Line L3 run over all public points makes the bound 2γQ2\gamma Q large. Query few points, and let line L6 use the rest without labels.

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
pate.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pate/. The authors are listed in prov/7WDT5Q.jsonl.
"""Private aggregation of teacher ensembles (PATE) with the Laplace noisy max (LNMax).

The private data is split into k disjoint parts by position, and one teacher
is trained on each part. Each public query point gets the label that wins a
vote of the teachers after Laplace noise of scale 1/gamma is added to each
vote count. A student is trained on the public points and the noisy labels.

Under replace neighbors (one private example changed, at the same position),
one teacher changes, so each answer is 2 gamma-DP and Q answers are
2 gamma Q-DP by basic composition. The student is post-processing.

The teachers and the student are nearest-centroid classifiers, so that the
code needs no library. 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 Optional, Sequence

Point = Sequence[float]
Example = tuple[Point, int]
Model = list[Optional[list[float]]]  # one centroid per class, or None for a class with no example


def split(data: Sequence[Example], k: int) -> list[list[Example]]:
    """The k disjoint parts: example i goes to part i mod k. Cost: O(n)."""
    parts: list[list[Example]] = [[] for _ in range(k)]
    for i, example in enumerate(data):
        parts[i % k].append(example)
    return parts


def train_centroids(examples: Sequence[Example], classes: int) -> Model:
    """The mean point of each class. Cost: O(n d)."""
    sums: list[Optional[list[float]]] = [None] * classes
    counts = [0] * classes
    for x, y in examples:
        if sums[y] is None:
            sums[y] = [0.0] * len(x)
        s = sums[y]
        for j, xj in enumerate(x):
            s[j] += xj
        counts[y] += 1
    return [None if s is None else [v / counts[c] for v in s] for c, s in enumerate(sums)]


def predict(model: Model, x: Point) -> int:
    """The class of the nearest centroid; ties go to the smaller class, and an empty model says 0. Cost: O(m d)."""
    best, best_d = 0, math.inf
    for c, centre in enumerate(model):
        if centre is None:
            continue
        dist = sum((a - b) ** 2 for a, b in zip(x, centre))
        if dist < best_d:
            best, best_d = c, dist
    return best


def vote_counts(teachers: Sequence[Model], x: Point, classes: int) -> list[int]:
    """The number of teachers that predict each class at x. Cost: O(k m d)."""
    counts = [0] * classes
    for t in teachers:
        counts[predict(t, x)] += 1
    return counts


def laplace(scale: float, rng: random.Random) -> float:
    """A Laplace(0, scale) draw, as the difference of two exponential draws."""
    return rng.expovariate(1 / scale) - rng.expovariate(1 / scale)


def noisy_max(counts: Sequence[int], gamma: float, rng: random.Random) -> int:
    """argmax_c (counts[c] + Lap(1/gamma)). Ties have probability 0. Cost: O(m)."""
    noisy = [n + laplace(1 / gamma, rng) for n in counts]
    return max(range(len(noisy)), key=lambda c: noisy[c])


def pate(private: Sequence[Example], public: Sequence[Point], k: int, classes: int,
         gamma: float, rng: random.Random) -> tuple[Model, list[int]]:
    """The student model and the noisy labels of the public points.

    Precondition: k >= 1, gamma > 0, labels in range(classes).
    Privacy: 2 gamma len(public)-DP under replace neighbors on the private data.
    Cost: O(n d) to train the teachers, O(k m d) per query, O(Q d) for the student.
    """
    if k < 1 or gamma <= 0:
        raise ValueError("need k >= 1 and gamma > 0")
    if any(not 0 <= y < classes for _, y in private):
        raise ValueError("labels must be in range(classes)")
    parts = split(private, k)  # @line L1
    teachers = [train_centroids(part, classes) for part in parts]  # @line L2
    labels: list[int] = []
    for x in public:  # @line L3
        counts = vote_counts(teachers, x, classes)  # @line L4
        labels.append(noisy_max(counts, gamma, rng))  # @line L5
    student = train_centroids(list(zip(public, labels)), classes)  # @line L6
    return student, labels  # @line L7


def basic_epsilon(gamma: float, queries: int) -> float:
    """The privacy of the labels by basic composition: 2 gamma per answer."""
    return 2 * gamma * queries


def _laplace_pdf(z: float, gamma: float) -> float:
    return gamma / 2 * math.exp(-gamma * abs(z))


def _laplace_cdf(z: float, gamma: float) -> float:
    return 0.5 * math.exp(gamma * z) if z < 0 else 1 - 0.5 * math.exp(-gamma * z)


def noisy_max_pmf(counts: Sequence[int], gamma: float, per_unit: int = 20) -> list[float]:
    """The probability that each class wins the noisy vote, by numerical integration.

    P(c wins) = integral of pdf(z - n_c) prod_{j != c} cdf(z - n_j) dz. The
    integrand is smooth between the counts, so composite Simpson is used on
    each piece between them, and on tails of width 30 / gamma, whose outer
    mass is below e^(-30). Each piece gets at least per_unit steps per length
    1 / gamma. Cost: O(m^2 (m + gamma max_count + 30) per_unit).
    """
    knots = sorted(set(counts))
    lo, hi = knots[0] - 30 / gamma, knots[-1] + 30 / gamma
    points = [lo] + knots + [hi]
    out = []
    for c, nc in enumerate(counts):
        def g(z: float) -> float:
            v = _laplace_pdf(z - nc, gamma)
            for j, nj in enumerate(counts):
                if j != c:
                    v *= _laplace_cdf(z - nj, gamma)
            return v

        total = 0.0
        for a, b in zip(points, points[1:]):
            if b <= a:
                continue
            pieces = 2 * max(10, math.ceil((b - a) * gamma * per_unit / 2))
            h = (b - a) / pieces
            s = g(a) + g(b)
            for i in range(1, pieces):
                s += (4 if i % 2 else 2) * g(a + i * h)
            total += s * h / 3
        out.append(total)
    return out
test_pate.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pate/. The authors are listed in prov/7WDT5Q.jsonl.

import math
import random

import pytest

import dpkit
from pate import (
    basic_epsilon,
    noisy_max,
    noisy_max_pmf,
    pate,
    predict,
    split,
    train_centroids,
    vote_counts,
)

CLASS_0 = [(-1.0, 0.2), (-0.8, -0.1), (-1.2, 0.0), (-0.9, 0.3), (-1.1, -0.2),
           (-0.7, 0.1), (-1.3, 0.1), (-1.0, -0.3), (-0.6, 0.0), (-1.2, 0.2)]
CLASS_1 = [(1.0, 0.1), (0.9, -0.2), (1.1, 0.0), (0.8, 0.2), (1.2, -0.1),
           (0.7, 0.0), (1.3, 0.2), (1.0, -0.3), (0.6, 0.1), (1.1, 0.3)]
PRIVATE = [e for a, b in zip(CLASS_0, CLASS_1) for e in ((a, 0), (b, 1))]
PUBLIC = [(-0.5, 0.0), (0.02, 0.0), (0.9, 0.0)]


def test_check_values():
    teachers = [train_centroids(p, 2) for p in split(PRIVATE, 5)]
    assert [vote_counts(teachers, x, 2) for x in PUBLIC] == [[5, 0], [3, 2], [0, 5]]
    p = noisy_max_pmf([5, 0], 0.5)
    assert p[0] == pytest.approx(0.907654, abs=1e-6)
    assert noisy_max_pmf([3, 2], 0.5)[0] == pytest.approx(0.620918, abs=1e-6)
    student, labels = pate(PRIVATE, PUBLIC, 5, 2, 0.5, random.Random(2))
    assert labels == [0, 0, 1]
    assert student[0] == pytest.approx([-0.24, 0.0]) and student[1] == pytest.approx([0.9, 0.0])
    assert basic_epsilon(0.5, 3) == 3.0
    assert basic_epsilon(0.05, 100) == pytest.approx(10.0)


def test_bad_input():
    with pytest.raises(ValueError):
        pate(PRIVATE, PUBLIC, 0, 2, 0.5, random.Random(0))
    with pytest.raises(ValueError):
        pate([((0.0,), 3)], PUBLIC, 1, 2, 0.5, random.Random(0))


def random_data(n, d, classes, rng):
    return [(tuple(rng.uniform(-1, 1) for _ in range(d)), rng.randrange(classes)) for _ in range(n)]


def oracle_votes(data, k, x, classes):
    """Independent oracle: rebuild each teacher from the indices and rank (distance, class) pairs."""
    votes = [0] * classes
    for j in range(k):
        mine = [data[i] for i in range(j, len(data), k)]
        options = []
        for c in range(classes):
            pts = [p for p, y in mine if y == c]
            if pts:
                centre = [sum(col) / len(pts) for col in zip(*pts)]
                options.append((sum((a - b) ** 2 for a, b in zip(x, centre)), c))
        votes[min(options)[1] if options else 0] += 1
    return votes


def test_votes_against_oracle():
    rng = random.Random(1)
    for _ in range(500):
        n = rng.randint(1, 20)
        d = rng.randint(1, 3)
        classes = rng.randint(2, 3)
        k = rng.randint(1, 5)
        data = random_data(n, d, classes, rng)
        x = tuple(rng.uniform(-1, 1) for _ in range(d))
        teachers = [train_centroids(p, classes) for p in split(data, k)]
        assert vote_counts(teachers, x, classes) == oracle_votes(data, k, x, classes)


def two_class_win(n0, n1, gamma):
    """Closed form: class 0 wins when L1 - L0 < n0 - n1, and L1 - L0 has P(> t) = e^(-gamma t)(1 + gamma t / 2) / 2."""
    t = n0 - n1
    if t >= 0:
        return 1 - 0.5 * math.exp(-gamma * t) * (1 + gamma * t / 2)
    return 0.5 * math.exp(gamma * t) * (1 - gamma * t / 2)


def test_pmf_against_closed_form():
    rng = random.Random(2)
    for _ in range(500):
        n0, n1 = rng.randint(0, 8), rng.randint(0, 8)
        gamma = rng.uniform(0.05, 2.0)
        p = noisy_max_pmf([n0, n1], gamma)
        assert p[0] == pytest.approx(two_class_win(n0, n1, gamma), abs=1e-6)
        assert p[0] + p[1] == pytest.approx(1.0, abs=1e-6)


def test_sampler_against_pmf():
    rng = random.Random(3)
    m = 2000
    margin = dpkit.hoeffding_margin(m, 1e-6)
    for counts, gamma in (([4, 3, 1], 0.5), ([2, 2, 4], 1.0)):
        p = noisy_max_pmf(counts, gamma)
        assert sum(p) == pytest.approx(1.0, abs=1e-6)
        emp = dpkit.empirical_pmf(noisy_max(counts, gamma, rng) for _ in range(m))
        for c in range(3):
            assert abs(emp.get(c, 0.0) - p[c]) <= margin


def test_one_moved_vote_costs_at_most_two_gamma():
    rng = random.Random(4)
    worst = 0.0
    for _ in range(40):
        k = rng.randint(1, 6)
        gamma = rng.uniform(0.1, 1.0)
        counts = [0, 0, 0]
        for _ in range(k):
            counts[rng.randrange(3)] += 1
        a = rng.choice([c for c in range(3) if counts[c] > 0])
        b = rng.choice([c for c in range(3) if c != a])
        moved = list(counts)
        moved[a] -= 1
        moved[b] += 1
        p = dict(enumerate(noisy_max_pmf(counts, gamma)))
        q = dict(enumerate(noisy_max_pmf(moved, gamma)))
        loss = max(dpkit.max_privacy_loss(p, q), dpkit.max_privacy_loss(q, p))
        assert loss <= 2 * gamma + 1e-5
        worst = max(worst, loss / (2 * gamma))
    assert worst > 0.5
    # With two classes and a large lead the bound 2 gamma is nearly reached.
    p = two_class_win(0, 30, 0.5)
    q = two_class_win(1, 29, 0.5)
    assert 0.9 * 2 * 0.5 < math.log(q / p) <= 2 * 0.5


def test_replacing_one_example_changes_one_teacher():
    rng = random.Random(5)
    for _ in range(200):
        n = rng.randint(1, 20)
        k = rng.randint(1, 5)
        data = random_data(n, 2, 3, rng)
        other = list(data)
        i = rng.randrange(n)
        other[i] = (tuple(rng.uniform(-1, 1) for _ in range(2)), rng.randrange(3))
        t1 = [train_centroids(p, 3) for p in split(data, k)]
        t2 = [train_centroids(p, 3) for p in split(other, k)]
        assert all(t1[j] == t2[j] for j in range(k) if j != i % k)
        x = (rng.uniform(-1, 1), rng.uniform(-1, 1))
        v1, v2 = vote_counts(t1, x, 3), vote_counts(t2, x, 3)
        assert sum(abs(a - b) for a, b in zip(v1, v2)) <= 2


def test_predict_tie_and_empty():
    assert predict([None, None], (0.0,)) == 0
    assert predict([[1.0], [-1.0]], (0.0,)) == 0
    assert predict([None, [0.5]], (0.0,)) == 1

History

Hamm, Cao and Belkin (ICML 2016) trained local classifiers on separate private data sets and transferred their votes to a global classifier on public data. Papernot, Abadi, Erlingsson, Goodfellow and Talwar (ICLR 2017) introduced PATE: deep network teachers on disjoint parts, the Laplace noisy max, a data-dependent moments accountant, and a student trained by semi-supervised learning with generative adversarial networks. They reported single-digit ε\varepsilon on MNIST and SVHN. Papernot, Song, Mironov, Raghunathan, Talwar and Erlingsson (ICLR 2018) scaled PATE to more classes with the Gaussian noisy max and the confident aggregator.

References

  1. Nicolas Papernot, Martín Abadi, Úlfar Erlingsson, Ian Goodfellow and Kunal Talwar, Semi-supervised knowledge transfer for deep learning from private training data, ICLR 2017, the noisy aggregation mechanism of equation (1) in Section 2.1, and the results with 250 teachers and Laplace noise of scale 20 on MNIST and SVHN
  2. Nicolas Papernot, Shuang Song, Ilya Mironov, Ananth Raghunathan, Kunal Talwar and Úlfar Erlingsson, Scalable private learning with PATE, ICLR 2018, the Gaussian noisy max (GNMax) and the Confident GNMax aggregator

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