# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

DP-SGD tutorial using Flax Linen on MNIST#

Copyright 2025 DeepMind Technologies Limited.

Welcome to Jax Privacy for Flax Linen! In this tutorial you will learn how to train a simple CNN model in a differentially-private (DP) way using DP-SGD algorithm. We will train our model on the MNIST dataset.

This turorial is based on the official MNIST example for Flax Linen. However, the code is rearranged the same way as in the official MNIST example for Flax NNX.

In the tutorial we highlight the changes we need to make in the official non-DP example to make the model differentially-private.

Install libraries#

If one of the following libraries are not installed in your Python environment, use pip to install the package from PyPI (below, just uncomment the code in the cell if you are working from Google Colab/Jupyter Notebook):

%%capture

!pip install flax
!pip install dp_accounting

!pip install git+https://github.com/google-parfait/jax_privacy.git

Define hyper-parameters#

First we define hyper-parameters for our training. These parameters are important for DP-SGD training. See the comments describing what each parameter means.

Note, that in real applications the same hyper-parameters used for non-DP training might be not optimal for DP training. Therefore fine-tuning of these params might be necessary.

With this setup, expected DP-SGD result is ~92% accuracy on the test dataset and expected non-DP result is ~99%.

# Whether to train model using DP-SGD or not.
# Switch it to False to see the non-DP-SGD results for comparison.
# Expected DP-SGD accuracy: ~92%
# Expected non-DP accuracy: ~99%.
use_dp = True

# Training with DP-SGD might require different values for hyperparameters.
# How many optimization steps to do.
train_steps = 5000 if use_dp else 5000

# How often (number of steps) to evaluate model performance during training.
eval_every = 200

# Batch size for training. In our example, we don't accumulate gradients, so this
# is the batch size for each gradient update.
# In DP-SGD the batch size matters a lot, the bigger batch size the better
# model performance you will get spending the same amount of privacy budget.
batch_size = 256 if use_dp else 128

# Learning rate for the optimizer.
learning_rate = 0.1 if use_dp else 0.1

# Momentum for the optimizer.
momentum = 0.9 if use_dp else 0.9

# DP-SGD parameters.
# Epsilon DP parameter.
epsilon = 1.0

# Delta DP parameter.
delta = 1e-5

# Clipping norm for the gradient vector (i.e. all gradients will have L2 norm at most equal to this value).
# Clipping happens separately for each example in the batch (i.e. before taking sum or mean of gradients).
clipping_norm = 0.1

# Defines how many examples are clipped in parallel per microbatch.
# It does not affect the results, but it allows speed/memory trade-offs.
# Setting microbatch_size=None is fully vectorized, which requires more memory
# but is faster because it uses vmap and each example is clipped in parallel.
# Setting microbatch_size to a positive integer (e.g. 1) is slower but uses less
# memory because it uses lax.scan to process microbatches sequentially.
microbatch_size = None

Load the MNIST dataset#

First, you need to load the MNIST dataset and then prepare the training and testing sets via Tensorflow Datasets (TFDS). You normalize image values, shuffle the data and divide it into batches, and prefetch samples to enhance performance.

No changes related to DP.

import tensorflow as tf  # TensorFlow / `tf.data` operations.
import tensorflow_datasets as tfds  # TFDS to download MNIST.

tf.random.set_seed(0)  # Set the random seed for reproducibility.

train_ds: tf.data.Dataset = tfds.load('mnist', split='train')
test_ds: tf.data.Dataset = tfds.load('mnist', split='test')

# Train size is important for DP-SGD.
train_size = train_ds.cardinality().numpy()
print(f'Train size: {train_size}')
test_size = test_ds.cardinality().numpy()
print(f'Test size: {test_size}')

train_ds = train_ds.map(
    lambda sample: {
        'image': tf.cast(sample['image'], tf.float32) / 255,
        'label': sample['label'],
    }
)  # normalize train set
test_ds = test_ds.map(
    lambda sample: {
        'image': tf.cast(sample['image'], tf.float32) / 255,
        'label': sample['label'],
    }
)  # Normalize the test set.

# Create a shuffled dataset by allocating a buffer size of 1024 to randomly draw elements from.
train_ds = train_ds.repeat().shuffle(1024)
# Group into batches of `batch_size` and skip incomplete batches, prefetch the next sample to improve latency.
train_ds = (
    train_ds.batch(batch_size, drop_remainder=True)
    .take(train_steps)
    .prefetch(1)
)
# Group into batches of `batch_size` and skip incomplete batches, prefetch the next sample to improve latency.
test_ds = test_ds.batch(batch_size, drop_remainder=True).prefetch(1)

