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 192 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/27
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 Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingModel 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 & AutoscalingDistributed 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.

9 min read
Learning path
Step 68 of 192 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.

A support model is in its last pre-launch review. A red-team analyst pastes a private troubleshooting note, and the model completes a missing sentence with customer-specific detail. Names were stripped from the training rows, but the model can still depend on the note itself.

Responsible AI Governance established ownership, policy, and review gates. Differential privacy turns this incident into a neighboring-dataset question: if every record from one protected person disappeared before training, how much could the distribution of released 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/

That question names a promise redaction can't make. To answer it, you must choose the protected unit, bound its full contribution, add calibrated randomness, and count every later release against the same promise.

Alice contributes combined gradient 5.5 and Bao contributes 0.25; user-level clipping bounds those contributions at 1.0 and 0.25 before calibrated noise and user-aware privacy accounting.
User-level privacy requires grouping and bounding each user's complete contribution. Noise and accounting must use the same protected-user definition across training and releases.

Start with the unit you promise to protect

Before choosing an epsilon, write one sentence: “one protected unit is ___.” Two datasets are neighbors when they differ by that protected unit. In support data, the blank might be one row, one conversation, one user, or one organization.

Protected unitNeighboring changeHidden mistake
RowRemove one training rowOne person contributes several rows
ConversationRemove one complete conversationA user appears across multiple conversations
UserRemove every row belonging to one userMissing user identity prevents contribution limits

Suppose Alice contributed twelve messages. A row-level accountant considers one message at a time. A user-level review asks what happens when all twelve disappear together. Same dataset, different neighboring relation, different privacy promise.

Diagram showing Dataset with protected user, Randomized private training, Neighbor without that user, and Bounded change in release behavior.
Dataset with protected user, Randomized private training, Neighbor without that user, and Bounded change in release behavior.

Turn that promise into a release condition. For every possible output event SSS, an (ε,δ)(\varepsilon,\delta)(ε,δ)-private mechanism satisfies:[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)+δ

Here DDD and D′D'D′ are neighbors, and MMM is randomized. ε\varepsilonε bounds the multiplicative change in an event’s probability; δ\deltaδ allows a small additive failure term.

Neither number travels alone. The protected unit, sampling, contribution bound, randomness, and composition assumptions explain what the pair actually promises.

One support customer contributes twelve training messages. A release claims user-level privacy but defines neighboring datasets by removing one message. What exactly is wrong with the claim?

Answer

The mechanism's declared adjacency protects one row, while removing the customer removes twelve rows. Its epsilon and delta therefore describe a row-level comparison, not the promised user-level comparison, unless the full user contribution is bounded and accounted for explicitly.

Bound each contribution before aggregation

Once the protected unit is fixed, bound its influence at that same boundary. Differentially private stochastic gradient descent (DP-SGD) usually computes each training example’s gradient separately, so standard DP-SGD bounds an example-level contribution. A user-level promise needs user-aware grouping or a valid conversion and accountant.[3]Reference 3Deep Learning with Differential Privacyhttps://arxiv.org/abs/1607.00133[4]Reference 4Fine-Tuning Large Language Models with User-Level Differential Privacyhttps://arxiv.org/abs/2407.07737

For gradient gig_igi​ and clip threshold CCC:

gˉi=gimin⁡(1,C∥gi∥2)\bar g_i=g_i\min\left(1,\frac{C}{\lVert g_i\rVert_2}\right)gˉ​i​=gi​min(1,∥gi​∥2​C​)

The norm operation leaves a gradient below CCC alone and scales a larger one down to CCC. Average those clipped contributions, add calibrated noise through a Gaussian mechanism, and update the model. Clipping an already-averaged batch gradient comes too late: cancellation and reinforcement have hidden each individual contribution.

Predict before running the cell: with gradients 0.50.50.5 and 5.05.05.0 and a bound of 1.01.01.0, which value changes, and what mean remains before noise? The calculation clips each scalar independently. It intentionally omits randomness, so it demonstrates sensitivity control rather than a private release.

clip-individual-training-gradients.py
1def clip_scalar(gradient: float, bound: float) -> float: 2 scale = min(1.0, bound / max(abs(gradient), 1e-12)) 3 return gradient * scale 4 5gradients = [0.5, 5.0] 6clip_bound = 1.0 7clipped = [clip_scalar(value, clip_bound) for value in gradients] 8 9assert clipped == [0.5, 1.0] 10print(f"raw gradients: {gradients}") 11print(f"clipped gradients: {clipped}") 12print(f"clipped mean before noise: {sum(clipped) / len(clipped):.2f}")
Output
1raw gradients: [0.5, 5.0] 2clipped gradients: [0.5, 1.0] 3clipped mean before noise: 0.75

