🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

ML Security & Privacy

AI System DesignSecurity & Privacy in ML SystemsđŸŸĸ Free Lesson

ML Security & Privacy

Protecting ML systems from attacks while preserving data privacy

What You'll Learn

  • 1Map the ML attack surface from training data extraction to prompt injection and pick layered defenses
  • 2Calibrate differential privacy noise with the Gaussian mechanism and track the budget across training steps
  • 3Quantify the accuracy cost of a privacy guarantee such as epsilon = 1.0 on your own workload
  • 4Design a GDPR-aligned serving pipeline with encryption, logging, and a right-to-erasure path

Why This Matters

ML systems face unique security threats including adversarial attacks, data poisoning, model theft, and privacy breaches. A single vulnerability can compromise millions of users' data or enable model manipulation. Security must be built into ML systems from the ground up.

âš ī¸

73% of organizations have experienced at least one ML security incident in the past year. The average cost of an ML security breach is $4.2M.

ML Security Architecture

ML Security ArchitectureData Security LayerEncryption at RestEncryption in TransitData MaskingAccess ControlsModel Security LayerModel WatermarkingAdversarial DetectionModel EncryptionAccess LoggingInference Security LayerInput ValidationRate LimitingOutput SanitizationAnomaly DetectionAttack Vectors- Data Poisoning- Model Inversion- Membership Inference- Adversarial Examples- Model Stealing- Prompt Injection- Backdoor AttacksDefense Mechanisms- Differential Privacy- Federated Learning- Secure Multi-Party Computation- Homomorphic Encryption- Robust Training- Input Validation- Output Filtering

Adversarial Attack Detection

Adversarial attacks involve crafting malicious inputs designed to fool ML models. Detection systems use multiple complementary methods: gradient-based detection analyzes input sensitivity by computing loss gradients; statistical analysis checks for distributional anomalies in input features; Monte Carlo dropout estimates model uncertainty through multiple forward passes with dropout enabled; and feature squeezing compares predictions on original vs. simplified inputs. These methods are combined into a composite score that determines whether an input is adversarial, identifies the likely attack type (FGSM, PGD, or optimization-based), and recommends appropriate defense mechanisms.

The simplest attack to reason about is the fast gradient sign method, which moves each input pixel by the sign of the loss gradient inside an budget:

With 8-bit images and the perturbation is about 3 intensity levels per channel, invisible to a human, yet published evaluations show it flips the label of undefended ImageNet classifiers on the majority of samples. Iterative variants such as projected gradient descent (PGD) take to 40 steps of size and are strictly stronger, so a defense that only survives FGSM is not defended. The matching detection signal is disagreement: squeeze the input with bit depth reduction or Gaussian smoothing, run both versions, and flag the request when the predicted class changes, because benign inputs rarely change class under a mild smoothing while adversarial ones often do.

Differential Privacy Implementation

Differential privacy provides mathematical guarantees that individual training examples cannot be inferred from model outputs. The core technique involves clipping per-example gradients to bound sensitivity, then adding calibrated Gaussian noise to the aggregated gradients. The privacy budget (epsilon, delta) tracks cumulative privacy loss across training steps using the moments accountant method. Key implementation considerations include choosing appropriate clipping norms, noise multipliers, and batch sizes to achieve desired privacy-utility tradeoffs. Strong privacy guarantees (epsilon below 1.0) typically result in roughly 5 percent accuracy loss, while moderate guarantees (epsilon around 10) reduce loss to about 2 percent.

The formal guarantee says that for any two datasets and that differ by one person, the probability of any output set barely moves:

At the factor is , so a single person's presence changes the odds of any model output by at most 65 percent plus the slack; at the factor is 22,026, which is why practitioners treat epsilon as a log-scale quantity and argue about whether 1.0 or 8.0 is the right target rather than whether it is small.

In DP-SGD the noise itself is calibrated to the clip bound through the Gaussian mechanism:

With unit clipping (), and a per-step budget of , the square root evaluates to , so the noise multiplier is about 4.84. That noise then composes over training: advanced composition turns steps each costing into

For steps, and , the first term is and the second is , giving instead of the naive sum of 100. This is the number to put in the model card, alongside the measured accuracy delta, because auditors and product reviewers will ask for both.

ThreatSignal to logTypical controlResidual risk
Membership inferencePer-record loss distributionDP-SGD, output perturbationWeaker models leak more
Model inversionConfidence on synthetic probesCap top-1 confidence, rate limitAttribute inference remains
Training data extractionn-gram overlap with promptsDedup training data, canary tokensLong-tail memorization
Prompt injectionInstruction-looking input patternsInput filters, tool allow listsNovel phrasings slip through
Model stealingQuery volume per accountRate limits, watermarkingOffline distillation

Secure Inference Pipeline

Secure Inference PipelineInputUser RequestEncrypted DataAuthenticationValidationInput SanitizationSchema ValidationAttack DetectionEncryptionHomomorphic Enc.Secure EnclaveKey ManagementInferencePrivate PredictionModel ExecutionResult CachingOutputResponse FilterEncryptionAudit Logging

Compliance Framework

A comprehensive ML compliance framework addresses regulatory requirements like GDPR through systematic assessment and documentation. Key components include: assessing compliance with processing principles (lawfulness, fairness, transparency, purpose limitation, data minimization); checking automated decision-making rules (right to human intervention, explanation, and contest); validating data protection by design principles; and maintaining data processing records as required by Article 30. The framework should generate privacy policies, track compliance status across articles, identify gaps, and maintain audit logs for accountability.

Interview Q&A

Q1: How would you protect an ML model from adversarial attacks in production?

