Skip to content

DP-SGD in depth: clipping, noise and the privacy budget

Follow one DP-SGD step - clip each row's gradient, add noise, take the step - then see how the noise multiplier, sampling rate and number of steps set ε, what costs accuracy, and what the guarantee leaves out.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Compute a clipped per-row gradient and the noisy average of a batch
  • Explain how the noise multiplier, sampling rate and steps combine into ε
  • Choose a clipping norm and say why clipping biases the gradient
  • Train a private CodeSplash network and state what its ε covers

Read first

01

One private step

Read

DP-SGDDP-SGDTraining that clips each row's gradient and adds Gaussian noise to every step, so the model is differentially private. changes each training step in three ways:

  1. Clip each row's gradient gig_i to length at most CC:   gˉi=gi/max⁡(1,∥gi∥/C)\;\bar g_i = g_i / \max(1, \lVert g_i \rVert / C).
  2. Add noise to the sum:   g~=1B(∑igˉi+N(0,σ2C2I))\;\tilde g = \frac{1}{B}\big(\sum_i \bar g_i + \mathcal N(0, \sigma^2 C^2 I)\big).
  3. Step with g~\tilde g as usual.

Clipping bounds how far any one row can move the weights; the noise hides whether that row was there at all. The batch is drawn by Poisson samplingPoisson samplingEach row joins each batch independently with chance batch size ÷ rows, so batch sizes vary.: each row joins with probability qq.

02

Clip, then add noise

Read

In the reference's example, two rows have gradients (3,4)(3, 4) and (0.3,0.4)(0.3, 0.4) with C=1C = 1. The first has length 5 and is scaled down to length 1; the second, already shorter, is kept. Noise with σ=0.5\sigma = 0.5 is added to their sum and divided by two.

Python printed 0.450 for the first coordinate and R printed 1.022: the two programs draw different noise. CodeSplash's own DP-SGD draws its noise from the shared random stream, so a private network trains the same in Python and R.

03

What sets ε

Read

A Rényi-DP accountantRényi-DP accountantAdds up the privacy cost of every DP-SGD step in Rényi divergence, then converts the total to (ε, δ). adds up the privacy cost of every step. Three things drive the total εPrivacy budget (ε)How much one person's row may change what a private computation shows; smaller is more private.:

  • the noise multiplierNoise multiplier (σ)In DP-SGD, the noise's standard deviation divided by the clipping norm; more noise, smaller ε. σ: more noise, smaller ε;
  • the sampling rate qq = batch size ÷ rows: smaller batches relative to the data, smaller ε;
  • the number of steps: every epoch spends more budget.

So "train longer" and "use bigger batches" both cost privacy unless σ grows. Set a target ε and CodeSplash finds the smallest σ that reaches it for the planned steps.

04

The clipping norm

Read

CC trades two harms. Too small, and almost every row is clipped: the average gradient shrinks and points the wrong way, a bias no amount of training removes. Too large, and the noise, which scales with CC, swamps the signal. A common start is a CC near the typical per-row gradient length early in training.

DP-SGD also rules out things that let one row's gradient mix with others: mixup and row or class weights stop the run with a message, and so does resampling. Label smoothing and focal loss keep each row to itself, so they work with it: each row's gradient comes from its smoothed or focal loss, before clipping.

05

Train a private network

In the app
Deep neural network (torch MLP)Recorded · Python and R agreeRecorded 2026-11-25 · 33 values compared
R

Deep neural network (torch MLP): cross-validated ROC AUC 0.822 ± 0.019 over 3 folds; ROC AUC on the locked test set 0.809 (n = 106).

CV ROC AUC
0.8224
SD across folds
0.0188
Test ROC AUC
0.8089

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.83720.47100.80990.7504
211420.80120.54170.71830.6981
311420.82890.47820.78870.7640
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec d6ac628cd57815ee
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network itself is built by codesplashr's cs_deep_* twins.

# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("glu", "bmi")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  hidden_layers = c(6),
  activation = "relu",
  epochs = 2,
  learning_rate = 0.05,
  batch_size = 128,
  weight_decay = 0.0001,
  early_stopping = 0,
  validation_fraction = 0.1,
  dropout = 0,
  mc_passes = 0,
  variational_weights = FALSE,
  prior_scale = 1,
  kl_weight = 1,
  robust_training = "none",
  dro_step = 0.01,
  adv_epsilon = 0.1,
  adv_steps = 5,
  trades_beta = 6,
  loss = "cross_entropy",
  focal_gamma = 2,
  focal_alpha = NULL,
  dp_epsilon = 8,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson",
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_dp_epsilon/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    glu = "numeric",
    bmi = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.torch_mlp/binary_dp_epsilon/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
  warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL  # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
  yy <- y[rows + 1L]
  ww <- sample_weights(rows)
  if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
  r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
                      seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
  if (fold_id == 0) resampled <<- r$info
  r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)

# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  dp_epsilon = 8,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson",
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.torch_mlp/binary_dp_epsilon/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
  cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
  .deep_training_set(X, rows, fold_id, repeat_)
}
# A dense network on torch for R (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — Python's torch starts from the same weights and takes the same steps.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
ACTIVATION <- PARAMS$activation
DROPOUT <- as.numeric(PARAMS$dropout)
PASSES <- as.integer(PARAMS$mc_passes)
VARIATIONAL <- isTRUE(PARAMS$variational_weights)
ROBUST <- PARAMS$robust_training
# Any of the options on: train with cs_deep_fit_mlp_ext (otherwise the plain network, unchanged).
EXTENDED <- DROPOUT > 0 || PASSES > 0 || VARIATIONAL || ROBUST != "none"
if (PASSES > 0 && DROPOUT == 0 && !VARIATIONAL) {
  cs_error("CS_E_INVALID_OPTION", option = "Prediction passes", allowed = "0 unless dropout or variational weights are on", value = PASSES)
}
if (VARIATIONAL && DROPOUT > 0) {
  cs_error("CS_E_INVALID_OPTION", option = "Dropout", allowed = "0 with variational weights (their noise replaces it)", value = DROPOUT)
}
SUBGROUPS <- NULL
if (ROBUST == "group_dro" && is.null(SUBGROUPS)) {
  cs_error("CS_E_INVALID_OPTION", option = "Robust training", allowed = "Group DRO only with a Subgroups column", value = "group_dro")
}
if (ROBUST == "group_dro" && RESAMPLE != "none" && TASK != "regression") {
  cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none with Group DRO", value = RESAMPLE)
}
# Differential privacy (DP-SGD): with an epsilon or a noise multiplier set, every fit clips each row's
# gradient and adds noise (cs_deep_dp_*, turned on by the trainer's dp plugin above; the guarantee goes to
# dp.json). Off by default. These options can't be combined with it:
DP <- cs_deep_dp_settings(PARAMS)
if (!is.null(DP)) {
  if (VARIATIONAL || ROBUST != "none") {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with variational weights or robust training", value = "on")
  }
  if (RESAMPLE != "none") {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with resampling (copies of a row would each count)", value = "on")
  }
}

fit_model <- function(X, y, w) {
  if (cs_deep_dp_enabled() && !is.null(w) && diff(range(as.numeric(w))) > 0) {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with row or class weights", value = "on")
  }
  if (TASK == "regression") {
    # Standardize the target (training mean and population SD); predictions are mapped back.
    mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
    target <- (as.numeric(y) - mu) / sd; o <- 1L
  } else if (TASK == "binary") {
    mu <- 0; sd <- 1
    target <- as.numeric(y); o <- 1L
  } else {
    mu <- 0; sd <- 1
    target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
  }
  if (!EXTENDED) {
    fit <- cs_deep_fit_mlp(
      unname(X), target, w, TASK, HIDDEN, o,
      activation = ACTIVATION,
      epochs = as.integer(PARAMS$epochs),
      lr = PARAMS$learning_rate,
      batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
      weight_decay = PARAMS$weight_decay,
      early_stopping = as.integer(PARAMS$early_stopping) > 0,
      validation_fraction = PARAMS$validation_fraction,
      patience = max(1L, as.integer(PARAMS$early_stopping)),
      seed = SEED
    )
    return(list(params = fit$params, mu = mu, sd = sd, history = fit$history, best_epoch = fit$best_epoch))
  }
  fit <- cs_deep_fit_mlp_ext(
    unname(X), target, w, TASK, HIDDEN, o,
    activation = ACTIVATION,
    epochs = as.integer(PARAMS$epochs),
    lr = PARAMS$learning_rate,
    batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
    weight_decay = PARAMS$weight_decay,
    early_stopping = as.integer(PARAMS$early_stopping) > 0,
    validation_fraction = PARAMS$validation_fraction,
    patience = max(1L, as.integer(PARAMS$early_stopping)),
    seed = SEED,
    dropout = DROPOUT,
    variational = VARIATIONAL,
    prior_scale = PARAMS$prior_scale,
    kl_weight = PARAMS$kl_weight,
    robust = ROBUST,
    groups = if (ROBUST != "group_dro") NULL else SUBGROUPS[FIT_ROWS + 1L],
    dro_step = PARAMS$dro_step,
    adv_epsilon = PARAMS$adv_epsilon,
    adv_steps = as.integer(PARAMS$adv_steps),
    trades_beta = PARAMS$trades_beta,
    mc_passes = PASSES
  )
  fit$mu <- mu; fit$sd <- sd; fit$extended <- TRUE
  fit
}

