Model Privacy and Extraction Defense: Membership Inference, Surrogates, and Prediction API Controls
Model Privacy and Extraction Defense: Membership Inference, Surrogates, and Prediction API Controls
Search
Ask the AI

Model Privacy and Extraction Defense: Membership Inference, Surrogates, and Prediction API Controls

A model can leak whether a record participated in training. Membership inference uses signals such as loss or confidence to estimate that membership; its performance depends on the model, data, and false-positive threshold. For models trained on medical records, chat logs, or proprietary code, measure the attack’s true-positive rate at a specified low false-positive rate.

1. The Mathematics of Differential Privacy (DP)

DP-SGD (Differentially Private Stochastic Gradient Descent) combines sampling, per-sample clipping, noise calibrated to sensitivity, and privacy accounting. Its guarantee bounds the distribution of outputs on neighbouring datasets; it does not require two trained weight vectors to be close point by point. State the adjacency unit as well: this article uses the addition or removal of one record. Multiple records from one person require analysis for that protection unit.

A randomized algorithm \(\mathcal{M}\) satisfies \((\epsilon, \delta)\)-Differential Privacy if the following inequality holds for every pair of datasets \(D\) and \(D^{\prime}\) differing by at most one record and every measurable output event \(S \subseteq \text{Range}(\mathcal{M})\):

$$ P[\mathcal{M}(D) \in S] \le e^\epsilon P[\mathcal{M}(D^{\prime}) \in S] + \delta $$

  • \(\epsilon\) (Privacy Loss Bound): Controls the multiplicative bound on output-event probabilities for neighbouring datasets. A smaller \(\epsilon\) gives a tighter bound when \(\delta\) and the adjacency relation are fixed.
  • \(\delta\) (Additive Relaxation): The additive term in the definition. It is not directly the probability that a particular record is exposed, and it does not automatically imply cryptographic security. The scale \(< 1/|D|\) can guide parameter selection; justify the chosen value against dataset size and risk.

2. Real-World Membership Inference Attacks

LiRA (Likelihood Ratio Attack) uses shadow models to estimate score distributions for the same example when it is included in or excluded from training. Let \(s_\theta(x,y)\) denote the logit transform of the target model’s confidence in the true class. Let \(p_{in}\) and \(p_{out}\) be the corresponding densities. A likelihood-ratio statistic is:

$$ \Lambda(x, y) = \frac{p_{in}(s_\theta(x,y))}{p_{out}(s_\theta(x,y))}. $$

LiRA fits Gaussian distributions to shadow-model scores and applies a threshold to the likelihood ratio. Calibrate that threshold on non-members and report false-positive and true-positive rates. Membership decisions can be wrong. Evaluate LLMs trained on private code or PII under their own data and attack conditions.

3. PyTorch Implementation: DP-SGD Gradient Clipping

The following teaching implementation computes per-sample gradient clipping and adds Gaussian noise. It assumes reduction='none' and a loss for each sample that depends only on that sample and the model parameters. Training-mode BatchNorm and other cross-sample operations violate this condition. The function illustrates one update; configure and validate sampling, privacy accounting, and production randomness separately.

import torch
import torch.nn as nn

def dp_sgd_step(model: nn.Module, optimizer: torch.optim.Optimizer, 
                loss_fn, x: torch.Tensor, y: torch.Tensor, 
                max_grad_norm: float = 1.0, noise_multiplier: float = 0.5):
    optimizer.zero_grad()
    
    # Forward pass
    logits = model(x)
    # Compute per-sample losses (reduction='none' is critical)
    losses = loss_fn(logits, y)
    
    saved_grads = {name: torch.zeros_like(param) for name, param in model.named_parameters()}
    
    # 1. Per-sample gradient computation and clipping
    for i in range(x.size(0)):
        losses[i].backward(retain_graph=True)
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_grad_norm)
        
        for name, param in model.named_parameters():
            if param.grad is not None:
                saved_grads[name] += param.grad.data
            param.grad = None # clear for next sample
            
    # 2. Add Gaussian Noise scaled by sensitivity (max_grad_norm)
    for name, param in model.named_parameters():
        if param.requires_grad:
            noise = torch.normal(
                mean=0.0, 
                std=noise_multiplier * max_grad_norm, 
                size=param.size(), 
                device=param.device
            )
            # Average the noisy gradients over the batch
            param.grad = (saved_grads[name] + noise) / x.size(0)
            
    optimizer.step()

4. Enterprise Inference Architecture Guardrails

For a public prediction API, access controls, query-rate limits, and output granularity can mitigate model extraction. The preserved diagram is one candidate architecture. Validate its query rules and output policy against the service’s task; the presence of these modules alone does not establish protection.


graph LR
    A[Client Request] --> B[API Gateway / WAF]
    B --> C{Query Entropy Analysis}
    C -->|High Variance| D[Rate Limit / Tarpit]
    C -->|Normal| E[Inference Engine]
    E --> F[Output Perturbation Layer]
    F -->|Top-K Logits Only| A
    F -->|Rounding/Bucketing| A

Key Defenses:

  • Output Granularity (Output Perturbation): Choose full probabilities, top-K classes, or confidence buckets according to the application, and measure utility and extraction risk. Rounding to 2 decimal places reduces output detail, but label-only APIs can also be extracted. Rounding alone supplies no DP guarantee.
  • Query-Pattern Monitoring: Treat query volume and similarity across accounts, tokens, or IP blocks as investigation signals. Validate rules against legitimate traffic and false positives before applying rate limits or API tarpitting. Query traces alone do not identify the attacker’s active-learning algorithm.