Answer:

  1. Input Validation: Implement robust input validation and sanitization
  2. Adversarial Training: Train models with adversarial examples to improve robustness
  3. Ensemble Methods: Use multiple models and aggregate predictions
  4. Input Transformation: Apply preprocessing like feature squeezing
  5. Certified Defenses: Use randomized smoothing for certified robustness
  6. Monitoring: Deploy adversarial detection systems in production

Q2: Design a privacy-preserving ML system that complies with GDPR

Answer: Architecture:

  1. Data Layer

    • Differential privacy for training data
    • Data anonymization/pseudonymization
    • Purpose limitation controls
  2. Model Layer

    • Federated learning for distributed training
    • Secure multi-party computation
    • Model ensembles for privacy
  3. Inference Layer

    • Homomorphic encryption for predictions
    • Secure enclaves for model execution
    • Output sanitization
  4. Compliance Layer

    • Data processing records
    • Privacy impact assessments
    • User consent management
    • Right to explanation implementation

Q3: Explain the trade-off between model accuracy and privacy guarantees

Answer:

Accuracy-Privacy Trade-off:

  • Higher privacy (lower epsilon) requires more noise, reducing accuracy
  • Typical epsilon values: epsilon = 1 gives strong privacy with about 5 percent accuracy loss, epsilon = 10 gives moderate privacy with about 2 percent loss
  • Mitigation strategies: larger datasets, better noise calibration, private aggregation

Recommendations:

  • Start with epsilon = 1.0, adjust based on use case
  • Use privacy amplification through subsampling
  • Combine with other privacy techniques (federated learning, secure computation)
  • Monitor for privacy leakage through membership inference attacks

Common Mistakes

Treating anonymization as privacy

Fix: Re-identification works on weakly anonymized rows; use DP-SGD or federated training so privacy holds even after linkage.

Tuning epsilon without measuring accuracy

Fix: Report epsilon, delta, and the accuracy delta together; a guarantee nobody can afford is not a guarantee you can ship.

Defending only the training pipeline

Fix: Harden inference too: rate limit, sanitize inputs, filter outputs, and log access, since prompt injection and model stealing happen at serving time.

Best Practices

  • Clip per-example gradients, calibrate noise from the Gaussian mechanism, and publish epsilon with the model card
  • Run membership inference and extraction probes against every release, not just once at launch
  • Encrypt data at rest and in transit, keep per-purpose access logs, and implement deletion as an automated pipeline

Key Takeaways

  • Differential privacy bounds influence as P[M(D) in S] no more than e^epsilon times P[M(D') in S] plus delta; epsilon = 0.5 is a 65 percent odds shift
  • Gaussian noise for a unit clip bound at epsilon = 1.0 and delta = 1e-5 needs a multiplier of 4.84
  • Advanced composition turns 10,000 steps at 0.01 each into epsilon total near 5.8, not the naive 100
  • Defense is layered: input validation, adversarial training, output filtering, and audit logging each catch what the others miss

Frequently Asked Questions

What does epsilon actually measure?

Privacy loss on a log scale. An epsilon of 0.69 means the odds of any output shift by at most a factor of 2 when one person joins or leaves the dataset, an epsilon of 2.3 is a factor of 10, and an epsilon of 10 is a factor of 22,026. Because the factor grows exponentially, small changes in epsilon matter: moving from 1.0 to 8.0 is not 8 times more exposure, it is roughly 1,000 times more. Teams should pick epsilon from the sensitivity of the domain - health data sits below 1.0, ad click counts can sit near 8.0 - and then hold it as a budget the same way they hold an error budget.

Is differential privacy the only privacy tool we need?

No, and it is not free. DP-SGD adds noise to every gradient step, which typically costs 2 to 5 accuracy points on small datasets and can be tuned away with more data or larger batches. In practice you combine mechanisms: federated learning keeps raw data on device, secure multi-party computation protects aggregation, encryption covers storage and transit, and differential privacy covers the statistics that actually leave the boundary. Each layer costs latency or accuracy, so pick the smallest set that closes your threat model.

How do we respond to a data subject deletion request when the model already trained on their rows?

You cannot unlearn a row from gradient descent directly, so design for it up front: keep training manifests keyed by subject id, prefer retraining from an excluded dataset when the model is small, or use machine unlearning / influence-function approximations for large models with a measured forgetting test. Under GDPR Article 17 the practical answer is a documented pipeline that removes the source rows, retrains or fine-tunes within an agreed window, and records what was done - auditors accept a tested process faster than they accept a perfect algorithm that does not exist.

Interview Questions

Q1: Walk me through defending an LLM chatbot against prompt injection and data exfiltration.

Layer it: classify and strip instruction-like input patterns before the model, run the model with an allow list of tools so output cannot open arbitrary URLs, scan responses for PII patterns with a regex and a classifier, and rate limit per account so scripted harvesting is expensive. Log every tool call, and canary the system prompt so you can detect when an attacker has extracted it.

Q2: You must train on 10 million medical records with a privacy guarantee. How do you set epsilon and what does it cost you?

Fix delta at 1e-5 or below the inverse dataset size, start at epsilon = 1 to 2, and use subsampled DP-SGD with clip norm 1.0 and a noise multiplier from the Gaussian mechanism. On 10 million rows the accuracy cost is typically 1 to 3 points because the sample is large; I would validate with membership inference attacks and report epsilon, delta, and the accuracy delta together in the model card.

Q3: How would you detect a poisoned training pipeline before the model ships?

Check provenance hashes on every dataset snapshot, run influence or per-sample loss scoring to find outliers that dominate the gradient, verify label distribution and canary counts against the previous release, and validate the final model on a held-out clean set. In production add backdoor scans: trigger-pattern probes that measure whether a suspicious input flips the prediction.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement