LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 196 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/31
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Parallel Primitives LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingGPU Runtime Execution LabAI-Generated Kernel EngineeringModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingGPU Failure OperationsDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnApplied LLM EngineeringPrivacy-Preserving Machine Learning
🛡️MediumAlignment & Safety

Privacy-Preserving Machine Learning

Define neighboring datasets and privacy budgets, implement protected-unit-aware clipping, distinguish DP-SGD from redaction, and audit membership leakage.

19 min read
Learning path
Step 68 of 196 in the full curriculum
Responsible AI GovernanceData Labeling and Human Feedback

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

An enterprise customer support copilot is in its final pre-launch security review. A red-team analyst enters a snippet from an internal troubleshooting ticket: "Incident 4092: Customer reported recurring billing error on...". The model immediately completes the sentence with an unmasked credit card tail, a personal home address, and an internal note recording that the customer entered psychiatric medical leave.

The engineering team is stunned. They ran regex scrubbers across the training corpus before fine-tuning. Names were stripped, and user identifiers were replaced with random hashes. Yet the model still reproduced the customer's private history verbatim.

Scrubbing explicit names leaves unique phrase combinations, rare tokens, and semantic correlations completely intact. Deep language models have billions of parameters; when an unusual sequence appears in training data, gradient descent fits it tightly. Redaction can't change that fundamental memorization dynamic.

Differential privacy frames this problem as a mathematical neighboring-dataset contract: if every single record contributed by one protected person vanished before training began, how much could the probability distribution of released model outputs change?[1]Reference 1Calibrating Noise to Sensitivity in Private Data Analysis.https://people.csail.mit.edu/asmith/PS/sensitivity-tcc-final.pdf[2]Reference 2The Algorithmic Foundations of Differential Privacy.https://www.microsoft.com/en-us/research/publication/algorithmic-foundations-differential-privacy/

Answering that question requires choosing the exact unit you promise to protect, bounding each unit's mathematical influence, injecting calibrated randomness, and tracking cumulative privacy loss across every released checkpoint.

We'll work within the central privacy model: a trusted infrastructure service accesses raw records to run training, but the released model weights and generated text must satisfy provable privacy bounds. Differential privacy doesn't replace database access controls or scrub internal logs. It establishes a formal limit on what an external observer can extract from the final system.

Why redaction fails against modern extraction attacks

Redaction treats privacy as a syntactic text-matching task. If a word matches an entity dictionary or regex pattern, you mask it. Real privacy attacks operate on semantic statistics and model capacity.

Modern privacy evaluation focuses on three primary attack vectors:

  1. Training data memorization and extraction: Overparameterized neural networks easily memorize rare or unique training sequences. Attackers probe models with targeted prompt prefixes, greedy decoding, or beam search to extract memorized strings verbatim. Security teams evaluate this vulnerability using canary insertion: inserting artificial secrets with controlled repetition counts rrr into the training data, then measuring how many exposures allow an attacker to reconstruct the secret. Without mathematical protection, models can memorize sequences seen only once or twice.
  2. Membership inference attacks (MIA): An adversary tests whether a known document xxx belonged to the training set DDD [3]Reference 3Membership Inference Attacks against Machine Learning Modelshttps://arxiv.org/abs/1610.05820. Because standard training minimizes empirical loss on training examples, the model exhibits systematically lower loss L(θ;x)\mathcal{L}(\theta; x)L(θ;x) and lower perplexity on members than on non-members. Attackers calibrate this signal by comparing the target model's loss to a public reference model's loss (Ltarget(x)−Lref(x)\mathcal{L}_{\text{target}}(x) - \mathcal{L}_{\text{ref}}(x)Ltarget​(x)−Lref​(x)) or zlib compression entropy. If the target model finds a sentence significantly more probable than the reference model does, it flags that record as training data.
  3. Attribute reconstruction: An attacker combines partial knowledge of a user's record with query access to the trained model to infer omitted sensitive fields, such as diagnostic codes or salary brackets.
Defense strategyWhat it actually establishesVulnerability left open
Regex name scrubbingRemoves specific known string tokensSyntactic masking misses unique context, rare phrases, and semantic fingerprints
Identifier hashingConverts persistent IDs into fixed pseudonymsPseudonyms remain linkable across records; correlations still leak
Passing membership testConfirms one tested attack failed on selected samplesGives an empirical lower bound; offers zero guarantee against future attacks
Differentially private trainingGuarantees bounded output distribution divergence under any neighboring changeTrades a quantified drop in training efficiency or raw utility for provable safety

A failed empirical attack doesn't prove that your model is secure. It only proves that the specific auditor, threshold, and feature set you tested couldn't separate members from non-members. Differential privacy provides a mathematical upper bound across all possible attacks, including adversaries with arbitrary background knowledge.