Define the CNN model with Flax Linen#

No changes related to DP.

from flax import linen as nn


class CNN(nn.Module):
  """A simple CNN model."""

  @nn.compact
  def __call__(self, x):
    x = nn.Conv(features=32, kernel_size=(3, 3))(x)
    x = nn.relu(x)
    x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
    x = nn.Conv(features=64, kernel_size=(3, 3))(x)
    x = nn.relu(x)
    x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
    x = x.reshape((x.shape[0], -1))  # flatten
    x = nn.Dense(features=256)(x)
    x = nn.relu(x)
    x = nn.Dense(features=10)(x)
    return x

Create model and Flax Linen train state#

The only change is that we create two models: one we will train with DP and the other without to compare the performance.

from flax.training import train_state
from jax import random
import jax.numpy as jnp
import optax


def create_train_state(rng):
  """Creates initial `TrainState`."""
  cnn = CNN()
  params = cnn.init(rng, jnp.ones([1, 28, 28, 1]))['params']
  tx = optax.sgd(learning_rate, momentum)
  return train_state.TrainState.create(apply_fn=cnn.apply, params=params, tx=tx)


train_state = create_train_state(random.key(0))

Calibrate DP-SGD noise#

First we find the standard deviation of Gaussian noise (noise_multiplier) we have to add to achieve the required privacy guarantees (defined by epsilon and delta).

We define the DP-SGD privacy event using accounting.dpsgd_event and calibrate noise_multiplier with dp_accounting.calibrate_dp_mechanism and PLDAccountant.

import dp_accounting
from jax_privacy import accounting

# Calculate noise_multiplier (stddev) given the privacy budget.
# Note: dpsgd_event assumes Poisson subsampling, whereas this tutorial uses
# fixed-size shuffled batches for efficiency. This is a documented common
# pitfall that we make here for demonstration purposes; see:
# https://jax-privacy.readthedocs.io/en/latest/sharp_edges_dp_training_pitfalls.html#accounting-and-batch-selection-mismatch
make_event = lambda sigma: accounting.dpsgd_event(
    sigma, train_steps, sampling_prob=batch_size / train_size
)
noise_multiplier = dp_accounting.calibrate_dp_mechanism(
    dp_accounting.pld.PLDAccountant,
    make_event,
    target_epsilon=epsilon,
    target_delta=delta,
)
print(f'Noise multiplier {noise_multiplier}')

Define loss function#

No changes related to DP.

def loss_fn(params, state, batch):
  logits = state.apply_fn({'params': params}, batch['image'])
  loss = optax.softmax_cross_entropy_with_integer_labels(
      logits=logits, labels=batch['label']
  ).mean()
  return loss, logits

Define evaluation function#

No changes related to DP.

import jax


@jax.jit
def eval_step(state, batch):
  loss, logits = loss_fn(state.params, state, batch)
  accuracy = jnp.mean(jnp.argmax(logits, -1) == batch['label'])
  return loss, accuracy

Define non-DP train step#

We will use it to train non-DP model for comparison.

@jax.jit
def non_dp_train_step(state, batch):
  """Train for a single step."""

  value_and_grad_fn = jax.value_and_grad(loss_fn, has_aux=True)
  (loss, logits), grads = value_and_grad_fn(state.params, state, batch)
  new_state = state.apply_gradients(grads=grads)
  accuracy = jnp.mean(jnp.argmax(logits, -1) == batch['label'])
  return new_state, {'loss': loss, 'accuracy': accuracy}

Define DP-SGD train step#

This is the main function where DP-SGD magic happens.

First we wrap our standard loss_fn defined above with jax_privacy.clipped_grad to create clipped_grad_fn (the differentially-private counterpart to jax.value_and_grad):

  • l2_clip_norm=clipping_norm clips each per-example gradient to have L2 norm at most clipping_norm.

  • rescale_to_unit_norm=True rescales each clipped gradient by 1.0 / clipping_norm (so its L2 norm is at most 1.0), which decouples the clipping norm from the learning rate.

  • normalize_by=batch_size divides the sum of clipped per-example gradients by batch_size to return the average clipped gradient.

  • batch_argnums=2 tells clipped_grad that the third argument (batch, at index 2) contains the batch dimension, while argnums=0 (the default) differentiates with respect to params.

  • has_aux=True and return_values=True instruct clipped_grad_fn to also return per-example auxiliary outputs (logits in aux_outputs.aux and per-example losses in aux_outputs.values), stacked over the batch dimension so we can calculate the mean loss and accuracy later.

