Differential Privacy for Machine Learning Practitioners
Differential privacy (DP) is the rare privacy concept with a precise mathematical definition rather than a vague promise. Intuitively, a mechanism is differentially private if the presence or absence of any single individual's data cannot be reliably determined from the output โ a formal guarantee that survives attacks researchers have not yet invented. For machine learning, the practical form is DP-SGD: training with per-example gradient clipping and calibrated Gaussian noise so the resulting model weights reveal little about any training example.
This lesson builds from the definition to the algorithm. You will understand what epsilon and delta actually quantify, implement DP-SGD from the clipping/noise primitives upward, apply RDP-based privacy accounting to convert training hyperparameters into a cumulative privacy budget, and learn where DP fits โ and where simpler tools like aggregation and access control are the better choice.
What You'll Learn
- 1Explain the (epsilon, delta)-DP definition and interpret the budget numbers that appear in papers and audits
- 2Implement per-example gradient clipping and Gaussian noise for DP-SGD
- 3Use RDP accounting to compute the privacy budget consumed by a training run
- 4Recognize when DP is the right tool versus access control, aggregation, or federated learning
Prerequisites
- !Gradient descent and backpropagation
- !Basic probability: Gaussians, expectation, independence
- !PyTorch or similar tensor library familiarity
The definition, built from a story
Fix a dataset D and a neighboring dataset D' that differs in exactly one person's record (the "add/remove" adjacency). A randomized mechanism M is (epsilon, delta)-differentially private if, for every set of outputs S:
Pr[M(D) in S] <= exp(epsilon) * Pr[M(D') in S] + delta
Read the inequality operationally. With delta = 0, the odds of any outcome under D versus D' differ by at most a factor of exp(epsilon) โ a small epsilon forces the two distributions to nearly coincide, so no analyst can tell whether one particular person was in the training set. delta relaxes this to allow a small probability mass where the guarantee fails; it is conventionally set far below 1/N (the probability of singling out one person by chance), often 1e-5 or 1e-7.
Epsilon is a budget, not a dial with universal calibration. Common interpretations: epsilon below 1 is strong privacy; 1โ8 is typical for published DP systems (the 2020 US Census used epsilon around 2โ19 across products); above 20 the formal guarantee is weak even if empirical privacy may remain. Crucially, epsilons compose โ running two mechanisms at epsilon 2 each yields total budget around 4 (advanced composition does better, but the budget only grows).
| Epsilon | Formal strength | Typical use |
|---|---|---|
| 0.1 โ 1 | Very strong | High-sensitivity health data, heavy audit scrutiny |
| 1 โ 4 | Strong, usable | Consumer apps, census-style releases, DP training papers |
| 4 โ 10 | Moderate | Internal analytics, lower-sensitivity datasets |
| 10+ | Weak formal guarantee | Treat as empirical protection only, or re-tune |
The threat model: membership inference and memorization
Before reaching for an epsilon, name the attack you are defending against. The canonical one is membership inference: given the released model or statistics, decide whether a specific person's record was in the training set. Models that memorize rare training examples โ over-parameterized networks trained with small batches and no regularization โ leak membership through confidence gaps: a training example is classified with higher confidence than a held-out lookalike. DP-SGD counters this by bounding each example's influence through clipping and drowning residual signal in calibrated noise, which shrinks exactly the confidence gap attackers exploit.
A second threat is extraction: querying the model to reconstruct training data or the decision boundary itself. DP bounds the influence any single query can have on what an attacker learns, though it does not prevent the model from revealing patterns that were common in the training distribution โ that generalization is usually the product's purpose. A third, often overlooked threat is the release of intermediate artifacts: checkpoints logged every epoch, gradients uploaded for federated aggregation, or hyperparameter-search traces. Each release consumes privacy budget; the accountant must cover every artifact that leaves the trusted boundary, not just the final weights.
Writing the threat model down before selecting epsilon forces an honest conversation about what is in scope, who the adversary is, and which artifacts are released. Without it, epsilon becomes a number chosen to match a paper rather than a defense matched to an adversary.
DP-SGD: clipping and noise at the gradient step
Standard SGD averages per-example gradients and steps. DP-SGD modifies the inner loop in two places. First, each example's gradient is clipped to a fixed L2 norm C, bounding any one person's influence on the update. Second, Gaussian noise with standard deviation C * sigma is added to the aggregated clipped gradient. The noise scale sigma and clip norm C are the privacy-relevant hyperparameters; learning rate and architecture are utility knobs.
import torch
import torch.nn as nn
class DPSGDStep:
"""One DP-SGD step: per-example clip + Gaussian noise + descent."""
def __init__(self, model, lr=0.1, clip_norm=1.0, noise_multiplier=1.1,
batch_size=256):
self.model = model
self.lr = lr
self.C = clip_norm
self.sigma = noise_multiplier
self.B = batch_size
self.optimizer = torch.optim.SGD(model.parameters(), lr=lr)
def _per_example_grads(self, loss):
"""Return gradients with a batch dimension: (B, ...) per parameter."""
grads = torch.autograd.grad(
loss, self.model.parameters(), retain_graph=False
)
# torch.autograd.grad sums over the batch; recompute per-example via
# the outer-product trick for a correct per-example gradient.
# For clarity here we approximate with vmap when available.
return grads
def step(self, x_batch, y_batch, criterion=nn.CrossEntropyLoss(reduction="none")):
self.optimizer.zero_grad()
outputs = self.model(x_batch)
per_example_loss = criterion(outputs, y_batch) # shape (B,)
# Per-example gradients via functorch (one call, batched)
from torch.func import grad, vmap
params = tuple(self.model.parameters())
def single_loss(params, xi, yi):
out = torch.func.functional_call(self.model, params, (xi.unsqueeze(0),))
return criterion(out, yi.unsqueeze(0)).squeeze(0)
pe_grads = vmap(grad(single_loss), in_dims=(None, 0, 0))(params, x_batch, y_batch)
clipped = []
for g in pe_grads:
flat = g.reshape(g.shape[0], -1)
norms = flat.norm(dim=1, keepdim=True).clamp(min=1e-12)
factors = (self.C / norms).clamp(max=1.0)
clipped.append((g * factors.reshape(g.shape[0], *([1] * (g.dim() - 1)))))
# Aggregate clipped grads, then add noise
noisy = []
for g in clipped:
agg = g.mean(dim=0)
noise = torch.randn_like(agg) * self.C * self.sigma / self.B
noisy.append(agg + noise)
for p, g in zip(self.model.parameters(), noisy):
p.grad = g
self.optimizer.step()
return per_example_loss.mean().item()
The division by batch size in the noise term matters: noise is added to the sum of clipped gradients, then the average is taken, so effective noise on the mean scales as C * sigma / B. Larger batches dilute noise and improve utility at equal privacy cost โ one reason DP training favors big batches.
Privacy accounting with RDP
Each step consumes a sliver of budget; RDP (Rรฉnyi Differential Privacy) accounting tracks how those slills compose into a final epsilon for a target delta. The opacus library provides the accountant:
from opacus.accountants import RDPAccountant
from opacus.accountants.utils import get_noise_multiplier
accountant = RDPAccountant()
noise_mult = 1.1
sample_rate = 0.01 # batch_size / dataset_size
steps = 10_000
for _ in range(steps):
accountant.step(noise_multiplier=noise_mult, sample_rate=sample_rate)
epsilon = accountant.get_epsilon(delta=1e-5)
print(f"eps={epsilon:.2f} after {steps} steps, delta=1e-5")
# Or solve for the noise needed to hit a budget target:
nm = get_noise_multiplier(target_epsilon=3.0, target_delta=1e-5,
sample_rate=sample_rate, steps=steps)
print(f"required noise_multiplier={nm:.3f}")
Two practical readings. First, for fixed sigma, epsilon grows roughly with sqrt(steps * sample_rate) โ more epochs cost budget sublinearly but they do cost. Second, sample_rate (batch size over dataset size) is a first-class privacy knob: doubling batch size at fixed epochs doubles steps' worth of composition but each step is cheaper; net effect usually favors larger batches. Always report epsilon and delta alongside accuracy โ a model without its budget is not a DP model.
Where DP helps and where it does not
DP-SGD is the right tool when the training set contains individual-level sensitive records and you will publish or broadly share the model โ health records, location traces, private messages, census microdata. It is overkill and often counterproductive for data you already have contractual rights to use internally, where access control, audit logging, and aggregation give stronger practical protection at zero utility cost.
DP does not fix all privacy failures. Membership inference against a non-DP model can succeed precisely because the model memorized rare examples; DP-SGD targets that memorization directly. But DP says nothing about secrets you deliberately encode (a model trained to detect a rare disease still "leaks" that the disease exists โ that is usually intended), and it does not protect against attacks on the serving infrastructure, logging layers, or user inputs at inference time.
| Situation | Better tool than DP |
|---|---|
| Internal analytics, strict access control | Aggregated SQL, RBAC, audit logs |
| Sharing summary statistics of a table | Laplace-mechanism DP (simpler than DP-SGD) |
| Federated learning across devices | FedAvg + secure aggregation (DP optional on top) |
| Publishing a model trained on sensitive rows | DP-SGD (this lesson) |
| Compliance checkbox with no threat model | Documented access control; DP without a budget target is theater |
Federated learning and DP compose well: local gradients never leave devices (reducing exposure), and server-side DP aggregation of updates adds the formal guarantee. That combination โ secure aggregation plus clipped, noised updates โ is the current best-practice pattern for keyboard-prediction-style models on phones.
Utility trade-offs and the practitioner's checklist
DP-SGD typically costs 1โ10% accuracy versus non-private training on easy benchmarks, and more on hard, small-data tasks where noise swamps signal. Mitigations that work in practice: pre-training on public data and fine-tuning with DP (the privacy cost only covers the fine-tuning set), large batches with strong clip-norm tuning, and per-layer or per-parameter clip norms where the default single C is too conservative.
Before claiming DP for a model, verify the checklist: (1) adjacency is defined at the right granularity (one person, not one row, if a person contributes multiple rows โ otherwise the bound is wrong); (2) delta is below 1/N; (3) epsilon was computed with an accountant for the actual training trajectory, including any hyperparameter search on private data (tuning consumes budget too); (4) the released artifact โ weights, gradients, checkpoints โ is exactly what the accountant covered; (5) the threat model is documented so auditors can see what is and is not in scope.
Common Mistakes
Reporting epsilon without delta or the adjacency definition
Fix: Always publish epsilon, delta, and whether adjacency is add/remove at the row or person level; epsilon alone is uninterpretable.
Ignoring privacy cost of hyperparameter search on private data
Fix: Tune on a public or already-private proxy set, or budget the search explicitly with the accountant alongside training steps.
Using row-level adjacency when users contribute many rows
Fix: Define adjacency at the person level and clip/group per person, or the formal bound does not match the real privacy unit.
Applying DP-SGD where access control and aggregation would suffice
Fix: Start with the threat model; DP is for releasing information about a dataset, not for protecting data you never release.
Best Practices
- Set a target epsilon before training and use RDP accounting to solve for noise_multiplier rather than tuning noise blindly
- Use large batches and clip-norm search; utilities are dominated by C and sigma, not learning rate alone
- Pre-train on public data and DP fine-tune on sensitive data to cut budget consumption dramatically
- Pair DP with secure aggregation in federated settings for defense in depth
- Document the adjacency unit, delta, and accountant method in the model card next to accuracy metrics
Interview Questions
Q1: What does epsilon quantify in differential privacy, and why is it a budget?
Epsilon bounds how much the output distribution can differ when one individual is added or removed โ smaller is stronger. It is a budget because multiple mechanisms compose additively (or better under advanced/RDP composition), so every query or training step spends privacy that cannot be reclaimed.
Q2: Why does DP-SGD clip per-example gradients before adding noise?
Clipping bounds each individual's maximum contribution to an update, which is what makes the sensitivity (and thus required noise) finite and calibrated. Without clipping, a single extreme example would force arbitrarily large noise to preserve the guarantee.
Q3: When would you choose federated learning plus DP over central DP-SGD alone?
When raw data must not leave user devices at all โ secure aggregation hides individual updates from the server, and clipped, noised updates add the formal DP guarantee. Central DP-SGD requires all data to be pooled, which may violate policy or regulation before privacy accounting even starts.
Key Takeaways
- (epsilon, delta)-DP formalizes 'one person's data barely changes the output'; epsilon is a composable budget, delta a failure probability set far below 1/N
- DP-SGD = per-example gradient clipping to norm C + Gaussian noise at scale Cยทsigma; batch size, C, and sigma are the privacy-utility levers
- RDP accounting converts a training trajectory into a final epsilon; report epsilon and delta with every claimed-private model
- DP is for releasing models or statistics about sensitive data โ access control, aggregation, and secure aggregation cover other threat models
- Practical wins: public pre-training + DP fine-tuning, large batches, clip-norm search, and person-level adjacency definitions