The 5.05.05.0 gradient becomes 1.01.01.0, while 0.50.50.5 stays unchanged. Their mean is therefore 0.750.750.75, instead of the unclipped 2.752.752.75.

Now change only the ownership: if both examples belong to Alice, row clipping leaves a combined contribution of 1.51.51.5. A row-level bound of 1.01.01.0 has not bounded Alice’s full influence, so it can't support a user-level claim with that same bound.

User-level training can sample users, aggregate each sampled user’s examples, and clip that combined gradient. A capped example-level route can also work when each user’s maximum example count is enforced and a group-aware accountant converts that exposure into a user-level guarantee.

The choice changes sampling, compute, and utility. Under fixed compute budgets, the cited LLM study finds that capped example-level sampling can win in some settings, while user-level sampling generally helps when users contribute diverse examples.[4]Reference 4Fine-Tuning Large Language Models with User-Level Differential Privacyhttps://arxiv.org/abs/2407.07737

Neither route can enforce a user boundary when identity is unknown or the cap is unenforced.

The next cell makes that boundary explicit. It groups Alice’s two messages and Bao’s one message, clips each combined user gradient, and then computes the user-level average.

clip-complete-user-contributions.py
1def clip_scalar(gradient: float, bound: float) -> float: 2 scale = min(1.0, bound / max(abs(gradient), 1e-12)) 3 return gradient * scale 4 5user_gradients = {"Alice": [0.5, 5.0], "Bao": [0.25]} 6clip_bound = 1.0 7 8for user, gradients in user_gradients.items(): 9 row_clipped_sum = sum(clip_scalar(value, clip_bound) for value in gradients) 10 user_clipped = clip_scalar(sum(gradients), clip_bound) 11 print(f"{user}: row-clipped sum={row_clipped_sum:.2f}, user-clipped={user_clipped:.2f}") 12 13user_contributions = [clip_scalar(sum(values), clip_bound) for values in user_gradients.values()] 14print(f"user-level clipped mean before noise: {sum(user_contributions) / len(user_contributions):.3f}")
Output
1Alice: row-clipped sum=1.50, user-clipped=1.00 2Bao: row-clipped sum=0.25, user-clipped=0.25 3user-level clipped mean before noise: 0.625

The example still has no randomness. A real mechanism needs correctly sampled noise, protected-unit-aware sampling, and an accountant that uses the same adjacency definition from training through release.

Why isn't clipping the final average gradient equivalent to bounding each declared protected contribution?

Answer

The final average can hide how much one protected unit contributed before aggregation. Row-level privacy clips each example first, while user-level privacy needs a bounded combined user contribution or valid group-aware accounting.

Account for every exposed release

Clipping controls sensitivity for one step; it doesn't tell you the exposure of the whole run. A privacy budget accumulates across repeated access to the same protected data. A privacy accountant combines the protected-unit sampling rate, noise multiplier, iteration count, and composition method into the resulting guarantee.[5]Reference 5Compute DP-SGD Privacyhttps://opacus.ai/api/compute_dp_sgd_privacy.html

QuantityWhat must be recorded
Protected unitWhether one record, conversation, or user is protected
Clip boundMaximum permitted contribution before aggregation
Noise multiplierScale of randomness relative to the clipping bound
Sampling rateFraction of protected units included in each step
Training stepsNumber of composed accesses
Final (ε,δ)(\varepsilon,\delta)(ε,δ)Accounted release guarantee under the declared assumptions

For separately accounted sequential releases, basic composition adds their epsilon values and their delta values. Specialized moments or Rényi accountants often give tighter valid bounds for a subsampled Gaussian training mechanism. Their result still depends on the sampling and release assumptions that the implementation actually meets.[3]Reference 3Deep Learning with Differential Privacyhttps://arxiv.org/abs/1607.00133

Predict before running the cell: two earlier releases spent 1.21.21.2 and 1.11.11.1, and a candidate spends 0.90.90.9. A simplified additive policy with a cap of 3.03.03.0 should reject it. This ledger omits delta and is not a DP-SGD accountant; it illustrates a conservative release gate.

track-private-release-ledger.py
1budget_limit = 3.0 2released_epsilon = [1.2, 1.1] 3candidate_epsilon = 0.9 4 5spent = sum(released_epsilon) 6proposed_total = spent + candidate_epsilon 7allowed = proposed_total <= budget_limit 8 9print(f"previous releases: epsilon={spent:.1f}") 10print(f"candidate total: epsilon={proposed_total:.1f}") 11print(f"release allowed: {allowed}") 12assert not allowed
Output
1previous releases: epsilon=2.3 2candidate total: epsilon=3.2 3release allowed: False