predict_model <- function(model, X) {
  p <- if (!isTRUE(model$extended)) cs_deep_mlp_predict(model$params, unname(X), ACTIVATION, TASK) else cs_deep_mlp_predict_ext(model, unname(X), TASK)$mean
  if (TASK == "regression") model$mu + model$sd * p else p
}

# Predictive SD (numbers, with prediction passes): sqrt(training residual variance + spread across passes).
predict_sd <- function(model, X) model$sd * sqrt(model$noise_var + cs_deep_mlp_predict_ext(model, unname(X), TASK)$spread)

feature_importance <- function(model, names) NULL

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)  # plain numeric weights + the target scaling
  hist <- file.path(directory, "history.parquet")
  nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
  list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
  fold <- folds[[i]]
  prep <- cs_ml_design_fit(design, rows_of(fold$train))
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
  cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
            predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
  cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")

# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
  if (!is.null(resampled)) {
    warnings <- c(warnings, as.list(resampled$notes))
    notes <- c(notes, list(cs_ml_resample_describe(resampled)))
  }
  if (length(plan$test)) {
    cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
              predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
  }
  importance <- feature_importance(model, names_)
  artifacts[[length(artifacts) + 1L]] <- list(
    key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
  )
  artifacts <- c(artifacts, save_model(model, out))
  cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)

# %% Result
cs_publish(cs_ml_result(
  run,
  title = "Deep neural network (torch MLP)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
  n_features = length(names_),
  n_train = length(plan$train),
  n_test = length(plan$test),
  params = PARAMS,
  features = names_,
  importance = importance,
  artifacts = artifacts,
  warnings = warnings,
  notes = notes
))
Python

Deep neural network (torch MLP): cross-validated ROC AUC 0.822 ± 0.019 over 3 folds; ROC AUC on the locked test set 0.809 (n = 106).

CV ROC AUC
0.8224
SD across folds
0.0188
Test ROC AUC
0.8089

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.83720.47100.80990.7504
211420.80120.54170.71830.6981
311420.82890.47820.78870.7640
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec d6ac628cd57815ee
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import core as deep  # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.deep import mlp_ext as mlpx  # dropout, variational weights, Group DRO, PGD/TRADES (twin: cs_deep_*_ext)
from codesplash.deep import dp as deep_dp  # differentially private training, DP-SGD (twin: cs_deep_dp_*)

# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["glu", "bmi"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "hidden_layers": [6],
    "activation": "relu",
    "epochs": 2,
    "learning_rate": 0.05,
    "batch_size": 128,
    "weight_decay": 0.0001,
    "early_stopping": 0,
    "validation_fraction": 0.1,
    "dropout": 0,
    "mc_passes": 0,
    "variational_weights": False,
    "prior_scale": 1,
    "kl_weight": 1,
    "robust_training": "none",
    "dro_step": 0.01,
    "adv_epsilon": 0.1,
    "adv_steps": 5,
    "trades_beta": 6,
    "loss": "cross_entropy",
    "focal_gamma": 2,
    "focal_alpha": None,
    "dp_epsilon": 8,
    "dp_noise_multiplier": None,
    "dp_max_grad_norm": 1,
    "dp_delta": None,
    "dp_sampling": "poisson",
    "optimizer": "default",
    "lr_schedule": "none",
    "warmup_epochs": 0,
    "grad_clip": 0,
    "ema_decay": 0,
    "swa_start": 0,
    "label_smoothing": 0,
    "mixup_alpha": 0,
    "history_every_step": False,
    "profile": "parity",
    "checkpoint_every": None,
}