Secondly, inside dp_sgd_train_step, we calculate clipped gradients by calling clipped_grad_fn(state.params, state, batch). It splits batch into per-example slices (with batch size 1), calls loss_fn for each example, clips the resulting gradients, and averages them across the batch.

Now we have clipped the gradients and are ready to make an optimizer step. However, to make it differentially-private we also need to add Gaussian noise to the gradients. We create privatizer using noise_addition.gaussian_privatizer with standard deviation noise_multiplier * clipped_grad_fn.sensitivity(), where clipped_grad_fn.sensitivity() automatically accounts for l2_clip_norm, rescale_to_unit_norm, and normalize_by. Inside dp_sgd_train_step, we call privatizer.update(grads, noise_state), which returns the gradients with added noise and the updated new_noise_state (including the split PRNGKey) to save and pass in the next step.

Then the rest of the code is the same as in the usual non-DP training: we calculate updated model weights by applying the noisy gradients with the help of the optimizer and calculate the accuracy of predictions for monitoring purposes.

import jax_privacy
from jax_privacy import noise_addition

# Create clipped gradient function that clips per-example grads and averages.
clipped_grad_fn = jax_privacy.clipped_grad(
    loss_fn,
    has_aux=True,
    l2_clip_norm=clipping_norm,
    # Simplifies learning-rate tuning, see https://arxiv.org/abs/2204.13650.
    rescale_to_unit_norm=True,
    normalize_by=batch_size,
    batch_argnums=2,
    return_values=True,
    microbatch_size=microbatch_size,
)
sensitivity = clipped_grad_fn.sensitivity()
privatizer = noise_addition.gaussian_privatizer(
    stddev=noise_multiplier * sensitivity,
    prng_key=random.key(42),
)


@jax.jit
def dp_sgd_train_step(state, batch, noise_state):
  """Train for a single step."""

  grads, aux_outputs = clipped_grad_fn(state.params, state, batch)
  noisy_grads, new_noise_state = privatizer.update(grads, noise_state)
  new_state = state.apply_gradients(grads=noisy_grads)
  loss = jnp.mean(aux_outputs.values)
  logits = aux_outputs.aux
  accuracy = jnp.mean(jnp.argmax(logits, -1) == batch['label'])
  return new_state, new_noise_state, {'loss': loss, 'accuracy': accuracy}

Train#

The only difference from usual non-DP training is that we initialize and keep updating the noise_state (which tracks the PRNGKey for the noise across steps).

Worth noting that if you train with DP-SGD you can’t call train of the same model for the second time because the noise_multiplier was calculated for exactly that number of train steps.

import time
import numpy as np

# Train loop
metrics_history = {
    'train_loss': [],
    'train_accuracy': [],
    'test_loss': [],
    'test_accuracy': [],
}

checkpoint_start = time.time()
accumulated_losses = []
accumulated_accuracies = []
noise_state = privatizer.init(train_state.params)
for step, batch in enumerate(train_ds.as_numpy_iterator()):
  if use_dp:
    train_state, noise_state, step_metrics = dp_sgd_train_step(
        train_state, batch, noise_state
    )
  else:
    train_state, step_metrics = non_dp_train_step(train_state, batch)
  accumulated_losses.append(step_metrics['loss'])
  accumulated_accuracies.append(step_metrics['accuracy'])

  if step > 0 and (step % eval_every == 0 or step == train_steps - 1):
    checkpoint_time = time.time() - checkpoint_start
    # Log the training metrics.
    metrics_history[f'train_loss'].append(np.mean(accumulated_losses))
    metrics_history[f'train_accuracy'].append(np.mean(accumulated_accuracies))
    accumulated_losses = []
    accumulated_accuracies = []

    # Compute the metrics on the test set.
    for test_batch in test_ds.as_numpy_iterator():
      loss, accuracy = eval_step(train_state, test_batch)
      accumulated_losses.append(loss)
      accumulated_accuracies.append(accuracy)

    # Log the test metrics.
    metrics_history[f'test_loss'].append(np.mean(accumulated_losses))
    metrics_history[f'test_accuracy'].append(np.mean(accumulated_accuracies))
    accumulated_losses = []
    accumulated_accuracies = []

    print(
        f' [elapsed time]: {checkpoint_time:.2f}\n',
        f'[train] step: {step}, '
        f'loss: {metrics_history["train_loss"][-1]}, '
        f'accuracy: {metrics_history["train_accuracy"][-1] * 100}',
    )
    print(
        f' [test] step: {step}, '
        f'loss: {metrics_history["test_loss"][-1]}, '
        f'accuracy: {metrics_history["test_accuracy"][-1] * 100}'
    )
    checkpoint_start = time.time()