Why does a passing membership inference test fail to guarantee that a customer's support ticket can't be extracted?

Answer

An attack test only establishes an empirical lower bound on privacy leakage for one specific adversary, interface, and test split. It doesn't bound what a stronger adversary with better auxiliary data or different decoding strategies can extract. Differential privacy provides a worst-case mathematical bound over all possible adversaries.

Start with the unit you promise to protect

Before configuring an epsilon or tuning noise scales, write one concrete contract: "one protected unit is ___." Two datasets are neighbors when they differ by that single protected unit.

In enterprise support data, that unit might be one row, one conversation ticket, or one customer account.

Protected unitNeighboring dataset definitionOperational failure mode
RowRemove one training messageOne customer sent fifty messages across several tickets
ConversationRemove one multi-turn conversationA user participated in multiple support incidents over time
UserRemove every message and ticket from that userMissing identity tracking prevents bounding total user contributions

Suppose Alice submitted twelve support messages across three tickets. A row-level guarantee bounds what happens when one message is removed. A user-level guarantee bounds what happens when all twelve messages disappear simultaneously. That's the exact same corpus under two completely different neighboring relations, yielding two radically different privacy promises.

The definition also depends on the adjacency convention:

  • Add/remove adjacency: Neighbor D′D'D′ contains one fewer (or one additional) protected unit than DDD, so ∣DΔD′∣=1|D \Delta D'| = 1∣DΔD′∣=1. Dataset size changes by one.
  • Replace-one adjacency: Neighbor D′D'D′ replaces one protected unit's complete value with another arbitrary valid value, keeping total population size NNN fixed, so ∣DΔD′∣=2|D \Delta D'| = 2∣DΔD′∣=2.

Replacing a vector bounded in [−C,+C][-C, +C][−C,+C] can swing an aggregate sum from −C-C−C to +C+C+C, spanning a distance of 2C2C2C. Removing that vector only changes the sum by CCC. Replacing doubles the sensitivity bound compared to removal. You can't swap conventions without updating your sensitivity calculations.

Turn this into Cynthia Dwork's formal condition. For every possible output event S⊆Range(M)S \subseteq \text{Range}(M)S⊆Range(M), a randomized mechanism MMM satisfies (ε,δ)(\varepsilon,\delta)(ε,δ)-differential privacy if:[1]Reference 1Calibrating Noise to Sensitivity in Private Data Analysis.https://people.csail.mit.edu/asmith/PS/sensitivity-tcc-final.pdf[2]Reference 2The Algorithmic Foundations of Differential Privacy.https://www.microsoft.com/en-us/research/publication/algorithmic-foundations-differential-privacy/