5. Privacy Risk Evidence Matrix

The matrix below connects privacy risk to observable engineering evidence and records the measurable trade-offs of each defense.

Risk Measurement Defense knob Residual risk to document
Membership inference MIA AUC, confidence gap between train and holdout samples, calibration error DP-SGD, regularization, early stopping, confidence rounding Strong privacy can reduce utility, especially on rare classes
Model extraction Query volume, boundary-probing rate, surrogate agreement score Rate limits, entropy throttling, top-k outputs, response bucketing Public APIs can still leak coarse decision boundaries over long periods
Training data memorization Canary exposure, exact-match generation rate, rare sequence recall Deduplication, DP fine-tuning, redaction, memorization tests Rare sensitive examples may remain vulnerable even after aggregate tests pass
Telemetry leakage Logs containing raw prompts, identifiers, or high-cardinality features Log minimization, retention windows, field-level hashing Security analytics still need enough signal to detect abuse

Per-sample clipping in DP-SGD

In the DP-SGD construction used here, clip each sample’s gradient norm to a chosen threshold before adding noise to the sum. This bounds a record’s gradient contribution to one update. The training run’s \((\epsilon,\delta)\) guarantee also depends on sampling and accounting for the noise and number of steps.

Ordinary training code often averages or sums a batch loss before calling loss.backward(); clip_grad_norm_ then clips the aggregate gradient. The preserved counterexample below concerns substituting batch clipping for per-sample clipping while reusing the same DP-SGD accountant. Read its original “DP guarantee does not hold” comment within that scope.

# wrong: clips the batch gradient, so the DP guarantee does not hold
loss = criterion(model(x_batch), y_batch)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), C)   # batch level

This code can train normally, but it does not perform the per-sample clipping required by this DP-SGD construction. Its sensitivity and accountant therefore cannot be reused directly. Clipping a batch vector also creates a norm bound; a different DP construction would need noise calibrated to its own adjacency, sampling, and sensitivity. Convergence alone does not justify a reported ε.

The correct approach computes each sample’s gradient, clips each, then sums and adds noise:

for x_i, y_i in zip(x_batch, y_batch):              # conceptually per-sample
    g_i = grad_of(loss(model(x_i), y_i))
    g_i = g_i * min(1.0, C / (g_i.norm() + 1e-6))   # per-sample clipping
    accum += g_i
accum += torch.normal(0, sigma * C, accum.shape)    # noise scale set by C

The dp_sgd_step in section three calls backward for each sample, clips, and accumulates. The setting reduction='none' retains per-sample losses, and param.grad = None clears the preceding sample’s gradient. Under the sample-independence condition above, this implements per-sample clipping. It does not implement the full sampling and accounting pipeline.

A Python loop over samples adds overhead. Libraries such as Opacus can organise per-sample gradients, clipping, noise, sampling, and accounting; model compatibility still requires checking. DP depends on whether the algorithm and implementation meet the analysis assumptions. A particular library is neither required nor a substitute for those checks.

In the section-three implementation, the noise standard deviation is noise_multiplier * C. Increasing the clipping threshold C while holding the noise multiplier fixed increases the noise as well. Record clipping rates, task performance, and accounting results when choosing the threshold.

ε and the Scope of Privacy Guarantees

In the \((\epsilon,\delta)\)-DP definition in section one, ε controls the multiplicative term and δ supplies additive slack. Only when δ = 0 (pure ε-DP) does adding or removing one record give a purely multiplicative e^ε bound for every output event. The original values below illustrate that factor. When δ > 0, retain the additive term as well.

Substituting a few values shows the magnitudes involved:

ε = 0.1  ->  e^0.1 ≈ 1.11      probability changes by at most ~10%
ε = 1    ->  e^1   ≈ 2.72      probability changes by at most ~172%
ε = 3    ->  e^3   ≈ 20.1      probability changes by at most ~20×
ε = 10   ->  e^10  ≈ 22026     probability changes by at most ~22,000×

With δ and adjacency fixed, ε = 10 gives a much looser multiplicative bound than ε = 3. It is not the success rate that a particular attack must attain. Report ε together with δ, the protection unit, training steps, sampling mechanism, and accounting method.

The following scope and composition conditions distinguish these guarantees:

  • Population statistics and individual protection: DP permits learning population patterns. Under record-level adjacency, multiple records from one person or group require group-privacy analysis, with weaker guarantees as the record count grows. This differs from prohibiting the release of population statistics.
  • Assess model extraction separately: Training DP bounds changes in output distributions caused by a record’s participation. It does not guarantee that an API’s prediction function cannot be copied. Test access controls, query management, and output granularity against that separate threat.
  • Compose repeated access to private data: Repeated training or new runs of a private-data mechanism require composition accounting. Inference from one released DP model is post-processing when it uses only that model and the query input, without accessing private training data again. More such queries do not themselves spend further training privacy budget.

Report ε and δ alongside the threat and protection unit. For example, specify add-or-remove-one-record adjacency and the training sampler and accountant, then measure membership-inference true-positive rates at a chosen false-positive rate. An isolated ε = 3 does not determine a universal membership confidence: that interpretation also needs prior information, δ, and an attack setting.

6. References

Leave a Reply

Scroll down