Privacy-Preserving Analytics and Experimentation Questions
Doing measurement and data science without over-collecting or exposing individuals: privacy-preserving experiment design, aggregate and on-device measurement, and privacy-respecting attribution. Covers techniques for analytics and A/B testing that limit personal-data use and honor consent. Includes reconciling measurement quality with privacy constraints.
HardTechnical
82 practiced
Provide a high-level implementation plan and key PyTorch or TensorFlow code snippets for training a DP-GAN that generates tabular data with mixed categorical and numeric features. Include how to implement per-example gradient clipping and noise addition for both generator and discriminator, how to integrate an RDP accountant, and which metrics to log to evaluate privacy and utility during training.
Sample Answer
High-level plan1. Clarify requirements: privacy budget (ε, δ target), dataset schema (which cols categorical vs numeric), utility targets (downstream task, distributional similarity).2. Model design: conditional GAN for mixed data (embedding layers for categorical features, continuous heads for numerics). Use architectures with small capacity to reduce required noise.3. Privacy: apply DP-SGD (per-example clipping + Gaussian noise) to both discriminator and generator updates (if generator trained with gradients that depend on real data — usually discriminator sees real data; if generator training uses discriminator output only, generator can be non-DP, but you requested DP for both so we add DP noise there too).4. Accounting: use RDP accountant each epoch to compute (ε, δ) from sigma, clipping, batch_size, dataset_size, and steps.5. Metrics: log privacy (ε for target δ), training losses, Wasserstein/JS estimates, feature-wise KS/JS, pairwise correlations, classifier AUC on real vs synthetic (propensity score), and utility on downstream tasks.6. Iterate hyperparameters (clip norm, noise multiplier, batch size) to trade privacy/utility.PyTorch (recommended: Opacus for per-sample grads; functorch for generator if needed)- Using Opacus for discriminator (handles per-sample clipping + noise + accounting).- For generator, if you require per-example clipping you can compute per-sample grads via functorch.vmap and add Gaussian noise manually before optimizer step.Example: discriminator with Opacus and RDP accountingPyTorch: generator per-sample clipping via functorch + manual noise(Implementing per-sample gradient aggregation is complex; functorch + helper utilities or Opacus extensions can simplify.)TensorFlow (using tensorflow_privacy)Key concepts / reasoning- Per-example gradient clipping bounds sensitivity so adding Gaussian noise yields DP guarantees.- RDP is preferred for composition and tight ε estimates; convert RDP -> (ε, δ) after each epoch or at end.- Larger batch sizes reduce noise per example (for same noise multiplier) but change privacy accounting (sample_rate).- Often only discriminator needs DP because generator updates depend only on discriminator outputs; however if generator directly touches real data (e.g., reconstruction loss), you must DP it too.Metrics to log (privacy + utility)- Privacy: ε at target δ using RDP accountant every epoch/step.- Training: generator & discriminator losses, gradient norms, noise multiplier, clip norm.- Distributional similarity: per-feature KS statistic, JS divergence for categorical distributions, marginal histograms.- Correlations: Pearson/Spearman and pairwise mutual information differences.- Downstream utility: classifier AUC/F1 trained on synthetic and tested on real (or vice versa), propensity score (train model to distinguish real vs synthetic; lower AUC = better).- Sample quality: nearest-neighbor distances to training set (privacy leakage check), likelihood if applicable.Practical tips- Start with strong clipping (small norm) and moderate noise multiplier; tune for utility.- Use public data or hold-out set to validate utility without consuming privacy budget.- Prefer established libraries: Opacus (PyTorch) or tensorflow_privacy to avoid subtle bugs in DP math.- Log privacy budget continuously to ensure you don't exceed target ε.
python
import torch
from opacus import PrivacyEngine
# model, dataloader, optimizer_d defined
privacy_engine = PrivacyEngine(
module=disc,
sample_rate=batch_size / len(dataset),
alphas=[1 + x/10. for x in range(1, 100)], # RDP orders
noise_multiplier=noise_multiplier,
max_grad_norm=clip_norm,
)
privacy_engine.attach(optimizer_d)
for epoch in range(epochs):
for real_batch in loader:
# standard GAN discriminator step
optimizer_d.zero_grad()
loss_d = discriminator_loss(real_batch, gen)
loss_d.backward()
optimizer_d.step()
eps, best_alpha = privacy_engine.get_privacy_spent(delta=target_delta)
print(f"Epoch {epoch} ε = {eps:.3f}, δ = {target_delta}")python
from functorch import make_functional_with_buffers, vmap, grad
# make functional for generator
f_gen, params_gen, buffers = make_functional_with_buffers(gen)
def loss_fn(params, buffers, z, real_labels):
fake = f_gen(params, buffers, z)
return generator_loss_from_disc(fake, disc)
# compute per-sample grads
per_sample_grads = vmap(grad(loss_fn), in_dims=(None, None, 0, 0))(params_gen, buffers, z_batch, real_labels_batch)
# clip per-sample grads (L2 across parameters)
def clip_and_aggregate(per_sample_grads, max_norm):
norms = torch.stack([torch.sqrt(sum((g**2).sum() for g in sample))) for sample in zip(*per_sample_grads)])
scales = (max_norm / (norms + 1e-6)).clamp(max=1.0)
# scale each sample's grads then sum and add noise
aggregated = [ (g * scales.view(-1, *([1]* (g.dim()-1)))).sum(0) for g in per_sample_grads ]
return aggregated
agg_grads = clip_and_aggregate(per_sample_grads, clip_norm)
# add Gaussian noise
for g in agg_grads:
g += torch.normal(0, noise_multiplier*clip_norm, size=g.shape, device=g.device) / batch_size
# load into optimizer & step (manual param update or set gradients then optimizer.step)python
import tensorflow as tf
from tensorflow_privacy.privacy.optimizers.dp_optimizer_keras import DPKerasAdamOptimizer
from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent
optimizer_d = DPKerasAdamOptimizer(
l2_norm_clip=clip_norm,
noise_multiplier=noise_multiplier,
num_microbatches=batch_size, # or set microbatches <= batch_size
learning_rate=lr
)
# compile discriminator with optimizer_d and train via gradient tape
# compute RDP epsilon each epoch:
orders = [1 + x/10. for x in range(1, 100)]
sampling_prob = batch_size / dataset_size
rdp = compute_rdp(q=sampling_prob, noise_multiplier=noise_multiplier, steps=steps, orders=orders)
eps, opt_order = get_privacy_spent(orders, rdp, target_delta)
print(eps)HardSystem Design
91 practiced
Design a production system for private inference where clients submit encrypted inputs and receive model outputs without the server learning inputs or leaking model parameters. Compare homomorphic encryption (HE), secure multi-party computation (MPC), and trusted execution environments (TEE) in terms of latency, throughput, supported model classes, and deployment complexity. Recommend approach(es) for low-latency web services vs batch processing.
Sample Answer
Requirements & constraints:- Confidentiality of client inputs (server learns nothing).- Model confidentiality (no leakage of weights/APIs).- Low latency for interactive web and high throughput for batch.- Practical deployment with maintainability and cost-awareness.High-level architecture options:- HE-only: client encrypts input with HE scheme, server evaluates model homomorphically, returns encrypted result; client decrypts.- MPC: client and server (or server + helper) run a secure protocol jointly to compute inference without revealing inputs or model.- TEE: server runs model inside enclave (SGX/AMD SEV); client establishes attested secure channel and sends plaintext input to enclave.Comparison (latency / throughput / models / complexity):- HE - Latency: high per-request latency (seconds+ for deep nets). - Throughput: low; heavy CPU/GPU limitations; batched evals possible but costly. - Supported models: arithmetic circuits efficient for linear layers + low-degree activations (CKKS supports approximate FP); deep non-linear nets require approximations (polynomial activations, quantization). - Deployment complexity: moderate — crypto libs (SEAL, PALISADE), key management; no trusted hardware.- MPC - Latency: moderate to high depending on rounds and network; semi-honest OT-based protocols can be tens–hundreds ms per op across LAN, more over WAN. - Throughput: medium; can be parallelized; communication-bound. - Supported models: flexible — works with arbitrary functions using garbled circuits or secret-sharing; optimized for ReLU-based nets via specialized protocols. - Deployment complexity: high — multiple parties, orchestration, network reliability, cryptographic expertise.- TEE - Latency: low — near-native inference latency. - Throughput: high — uses hardware acceleration (GPU passthrough depending on tech). - Supported models: full model compatibility. - Deployment complexity: low-to-moderate — rely on vendor hardware, attestation, patching enclaves; risk: side-channels and trust boundary.Recommendations:- Low-latency web services (interactive): prefer TEE for practical performance and developer velocity. Mitigate risks with strict attestation, memory-hard models split (keep most sensitive ops in enclave), and monitoring. If threat model disallows trusting hardware vendor, use hybrid TEE+MPC: handle latency-critical layers in TEE, sensitive layers via MPC.- Batch processing (large-scale, offline): HE or MPC depending on model. For linear/heavily-quantized models, HE (CKKS) for encrypted batch inference with vectorized SIMD offers good throughput. For complex non-linear models where model secrecy is critical and latency is less important, MPC (with pre-processing / offline phases) gives stronger cryptographic guarantees.- Hybrid patterns: split model — run initial feature extraction in enclave or plaintext on client, then HE/MPC for sensitive final layers to balance latency and privacy.Practical notes:- Start with threat model and benchmarks: measure latency and cost on representative inputs.- Use libraries: Microsoft SEAL, TF Encrypted, CrypTen, Intel SGX SDK, or cloud TEE offerings (Azure DC/Confidential Computing).- Monitor side-channels, plan key rotation, and legal/compliance constraints (data residency).
EasyTechnical
92 practiced
Explain secure aggregation in federated learning: goals, high-level steps, and why it matters for privacy-preserving model training. Describe how clients mask updates so the server only learns the aggregated sum, mention common protocols (for example Bonawitz et al.), and enumerate practical failure modes like client dropouts, key exchange failures, and performance/latency trade-offs.
Sample Answer
Secure aggregation in federated learning ensures the server learns only the aggregate (e.g., sum or average) of clients’ model updates, not individual updates—preserving user privacy while still enabling centralized model training.Goals:- Confidentiality: prevent server (and other clients) from seeing individual updates- Integrity: ensure aggregate is correct despite dropouts or faults- Practicality: reasonable computation/communication overheadHigh-level steps (typical mask-and-sum pattern):1. Setup: clients agree keys or seeds (pairwise or via threshold crypto).2. Masking: each client masks its update by adding pseudo-random masks that cancel out when summed (e.g., client i adds mask_ij and subtracts mask_ji for every peer j).3. Upload: clients send masked updates to server.4. Aggregate: server sums masked updates; pairwise masks cancel, revealing only the true aggregate.5. Unmasking/Recovery: if some clients drop, protocol uses secret shares/threshold decryption to recover/cancel remaining masks.Common protocols:- Bonawitz et al. (2017/19): practical secure aggregation using Diffie–Hellman-derived pairwise masks + Shamir secret sharing to tolerate dropouts and avoid trusting a coordinator.- Homomorphic encryption and multi-party computation (MPC) variants are alternative approaches.Why it matters:- Protects user-level privacy in sensitive domains (health, mobile telemetry) and helps meet regulatory/ethical requirements while enabling model utility.Practical failure modes and trade-offs:- Client dropouts: if many clients drop, masks may not cancel—mitigated with secret sharing or threshold schemes but increases complexity.- Key exchange failures or dishonest clients: require robust authentication and detection; malicious clients can corrupt aggregate unless using integrity checks or robust aggregation.- Performance/latency: pairwise masks scale O(n^2) in naive implementations; Bonawitz reduces overhead but still adds CPU, memory, and network cost compared to plain FL.- Scalability and stragglers: waiting for many clients increases wall-clock training time; systems often use partial participation or skip slow clients at some privacy cost.In practice, choose a protocol (Bonawitz for on-device FL) and tune participant counts, dropout thresholds, and cryptographic parameters to balance privacy, reliability, and latency.
EasyTechnical
94 practiced
List common de-identification techniques (masking, tokenization, generalization, suppression) and outline a practical pipeline to de-identify a transactional user dataset while measuring re-identification risk and preserving utility. Include steps for identifying quasi-identifiers, choosing transformations per attribute, and validating impact on downstream ML tasks.
Sample Answer
Common de-identification techniques:- Masking: replace parts of values (e.g., show last 4 digits).- Tokenization / pseudonymization: replace identifier with stable token/ID.- Generalization: bucket values (age → age-range, timestamp → day).- Suppression: remove entire field or rare values.- Perturbation/noise: add noise to numeric features (can be DP).- Hashing: one-way transform (caveat: vulnerable to brute-force).Practical pipeline for a transactional user dataset1. Inventory & threat model - List attributes (user_id, email, phone, name, dob, zipcode, transaction_amount, merchant, timestamp). - Define attackers (public registry matching, internal curious analyst).2. Identify quasi-identifiers (QIs) - QIs = {dob, zipcode, gender, transaction timestamps/patterns, merchant}. Anything combinable with external data.3. Choose transformations per attribute (examples) - user_id/email/name: tokenization + secure mapping in vault. - phone/ssn: masking or full suppression. - dob: generalize to year or age-band. - zipcode: truncate to 3-digit or county. - timestamp: round to day/hour or remove precise times. - transaction_amount: bucket or add calibrated noise. - merchant/category: keep category level, suppress very rare merchants.4. Apply k-anonymity / l-diversity constraints - Enforce k≥5 on QI groups by generalization/suppression. Monitor attribute distributions to maintain l-diversity for sensitive labels.5. Measure re-identification risk - Record linkage simulation: attempt matching against public datasets; compute unique QI combinations proportion. - Risk metrics: percentage of records with uniqueness=1, re-id probability estimate, average risk per record. - Optionally evaluate differential privacy budgets (ε) if DP mechanisms used.6. Preserve utility & validate downstream ML - Split pipeline: produce de-identified training and holdout raw (if allowed). - Train models on original vs de-identified data; compare metrics (AUC, RMSE), calibration, feature importances. - Run fairness checks and drift tests; log changes in predictive performance and per-subgroup impact. - If utility loss > threshold, iterate: relax suppression, change bucket sizes, or apply targeted synthetic data augmentation.7. Operationalize & governance - Store token maps in secure vault; audit access; maintain provenance. - Re-run risk assessment periodically and after schema changes.Key reasoning:- Balance privacy (reduce uniqueness) vs utility (preserve signal). Use metrics (k-anonymity, re-id rate) to quantify privacy and standard ML metrics to quantify utility; iterate until acceptable trade-off.
MediumSystem Design
94 practiced
Design a privacy-preserving A/B testing service for a consumer product with 1M monthly active users. Requirements: support 500 concurrent experiments, enforce per-user epsilon budgets, provide reliable noisy p-values for teams, allow cross-team budget requests and reservations, and produce immutable audit trails. Describe key architecture components, how privacy enforcement is implemented, and how to scale and shard budgets across millions of users.
Sample Answer
Requirements clarification:- 1M MAU, 500 concurrent experiments, per-user epsilon budgets, cross-team reservations, noisy p-values, immutable audit.High-level architecture:- Experiment Orchestrator API (creates experiments, reservations, policies)- User Assignment Service (deterministic bucketing + exposure logging)- Privacy Ledger (per-user epsilon accounting store, sharded, append-only)- DP Aggregation Service (secure aggregator computing noisy metrics & p-values)- Reservation Manager (handles cross-team budget reservations/locks)- Audit Store (immutable event log: assignments, queries, budgets; append-only storage like WORM on cloud object store + Merkle tree index)- Monitoring & Policy UIPrivacy enforcement:- Use local epsilon per user tracked centrally in Privacy Ledger. Each exposure or metric computation consumes epsilon via a token-based model. Assignments are deterministic (hash(user_id, experiment_id, salt)) so exposure only counted once per experiment-treatment.- DP mechanisms: for mean/CTR use Gaussian mechanism calibrated by delta; for p-values use permutation tests with DP-noise added to test statistics (or use bootstrapped private hypothesis tests like DP t-test). The DP Aggregation Service requires a verified epsilon input; it will refuse queries exceeding available reserved epsilon for the affected user cohort.- Compose per-user epsilon via advanced composition or privacy accountant (Moment Accountant) to compute remaining budget.Cross-team reservations:- Reservation Manager exposes API to request epsilon for a set of users/time window. It checks current budget commitments in Privacy Ledger, reserves tokens if available, returns reservation id. Supports priority/preemption policies and TTL. Reservation and consumption are atomic via transactions on the shard owning the user range.Sharding & scaling:- Shard Privacy Ledger by user-id ranges (e.g., consistent hashing) across N nodes; each node holds local epsilon counters and exposes atomic decrement/reserve operations. 1M users small but design scales to tens of millions. Use per-shard caches for high-throughput reads; enforce strong consistency for writes via lightweight leader per shard.- User Assignment Service is stateless and scales horizontally behind CDN. DP Aggregation runs as serverless jobs over pre-aggregated per-shard partial aggregates: each shard computes noisy partials (with shard-level noise calibrated so total noise meets target via noise partitioning) and signed partials are combined centrally to produce final noisy metrics and p-values. This avoids moving raw user data.Auditability:- Every assignment, reservation, consumption, aggregation request emits an immutable event recorded to Audit Store and indexed with Merkle roots. Provide cryptographic proofs of budget state and query authorization.Operational notes:- Enforce per-experiment caps (max epsilon per user per experiment), global per-user cap.- Provide SDK that logs exposures and enforces local checks to avoid double-counting.- Offer simulation tools to estimate statistical power under DP noise; recommend experimenters request reservations with power targets to guide epsilon allocation.This design balances strict per-user privacy accounting, practical DP metrics, cross-team coordination, and horizontal scalability.
Unlock Full Question Bank
Get access to hundreds of Privacy-Preserving Analytics and Experimentation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.