The ledger rejects the candidate because 3.23.23.2 exceeds 3.03.03.0. A real gate also tracks delta and checks that its accountant matches the protected unit, sampling scheme, mechanism, and disclosed output.

Extra checkpoints, private hyperparameter searches, and sensitive diagnostics can become additional releases. If the threat model exposes them, the accountant has to include them.

Two separately accounted releases spend epsilon 1.2 and 1.1, and a third needs 0.9. A simplified additive policy caps epsilon at 3.0. Can the third release proceed, and what other parameter must a real gate track?

Answer

No. The proposed additive total is 1.2 + 1.1 + 0.9 = 3.2, exceeding the 3.0 limit. A real release gate must also account for delta and verify that its composition method, protected unit, sampling assumptions, and disclosed outputs match the implemented mechanism.

Test attacks without mistaking them for proof

A membership inference attack asks whether a particular record was part of model training. In a black-box test, an attacker can compare prediction confidence or loss for known members and matched nonmembers.[6]Reference 6Membership Inference Attacks against Machine Learning Modelshttps://arxiv.org/abs/1610.05820

Ask what a passing or failing audit can support. An effective attack exposes one disclosure path.

A failed attack only says that this attacker, population, threshold, and interface didn't separate the tested members from nonmembers. A formal differential-privacy claim still rests on the complete randomized mechanism and its accounting assumptions.

Claimed protectionWhat it actually establishes
Removed visible namesOne form of direct identifier exposure was reduced
Hashed user IDsIdentifiers were transformed, possibly reversibly or linkably
Membership attack failedOne tested attack didn't distinguish the selected samples
Accounted user-level DP-SGDA formal bound under stated neighboring-user and implementation assumptions

Use the audit alongside access control, retention, consent, training-data provenance, audit trails, and legal review. A mathematical bound narrows one class of disclosure; it doesn't authorize collection or release by itself.

At release review, an engineer should be able to trace the claim to a record of the protected unit, maximum records per user, clipping boundary, noise multiplier, sampling scheme, accountant, epsilon, delta, and every disclosed checkpoint. Reproduce Alice’s row-clipped contribution of 1.501.501.50 beside her correctly user-clipped contribution of 1.001.001.00, then verify the user-level mean of 0.6250.6250.625 before noise.

Add a membership-inference audit as evidence about one tested interface. Reject the release when its only protection is redaction, a failed attack, an untracked checkpoint, or a row-level accountant attached to a user-level claim.

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 from training examples establish differential privacy?

Correct answer: Redaction doesn't bound how model outputs change when one protected user is removed.

Differential privacy is a formal neighboring-dataset output guarantee, while redaction only reduces particular observable identifiers.

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

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

Per-example clipping limits individual sensitivity before clipped gradients are aggregated and randomized.

4.The scalar gradients are 0.5 and 5.0 with clipping bound 1.0. What is their clipped mean before noise?

Correct answer: 0.75, because individual clipping changes the values to 0.5 and 1.0.

The gradients become 0.5 and 1.0 after individual clipping, and their mean is 0.75.

5.Why must a private-training release ledger account for multiple published checkpoints?

Correct answer: Repeated releases can compose privacy loss for the same protected population.

Privacy exposure can accumulate across released computations that access the same protected data, so accounting must cover the release sequence.

6.What does a successful membership inference attack attempt to determine?

Correct answer: Whether a particular record or person participated in model training.

Membership inference tries to distinguish training-set members from comparable nonmembers using model behavior.

7.Why doesn't one failed membership attack prove a model is differentially private?

Correct answer: Another attack or population may succeed, and no formal mechanism was established.

Attack evaluation tests a particular threat model, while differential privacy requires a proven randomized mechanism and explicit accounting assumptions.

8.Which additional detail is necessary before an epsilon value describes a useful privacy guarantee?

Correct answer: The protected unit, delta, sampling assumptions, and accounting method.

An epsilon value is interpretable only with the neighboring-unit definition, delta, mechanism assumptions, and composition/accounting details.

9.One user contributes twelve training rows. What is required before claiming a user-level DP-SGD guarantee?

Correct answer: Bound each user's combined contribution or apply valid group-aware accounting.

User-level adjacency removes all contributions from one user, so the clipping and accountant must bound that complete contribution or explicitly account for the bounded group.

9 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/

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

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

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.