P(M(D)∈S)≤eεP(M(D′)∈S)+δP(M(D) \in S) \le e^{\varepsilon} P(M(D') \in S) + \deltaP(M(D)∈S)≤eεP(M(D′)∈S)+δ

The probabilities reflect the internal randomness of mechanism MMM, not randomness in picking the training dataset. The condition must hold in both directions (DDD to D′D'D′ and D′D'D′ to DDD) for every neighboring pair and every measurable output event SSS.

Parameter ε\varepsilonε (epsilon) is the privacy budget. It sets a strict multiplicative ceiling on the log likelihood ratio an observer can gain about any individual's presence. When ε=0.5\varepsilon = 0.5ε=0.5, e0.5≈1.65e^{0.5} \approx 1.65e0.5≈1.65, meaning the odds of any model output can shift by at most 65%65\%65%. When ε=8.0\varepsilon = 8.0ε=8.0, e8.0≈2981e^{8.0} \approx 2981e8.0≈2981, leaving a wide window for distinguishing members.

Parameter δ\deltaδ (delta) provides additive slack for unlikely tail events where the strict eεe^{\varepsilon}eε ratio fails. In machine learning, δ\deltaδ isn't a minor failure percentage. Setting δ=1/N\delta = 1/Nδ=1/N is fatal: a mechanism could publish one raw customer record with probability 1/N1/N1/N and still satisfy the inequality mathematically! For a corpus of N=100,000N = 100{,}000N=100,000 training records, δ\deltaδ must be strictly smaller than 10−510^{-5}10−5, typically 10−610^{-6}10−6 or 10−710^{-7}10−7. Setting δ=0\delta = 0δ=0 gives pure differential privacy.

Differential privacy probability ratio envelope and neighboring sensitivity comparison. Top: Output probability density distributions for neighboring datasets D and D prime under mechanism M, illustrating that the density ratio at any output s is bounded within the exponential envelope exp(-epsilon) to exp(epsilon), with delta accounting for tail slack. Bottom: Neighboring dataset sensitivity under add/remove adjacency (distance C, normalized to C/m = 0.5) versus replace-one adjacency (distance 2C, normalized to 2C/m = 1.0).
Differential privacy bounds output distributions within an exponential envelope across neighboring datasets. The adjacency convention determines whether sensitivity is C or 2C.

Consider a toy mechanism you can evaluate by hand. A support customer answers a sensitive yes/no question truthfully with probability 0.750.750.75 and reports the opposite answer with probability 0.250.250.25:

True private responseProbability reporting YesProbability reporting No
Yes0.750.25
No0.250.75

The largest possible probability ratio for either output is 0.75/0.25=3.00.75 / 0.25 = 3.00.75/0.25=3.0. This randomized-response mechanism satisfies pure differential privacy with ε=ln⁡3≈1.10\varepsilon = \ln 3 \approx 1.10ε=ln3≈1.10 and δ=0\delta = 0δ=0. It's a local differential privacy mechanism because noise is added on the client device before anyone else observes the response.[2]Reference 2The Algorithmic Foundations of Differential Privacy.https://www.microsoft.com/en-us/research/publication/algorithmic-foundations-differential-privacy/

Training an LLM uses the central model instead. Gradients from thousands of examples are pooled, clipped, and perturbed inside a secure compute boundary before weights leave the cluster.

A machine learning engineer trains an LLM on 50,000 patient records and reports a privacy guarantee with epsilon = 2.0 and delta = 0.05. Why is this delta value unacceptable?

Answer

Delta represents the probability that the differential privacy bound fails completely. A delta of 0.05 means the mechanism could leak raw unperturbed records for 5% of the dataset (2,500 patients) while technically satisfying the mathematical inequality. In machine learning, delta must be strictly smaller than 1/N, typically 10^-5 or 10^-6 for this corpus size.

Mechanisms and sensitivity scaling

Differential privacy adds noise proportional to the query's global sensitivity. For any function fff mapping a dataset to a vector space, sensitivity measures the maximum change between any two neighboring datasets DDD and D′D'D′:

Δ1f=max⁡D∼D′∥f(D)−f(D′)∥1,Δ2f=max⁡D∼D′∥f(D)−f(D′)∥2\Delta_1 f = \max_{D \sim D'} \|f(D) - f(D')\|_1, \qquad \Delta_2 f = \max_{D \sim D'} \|f(D) - f(D')\|_2Δ1​f=D∼D′max​∥f(D)−f(D′)∥1​,Δ2​f=D∼D′max​∥f(D)−f(D′)∥2​

Two foundational mechanisms inject this noise:

The Laplace mechanism adds independent noise drawn from Lap(Δ1f/ε)\text{Lap}(\Delta_1 f / \varepsilon)Lap(Δ1​f/ε) to each coordinate. It guarantees pure (ε,0)(\varepsilon, 0)(ε,0)-differential privacy. For scalar counts or low-dimensional database queries, Laplace noise is simple and effective.

In deep neural networks, the Laplace mechanism fails completely. In a model with ddd parameters, the expected L1L_1L1​ norm of independent Laplace noise scales linearly with d/εd / \varepsilond/ε. When updating a 100-million-parameter model, adding coordinate-wise Laplace noise injects so much variance that optimization collapses immediately.

The Gaussian mechanism adds noise drawn from N(0,σ2I)\mathcal{N}(0, \sigma^2 I)N(0,σ2I), where standard deviation σ\sigmaσ satisfies:

σ≥Δ2f2ln⁡(1.25/δ)ε\sigma \ge \frac{\Delta_2 f \sqrt{2 \ln(1.25/\delta)}}{\varepsilon}σ≥εΔ2​f2ln(1.25/δ)​​

The Gaussian mechanism delivers (ε,δ)(\varepsilon, \delta)(ε,δ)-differential privacy. Its required noise scales with L2L_2L2​ sensitivity (Δ2f\Delta_2 fΔ2​f) rather than L1L_1L1​ sensitivity. Because the L2L_2L2​ norm of a vector is bounded by its maximum coordinate times d\sqrt{d}d​ rather than ddd, the Gaussian mechanism injects vastly less total variance into high-dimensional gradient vectors. That makes the Gaussian mechanism the standard engine for private deep learning.

Differentially private stochastic gradient descent

Standard stochastic gradient descent computes the loss gradient over a mini-batch, averages those vectors, and steps the parameters. That average is directly vulnerable to outliers: if Alice's private record has an unusually large gradient with norm 100.0100.0100.0 while normal samples have norm 0.50.50.5, Alice's record pulls the aggregate step toward her exact tokens.

Differentially private stochastic gradient descent (DP-SGD) fixes this vulnerability by bounding each contribution individually before summation [4]Reference 4Deep Learning with Differential Privacyhttps://arxiv.org/abs/1607.00133.

The DP-SGD algorithm proceeds in five explicit phases on each training step ttt:

  1. Poisson subsampling: Form batch BtB_tBt​ by including each training record independently with sampling probability q=L/Nq = L / Nq=L/N, where LLL is the target batch size and NNN is total dataset size.
  2. Per-sample backpropagation: For each example i∈Bti \in B_ti∈Bt​, compute its individual parameter gradient gi(θt)=∇θL(xi,θt)g_i(\theta_t) = \nabla_\theta \mathcal{L}(x_i, \theta_t)gi​(θt​)=∇θ​L(xi​,θt​) separately before any batch reduction occurs.
  3. Per-sample clipping: Enforce an L2L_2L2​ norm threshold C>0C > 0C>0 on each vector: gˉi(θt)=gi(θt)⋅min⁡(1,C∥gi(θt)∥2)\bar{g}_i(\theta_t) = g_i(\theta_t) \cdot \min\left(1, \frac{C}{\|g_i(\theta_t)\|_2}\right)gˉ​i​(θt​)=gi​(θt​)⋅min(1,∥gi​(θt​)∥2​C​) If ∥gi∥2≤C\|g_i\|_2 \le C∥gi​∥2​≤C, the gradient is untouched. If ∥gi∥2>C\|g_i\|_2 > C∥gi​∥2​>C, the gradient keeps its exact direction but its length shrinks to CCC.
  4. Summation and Gaussian noise injection: Sum the clipped vectors and add calibrated Gaussian noise scaled to sensitivity CCC: g~t=∑i∈Btgˉi(θt)+N(0,σ2C2I)\widetilde{g}_t = \sum_{i \in B_t} \bar{g}_i(\theta_t) + \mathcal{N}\left(0, \sigma^2 C^2 I\right)g​t​=i∈Bt​∑​gˉ​i​(θt​)+N(0,σ2C2I) Adding or removing one sample changes the sum by at most CCC, so the L2L_2L2​ sensitivity of the summation is Δ2=C\Delta_2 = CΔ2​=C.
  5. Descent step: Divide the noisy aggregate by target batch size LLL and update parameters: θt+1=θt−ηtg~tL\theta_{t+1} = \theta_t - \eta_t \frac{\widetilde{g}_t}{L}θt+1​=θt​−ηt​Lg​t​​
DP-SGD per-sample gradient clipping and calibrated noise injection pipeline. Top: 4-stage pipeline showing Poisson subsampling of examples with rate q, per-sample backpropagation before reduction, L2 norm clipping to threshold C, and summation with calibrated Gaussian noise. Bottom: Left panel contrasts in-bounds versus outlier gradients projected to the L2 ball of radius C. Right panel details the noise addition and descent step.
DP-SGD projects outlier gradients to the L2 ball of radius C before aggregation and Gaussian perturbation, bounding sensitivity to C.

A frequent bug in custom implementations is clipping the batch average after aggregation: clip(mean(gradients), C). This bounds the final update vector's length to CCC, but neighboring dataset averages can still point in opposite directions, creating a worst-case difference of 2C2C2C between outputs. Clipping must occur per sample before aggregation to establish sensitivity CCC for the batch sum.

To verify this geometry, test per-sample vector clipping on concrete gradient vectors. Outliers project onto the unit ball while in-bounds gradients remain untouched:

clip-vector-gradients.py
1import math 2 3def clip_vector_l2(vector: list[float], bound: float) -> list[float]: 4 if bound <= 0: 5 raise ValueError("bound must be positive") 6 norm = math.hypot(*vector) 7 if norm == 0.0 or norm <= bound: 8 return [round(x, 4) for x in vector] 9 scale = bound / norm 10 return [round(x * scale, 4) for x in vector] 11 12sample_gradients = [ 13 [0.4, 0.3], # norm = 0.5 <= 1.0 (unclipped) 14 [3.0, 4.0], # norm = 5.0 > 1.0 (scaled by 1.0 / 5.0 = 0.2) 15 [0.6, 0.8], # norm = 1.0 == 1.0 (unclipped) 16] 17clip_bound = 1.0 18clipped = [clip_vector_l2(g, clip_bound) for g in sample_gradients] 19 20print(f"sample gradients: {sample_gradients}") 21print(f"clipped gradients: {clipped}") 22 23sum_g = [sum(dim) for dim in zip(*clipped)] 24print(f"clipped sum before noise: [{sum_g[0]:.2f}, {sum_g[1]:.2f}]")
Output
1sample gradients: [[0.4, 0.3], [3.0, 4.0], [0.6, 0.8]] 2clipped gradients: [[0.4, 0.3], [0.6, 0.8], [0.6, 0.8]] 3clipped sum before noise: [1.60, 1.90]

The outlier [3.0, 4.0] with length 5.05.05.0 scales down to [0.6, 0.8], whose length is 0.62+0.82=1.0\sqrt{0.6^2 + 0.8^2} = 1.00.62+0.82​=1.0. The gradient's direction is preserved, but its ability to pull the model parameters toward its private values is clamped.

Now consider what happens when Alice contributes multiple messages. If Alice wrote two tickets with gradients 0.50.50.5 and 5.05.05.0, example-level clipping bounds each message to 1.01.01.0, leaving Alice with a combined influence of 1.51.51.5. A row-level clip doesn't bound Alice's full user-level influence.

User-level fine-tuning groups each user's records, sums their gradients, and clips that combined user vector [5]Reference 5Fine-Tuning Large Language Models with User-Level Differential Privacyhttps://arxiv.org/abs/2407.07737. Grouping records per user binds total customer influence before aggregation. Here we test Alice's two tickets against Bao's single ticket using a fixed public normalizer of two:

clip-complete-user-contributions.py
1def clip_scalar(gradient: float, bound: float) -> float: 2 if bound <= 0: 3 raise ValueError("bound must be positive") 4 return max(-bound, min(gradient, bound)) 5 6user_gradients = {"Alice": [0.5, 5.0], "Bao": [0.25]} 7clip_bound = 1.0 8 9for user, gradients in user_gradients.items(): 10 row_clipped_sum = sum(clip_scalar(value, clip_bound) for value in gradients) 11 user_clipped = clip_scalar(sum(gradients), clip_bound) 12 print(f"{user}: row-clipped sum={row_clipped_sum:.2f}, user-clipped={user_clipped:.2f}") 13 14normalizer = 2 # Public and unchanged across neighboring datasets. 15user_contributions = { 16 user: clip_scalar(sum(values), clip_bound) 17 for user, values in user_gradients.items() 18} 19with_alice = sum(user_contributions.values()) / normalizer 20without_alice = user_contributions["Bao"] / normalizer 21print(f"with Alice, before noise: {with_alice:.3f}") 22print(f"without Alice, before noise: {without_alice:.3f}") 23print(f"change from removing Alice: {with_alice - without_alice:.3f}") 24assert with_alice - without_alice <= clip_bound / normalizer
Output
1Alice: row-clipped sum=1.50, user-clipped=1.00 2Bao: row-clipped sum=0.25, user-clipped=0.25 3with Alice, before noise: 0.625 4without Alice, before noise: 0.125 5change from removing Alice: 0.500

Removing Alice changes the normalized sum by exactly 0.50.50.5, which equals C/m=1.0/2C / m = 1.0 / 2C/m=1.0/2. User-level grouping enforces that Alice's entire presence can't shift the pre-noise aggregate by more than CCC.

Why must DP-SGD compute gradients per sample before batch reduction, rather than clipping the batch average gradient?

Answer

Clipping the batch average bounds only the length of the final step, but neighboring datasets could still produce batch averages that point in opposing directions, creating an unbounded difference. Per-sample clipping bounds each individual contribution to norm C, guaranteeing that adding or dropping one sample shifts the batch sum by at most C.

Account for every exposed release

Clipping bounds sensitivity for one training step. Training an LLM takes thousands of steps. A privacy accountant tracks how privacy loss accumulates over the full optimization run [6]Reference 6Compute DP-SGD Privacyhttps://opacus.ai/api/compute_dp_sgd_privacy.html.

If you apply basic composition, privacy budgets add linearly: running TTT steps with step budget ε0\varepsilon_0ε0​ yields total ε=T⋅ε0\varepsilon = T \cdot \varepsilon_0ε=T⋅ε0​. A training run of 5,0005{,}0005,000 steps with ε0=0.1\varepsilon_0 = 0.1ε0​=0.1 would report ε=500\varepsilon = 500ε=500, an astronomically useless number.

Modern DP-SGD implementations rely on the Moments Accountant or Rényi Differential Privacy (RDP) [4]Reference 4Deep Learning with Differential Privacyhttps://arxiv.org/abs/1607.00133[7]Reference 7RDPAccountanthttps://opacus.ai/api/accounting/rdp.html. RDP measures the Rényi divergence of order α\alphaα between neighboring output distributions:

Dα(M(D)∥M(D′))=1α−1ln⁡∫(P(M(D)=s)αP(M(D′)=s)α−1)dsD_{\alpha}(M(D) \| M(D')) = \frac{1}{\alpha - 1} \ln \int \left( \frac{P(M(D) = s)^\alpha}{P(M(D') = s)^{\alpha - 1}} \right) dsDα​(M(D)∥M(D′))=α−11​ln∫(P(M(D′)=s)α−1P(M(D)=s)α​)ds

For a Gaussian mechanism with Poisson subsampling probability q=L/Nq = L / Nq=L/N, Rényi divergences compose linearly across steps:

εtotal(α)=T⋅εstep(α)≈T⋅αq2σ2\varepsilon_{\text{total}}(\alpha) = T \cdot \varepsilon_{\text{step}}(\alpha) \approx T \cdot \frac{\alpha q^2}{\sigma^2}εtotal​(α)=T⋅εstep​(α)≈T⋅σ2αq2​

Converting RDP back to (ε,δ)(\varepsilon, \delta)(ε,δ)-DP at the end of training yields an asymptotic bound:

ε≈q2Tln⁡(1/δ)σ\varepsilon \approx \frac{q \sqrt{2 T \ln(1/\delta)}}{\sigma}ε≈σq2Tln(1/δ)​​

Notice the factor q=L/Nq = L / Nq=L/N. This is subsampling amplification: because an attacker only sees an individual's data if that individual was included in the Poisson batch, privacy protection is amplified by qqq. In large datasets where q=10−3q = 10^{-3}q=10−3 or 10−410^{-4}10−4, subsampling amplification reduces cumulative epsilon by orders of magnitude compared to naive composition.

You can evaluate this directly with Opacus's RDPAccountant. We compare cumulative epsilon across 300 and 600 training steps under fixed sampling rate q=0.01q = 0.01q=0.01 and noise multiplier σ=1.0\sigma = 1.0σ=1.0:

account-sampled-gaussian-updates.py
1from opacus.accountants import RDPAccountant 2 3for steps in [300, 600]: 4 accountant = RDPAccountant() 5 for _ in range(steps): 6 accountant.step(noise_multiplier=1.0, sample_rate=0.01) 7 epsilon = accountant.get_epsilon(delta=1e-5) 8 print(f"steps={steps}, epsilon={epsilon:.3f}, delta=1e-5")
Output
1steps=300, epsilon=1.451, delta=1e-5 2steps=600, epsilon=1.748, delta=1e-5

Doubling training steps from 300 to 600 increases epsilon from 1.4511.4511.451 to 1.7481.7481.748, rather than doubling it to 2.902.902.90. Sublinear scaling allows practical models to train for thousands of steps while maintaining strict privacy budgets.

Once training finishes, what about serving customer inference requests? Under the post-processing theorem, applying any arbitrary function to the output of an (ε,δ)(\varepsilon,\delta)(ε,δ)-differentially private algorithm without accessing private data costs zero additional privacy budget [2]Reference 2The Algorithmic Foundations of Differential Privacy.https://www.microsoft.com/en-us/research/publication/algorithmic-foundations-differential-privacy/. Serving ten million inference queries from the released model doesn't spend any extra training epsilon.

Diagram showing Private training records, Accounted DP-SGD training, Released DP checkpoint, and Public user inferences Free post-processing.
Private training records, Accounted DP-SGD training, Released DP checkpoint, and Public user inferences Free post-processing.

Post-processing applies only to operations that touch public data and the released weights. If you compute validation scores on private held-out records, run hyperparameter grid searches on private logs, or save unnoised intermediate checkpoints, those operations expose private data outside the accounted transcript and spend separate privacy budget.

Release policies track this cumulative exposure across candidate models using release ledgers:

track-private-release-ledger.py
1from decimal import Decimal 2 3released = [ 4 (Decimal("1.2"), Decimal("0.000001")), 5 (Decimal("1.1"), Decimal("0.000001")), 6] 7candidate = (Decimal("0.9"), Decimal("0.000001")) 8proposed_epsilon = sum(eps for eps, _ in released) + candidate[0] 9proposed_delta = sum(d for _, d in released) + candidate[1] 10allowed = (proposed_epsilon <= Decimal("3.0") 11 and proposed_delta <= Decimal("0.000003")) 12 13print(f"candidate total: epsilon={proposed_epsilon:.1f}, delta={proposed_delta:.6f}") 14print(f"release allowed: {allowed}") 15assert not allowed
Output
1candidate total: epsilon=3.2, delta=0.000003 2release allowed: False

The release ledger blocks the candidate because total epsilon (3.23.23.2) exceeds the release cap (3.03.03.0). Using Decimal prevents floating-point rounding errors from approving unauthorized model deployments.

The privacy-utility trade-off in modern LLMs

Applying DP-SGD to a multi-billion-parameter language model exposes a brutal geometric obstacle: the curse of dimensionality.

When you add Gaussian noise Z∼N(0,σ2C2Id)Z \sim \mathcal{N}(0, \sigma^2 C^2 I_d)Z∼N(0,σ2C2Id​) to a model with ddd parameters, the expected Euclidean norm of the injected noise vector is:

E[∥Z∥2]≈σCd\mathbb{E}[\|Z\|_2] \approx \sigma C \sqrt{d}E[∥Z∥2​]≈σCd​

In a 7-billion-parameter model, d≈7×109≈83,666\sqrt{d} \approx \sqrt{7 \times 10^9} \approx 83{,}666d​≈7×109​≈83,666. If you set clipping threshold C=1.0C = 1.0C=1.0 and noise multiplier σ=1.0\sigma = 1.0σ=1.0, each update step injects a random noise vector with norm exceeding 80,00080{,}00080,000 into the weights!

True gradient sums from a standard mini-batch of 64 or 128 examples have norm on the order of 505050 to 100100100. The random noise vector dwarfs the learning signal by a factor of nearly a thousand. Full-parameter DP-SGD on large models fails to converge unless you scale batch sizes into the tens of thousands (L≥65,536L \ge 65{,}536L≥65,536), which requires immense compute cluster memory.

Parameter-efficient fine-tuning with DP-LoRA eliminates this dimensionality trap [8]Reference 8LoRA: Low-Rank Adaptation of Large Language Models.https://arxiv.org/abs/2106.09685[5]Reference 5Fine-Tuning Large Language Models with User-Level Differential Privacyhttps://arxiv.org/abs/2407.07737.

Instead of updating all weights W0∈Rdin×doutW_0 \in \mathbb{R}^{d_{\text{in}} \times d_{\text{out}}}W0​∈Rdin​×dout​, Low-Rank Adaptation freezes the pre-trained base model completely and injects trainable low-rank decomposition matrices:

W=W0+ΔW=W0+αrBA,A∈Rr×din,B∈Rdout×rW = W_0 + \Delta W = W_0 + \frac{\alpha}{r} B A, \qquad A \in \mathbb{R}^{r \times d_{\text{in}}}, \quad B \in \mathbb{R}^{d_{\text{out}} \times r}W=W0​+ΔW=W0​+rα​BA,A∈Rr×din​,B∈Rdout​×r

Setting rank r=8r = 8r=8 reduces the number of trainable parameters from billions down to a few million (often <0.1%< 0.1\%<0.1% of total parameters).

In DP-LoRA, gradients are computed, clipped, and perturbed only for matrices AAA and BBB. The dimension dtraind_{\text{train}}dtrain​ drops from 7×1097 \times 10^97×109 to 5×1065 \times 10^65×106. Because noise norm scales with dtrain\sqrt{d_{\text{train}}}dtrain​​, the total injected noise norm drops by a factor of 7000/5≈37×\sqrt{7000 / 5} \approx 37\times7000/5​≈37×. The gradient signal-to-noise ratio jumps dramatically, allowing DP-LoRA to learn domain tasks with high fidelity under strict privacy budgets.

Privacy-utility Pareto frontier comparing DP-LoRA, full-parameter DP-SGD, and zero-shot baseline across privacy budgets epsilon from 1 to 16 and non-private training. DP-LoRA maintains strong task accuracy (89 percent at epsilon = 4) by confining Gaussian noise to a low-rank subspace (0.1 percent of parameters), whereas full fine-tuning suffers severe degradation at strict epsilon due to high-dimensional noise variance.
DP-LoRA confines noise to low-rank adapter matrices, preserving gradient signal-to-noise ratio and achieving near-non-private utility at practical epsilon budgets.

This architecture creates an important pre-training privacy asymmetry:

  1. Pre-training corpus exposure: The foundation model was trained on trillions of public and crawled web tokens without differential privacy. It may already have memorized text from those public sources. DP fine-tuning doesn't purge or scrub pre-existing foundation model memorization.
  2. Fine-tuning corpus protection: The fine-tuning phase uses DP-SGD on proprietary domain data (such as medical records or customer support logs). The resulting adapter weights guarantee that an attacker querying the fine-tuned model can't extract or reconstruct private records from that fine-tuning dataset beyond the accounted (ε,δ)(\varepsilon, \delta)(ε,δ) bound.

By anchoring on frozen pre-trained representations and training only low-rank adapters with DP-SGD, teams ship enterprise copilots that master complex domain tasks while providing provable privacy guarantees.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.What distinguishes a user-level differential privacy guarantee from a row-level guarantee?

Correct answer: Its neighboring datasets differ by all protected contributions from one user.

A user-level neighboring relationship protects the presence or absence of the user's complete contribution, not just one row.

2.Why doesn't removing names and identifiers from training examples establish differential privacy?

Correct answer: Redaction doesn't bound how model output distributions change when one protected record is removed.

Differential privacy is a formal neighboring-dataset output distribution guarantee, while redaction only alters specific surface strings without bounding memorization or statistical dependency.

3.Which operation must occur before aggregating gradients in DP-SGD?

Correct answer: Clip each protected contribution to its configured norm bound before averaging.

Per-example clipping limits individual gradient norm to C before contributions are summed, guaranteeing that the summation sensitivity is bounded by C.

4.Why does the Gaussian mechanism outperform the Laplace mechanism when training deep neural networks?

Correct answer: Gaussian noise scales with L2 sensitivity rather than L1 sensitivity, injecting far less total variance in high dimensions.

In high-dimensional parameter spaces, L1 sensitivity and Laplace noise scale with parameter dimension d, destroying optimization signals, whereas Gaussian noise scales with L2 sensitivity.

5.What is the primary mechanism by which DP-LoRA preserves model utility compared to full-parameter DP-SGD?

Correct answer: It confines parameter updates to low-rank matrices, drastically reducing the noise vector dimension and boosting signal-to-noise ratio.

Noise vector norm scales with the square root of trainable parameter count. By training low-rank adapters (0.1% of weights), DP-LoRA reduces injected noise magnitude by orders of magnitude.

6.What does a reference-based membership inference attack compare to detect training set members?

Correct answer: Target model loss on the candidate against loss from a public reference model or compression entropy.

Comparing target model loss to a reference model factors out inherently predictable text, revealing whether the target model overfits the candidate specifically due to training exposure.

7.Why does replace-one adjacency yield twice the sensitivity of add/remove adjacency under norm bound C?

Correct answer: Replacing a record can swap a contribution of +C with -C, spanning distance 2C, whereas removal moves between C and 0.

Under add/remove, dropping an element changes the sum by at most C. Under replace-one, substituting an element at the opposite extreme can swing the sum by 2C.

8.Under the post-processing theorem, what privacy cost is incurred when serving 1,000,000 public inference queries from an already released DP model?

Correct answer: Zero additional privacy budget is spent.

The post-processing theorem states that any algorithm applied to the output of a differentially private mechanism without re-accessing private training data preserves the original privacy guarantee at zero additional cost.

9.How does Poisson subsampling with rate q = L/N amplify privacy in DP-SGD?

Correct answer: Each sample is included with probability q, scaling down effective privacy loss by roughly q per step.

Because an attacker can only observe an individual record's influence when that record is sampled (probability q), privacy loss scales down by q under Poisson subsampling.

10.Why doesn't DP fine-tuning protect against extraction of text seen during foundation model pre-training?

Correct answer: DP fine-tuning bounds only the information leakage from the fine-tuning dataset; pre-existing foundation weights were trained non-privately.

DP guarantees apply to the data processed by the private mechanism. Non-private pre-training weights already contain memorized internet data; DP-SGD fine-tuning protects only the new domain fine-tuning records.

10 questions remaining.

Next Step
Continue to Data Labeling and Human Feedback

Private training depends on well-scoped human data; the next lesson builds labeling and feedback pipelines that preserve provenance, consent, and reliable supervision.

PreviousResponsible AI Governance
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Calibrating Noise to Sensitivity in Private Data Analysis.

Dwork, C., McSherry, F., Nissim, K., & Smith, A. · 2006 · TCC 2006

https://people.csail.mit.edu/asmith/PS/sensitivity-tcc-final.pdf

The Algorithmic Foundations of Differential Privacy.

Dwork, C. & Roth, A. · 2014 · Foundations and Trends in Theoretical Computer Science

https://www.microsoft.com/en-us/research/publication/algorithmic-foundations-differential-privacy/

Membership Inference Attacks against Machine Learning Models

Shokri, R., Stronati, M., Song, C., & Shmatikov, V. · 2016 · IEEE Symposium on Security and Privacy 2017

https://arxiv.org/abs/1610.05820

Deep Learning with Differential Privacy

Abadi, M., Chu, A., Goodfellow, I., McMahan, H. B., Mironov, I., Talwar, K., & Zhang, L. · 2016 · ACM CCS 2016

https://arxiv.org/abs/1607.00133

Fine-Tuning Large Language Models with User-Level Differential Privacy

Charles, Z., Ganesh, A., McKenna, R., McMahan, H. B., Mitchell, N., Pillutla, K., & Rush, K. · 2024

https://arxiv.org/abs/2407.07737

Compute DP-SGD Privacy

Opacus Contributors · 2026

https://opacus.ai/api/compute_dp_sgd_privacy.html

RDPAccountant

Opacus Contributors · 2026

https://opacus.ai/api/accounting/rdp.html

LoRA: Low-Rank Adaptation of Large Language Models.

Hu, E. J., et al. · 2021 · ICLR

https://arxiv.org/abs/2106.09685

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.