df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_dp_epsilon/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "glu": "numeric",
        "bmi": "numeric",
    },
    levels={
    },
    impute="median",
    scale="standard",
    indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-8142/learn.torch_mlp/binary_dp_epsilon/out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
    warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None  # the final model's resampling summary
notes = []


def training_set(X, rows, fold_id, repeat):
    """A fit's design matrix, targets and weights: training rows only, resampled when asked
    (codesplash.ml.resample — the same rows in R, from the shared random stream)."""
    yy, ww = y[rows], sample_weights(rows)
    if RESAMPLE == "none" or TASK == "regression":
        return X, yy, ww
    from codesplash.ml import resample as csres

    X2, y2, w2, info = csres.resample(
        X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
    )
    if fold_id == 0:
        global resampled
        resampled = info
    return X2, y2, w2


# %% Model
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "dp_epsilon": 8,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "label_smoothing": 0,
        "mixup_alpha": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/learn.torch_mlp/binary_dp_epsilon/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set


def training_set(X, rows, fold_id, repeat):
    """Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
    the training set as _ml_learn does."""
    deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
    return _deep_training_set(X, rows, fold_id, repeat)


# A dense network on PyTorch (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — R's torch starts from the same weights and takes the same steps.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
ACTIVATION = PARAMS["activation"]
DROPOUT = float(PARAMS["dropout"])
PASSES = int(PARAMS["mc_passes"])
VARIATIONAL = bool(PARAMS["variational_weights"])
ROBUST = PARAMS["robust_training"]
# Any of the options on: train with codesplash.deep.mlp_ext (otherwise the plain network, unchanged).
EXTENDED = DROPOUT > 0 or PASSES > 0 or VARIATIONAL or ROBUST != "none"
if PASSES > 0 and DROPOUT == 0 and not VARIATIONAL:
    cs.cs_error("CS_E_INVALID_OPTION", option="Prediction passes", allowed="0 unless dropout or variational weights are on", value=PASSES)
if VARIATIONAL and DROPOUT > 0:
    cs.cs_error("CS_E_INVALID_OPTION", option="Dropout", allowed="0 with variational weights (their noise replaces it)", value=DROPOUT)
SUBGROUPS = None
if ROBUST == "group_dro" and SUBGROUPS is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Robust training", allowed="Group DRO only with a Subgroups column", value="group_dro")
if ROBUST == "group_dro" and RESAMPLE != "none" and TASK != "regression":
    cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none with Group DRO", value=RESAMPLE)
# Differential privacy (DP-SGD): with an ε or a noise multiplier set, every fit clips each row's gradient
# and adds noise (codesplash.deep.dp, turned on by the trainer's dp plugin above; the guarantee goes to dp.json).
# Off by default. These options can't be combined with it:
DP = deep_dp.settings(PARAMS)
if DP is not None:
    if VARIATIONAL or ROBUST != "none":
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with variational weights or robust training", value="on")
    if RESAMPLE != "none":
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with resampling (copies of a row would each count)", value="on")


def fit_model(X, y, w):
    if deep_dp.enabled() and w is not None and float(np.ptp(np.asarray(w, dtype=np.float64))) > 0:
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with row or class weights", value="on")
    if TASK == "regression":
        # Standardize the target (training mean and population SD); predictions are mapped back.
        mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
        target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
    elif TASK == "binary":
        mu, sd = 0.0, 1.0
        target, o = np.asarray(y, dtype=np.float64), 1
    else:
        mu, sd = 0.0, 1.0
        target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
    common = dict(
        activation=ACTIVATION,
        epochs=int(PARAMS["epochs"]),
        lr=PARAMS["learning_rate"],
        batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
        weight_decay=PARAMS["weight_decay"],
        early_stopping=int(PARAMS["early_stopping"]) > 0,
        validation_fraction=PARAMS["validation_fraction"],
        patience=max(1, int(PARAMS["early_stopping"])),
        seed=SEED,
    )
    if not EXTENDED:
        fit = deep.fit_mlp(X, target, w, TASK, HIDDEN, o, **common)
        return {"params": fit["params"], "mu": mu, "sd": sd, "history": fit["history"], "best_epoch": fit["best_epoch"]}
    fit = mlpx.fit_mlp_ext(
        X, target, w, TASK, HIDDEN, o, **common,
        dropout=DROPOUT,
        variational=VARIATIONAL,
        prior_scale=PARAMS["prior_scale"],
        kl_weight=PARAMS["kl_weight"],
        robust=ROBUST,
        groups=None if ROBUST != "group_dro" else SUBGROUPS[FIT_ROWS],
        dro_step=PARAMS["dro_step"],
        adv_epsilon=PARAMS["adv_epsilon"],
        adv_steps=int(PARAMS["adv_steps"]),
        trades_beta=PARAMS["trades_beta"],
        mc_passes=PASSES,
    )
    fit.update({"mu": mu, "sd": sd, "extended": True})
    return fit


def predict_model(model, X):
    if not model.get("extended"):
        p = deep.mlp_predict(model["params"], X, ACTIVATION, TASK)
    else:
        p, _ = mlpx.mlp_predict_ext(model, X, TASK)
    if TASK == "regression":
        return model["mu"] + model["sd"] * p
    return p


def predict_sd(model, X):
    """Predictive SD (numbers, with prediction passes): √(training residual variance + spread across passes)."""
    _, spread = mlpx.mlp_predict_ext(model, X, TASK)
    return model["sd"] * np.sqrt(model["noise_var"] + spread)


def feature_importance(model, names):
    return None


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)  # plain numpy weights + the target scaling
    hist = os.path.join(directory, "history.parquet")
    deep.history_frame(model["history"]).to_parquet(hist, index=False)
    return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]


def load_model(directory):
    import joblib

    return joblib.load(os.path.join(directory, "model.joblib"))


# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
    prep = design.fit(df.iloc[fold.train])
    model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
    run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
    progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")

# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
    model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
    if resampled is not None:
        from codesplash.ml import resample as csres

        warnings.extend(resampled["notes"])
        notes.append(csres.describe(resampled))
    if len(plan.test):
        run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
    importance = feature_importance(model, names)
    artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
    artifacts.extend(save_model(model, out))
    run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()

# %% Result
cs.publish(
    run.result(
        title="Deep neural network (torch MLP)",
        engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
        n_features=len(names),
        n_train=len(plan.train),
        n_test=len(plan.test),
        params=PARAMS,
        features=names,
        importance=importance,
        artifacts=artifacts,
        warnings=warnings,
        notes=notes,
    )
)

Under Advanced, set Privacy budget ε (differential privacy), or a Privacy noise multiplier instead, with a Privacy clipping norm. This run reached a CV ROC AUC of 0.822 and a test ROC AUC of 0.809. The run's Training tab shows the ε each fit reached, computed again by the app's accountant. To see what privacy cost, train the same network without it on the same folds.

06

What ε leaves out

Reflect

The guarantee covers the trained weights, and what is computed from them, for that fit's training rows. It doesn't cover choices made by looking at the data without noise: the column scaling, the category list, the rows used for early stopping, or the many runs you compared before picking one. Each extra look at private data is a release ε doesn't count. Write down which choices you made on the data before training.

07

What runs here

Read
08

Common mistakes

Read
09

Check: DP-SGD

Checkpoint

Check yourself

With clipping norm C = 1, a row's gradient is (0, 2). What does DP-SGD add to the batch sum for this row?

Show the answer

Answer: a

Each row is scaled to length at most C. Noise is added once, to the sum, not per row.

Check yourself

You double the epochs and keep the noise multiplier and batch size. What happens to the reported ε?

Show the answer

Answer: a

The accountant sums the cost of every step, so more steps mean a larger ε unless the noise grows.

Check yourself

A clipping norm far below every row's gradient length mostly causes what?

Show the answer

Answer: a

Heavy clipping is a bias that more training doesn't remove; a huge C instead lets noise swamp the signal.

Check yourself

You trained twenty private networks with different settings on the same rows and kept the best. What does the best run's ε describe?

Show the answer

Answer: a

Hyperparameter selection on private data leaks too. Account for it, or tune on public or held-apart data.

10

Recap

Recap
  • DP-SGD clips each row's gradient to C, adds Gaussian noise σC to the sum, and samples batches with probability q.
  • ε grows with steps and sampling rate and falls with noise; set a target ε and CodeSplash finds σ.
  • C trades clipping bias against noise.
  • ε covers that fit's trained weights, not the choices you made by looking at the data.

Concepts in this lesson