History of JAX Privacy#
Overview#
When JAX Privacy was initially released alongside
De et al. (2022) and
Berrada et al. (2023), a primary engineering
goal was making DP-SGD fast and scalable on modern accelerators. At the time,
existing frameworks like
TensorFlow Privacy made per-example
gradient clipping slow and difficult to speed up at scale. By harnessing JAX’s
vectorized transformations (jax.vmap() and jax.pmap()) and gradient
accumulation, the original package enabled large-scale DP-SGD training with
large batch sizes, augmentation multiplicity, and long training horizons. Those
papers demonstrated that standard DP-SGD could achieve strong privacy-utility
tradeoffs on competitive vision benchmarks, putting DP-SGD on the map as a
viable method in practice; indeed, that recipe remains a very strong baseline
for the tasks considered and has proven difficult to beat. To support that
research, the initial repository was designed as an end-to-end experimental
framework for reproducing those experiments on the DeepMind stack of the time
(Haiku, Jaxline, and jax.pmap()).
Since those papers were published, the differentially private machine learning literature has matured significantly. Many newer techniques now achieve strong privacy-utility tradeoffs in lower-compute or single-pass regimes where large batch sizes and data augmentation multiplicity are impractical. These advances span different components of the mechanism (batch selection, noise addition, clipping, optimization, and accounting), and supporting them cleanly called for decoupling those components into standalone primitives rather than an end-to-end training harness.
Around the same time, teams across Google were training differentially private models across a variety of internal codebases. Directly integrating gradient clipping and noise addition inside each training framework (for example, inside the Pax codebase) proved brittle and difficult to maintain across stacks. Even large-scale efforts like VaultGemma 1B, which built on earlier versions of JAX Privacy, reused its gradient clipping module while implementing custom batch selection and accounting to handle padding and truncation in their own training pipeline (see Chua et al., 2024). To provide a shared, framework-agnostic foundation for both modern JAX training stacks and newer DP mechanisms, JAX Privacy evolved from an experimental framework (v0.x) into a modular library (v2.x) of composable primitives.
Scope#
As JAX Privacy transitioned from an end-to-end experiment framework into a general-purpose library, paper-specific models, dataset loaders, and experiment runners were moved out of the core package, and the privacy primitives were organized into six flat pillar modules.
| Dimension | Original Framework (v0.x) | Current Library (v2.x) |
|---|---|---|
| Design Philosophy | Self-contained experimental framework built to reproduce large-scale DP vision papers. | Composable general-purpose library of lower-level DP ingredients (plus a high-level training API) that plug into any JAX loop. |
| Core Primitives | Fast per-example clipping and Gaussian noise in GradientComputer, paired with dataset iterators in the experiment pipeline. | Six flat pillar modules: clipping, noise_addition, batch_selection, accounting, auditing, and optimizers. |
| Model & Modality | Tailored for supervised image classification, augmentation multiplicity, and Haiku (params, network_state) signatures. |
Modality- and model-agnostic; operates on arbitrary PyTrees of JAX arrays with a leading batch axis. |
| Dependencies | 15 packages including Haiku, Jaxline, TensorFlow, TensorFlow Datasets, and scikit-learn. | 7 core requirements centered on JAX, Optax, and DP Accounting. |
| Models & Data Loaders | In Scope: Bundled Haiku vision models (NFNets, WideResNets) and TFDS loaders (ImageNet, CIFAR, CheXpert, MIMIC-CXR). | Out of Scope: Defining model architectures, tokenizers, and dataset loaders is left to the user's stack. |
| Domain Pipelines | In Scope: Bundled end-to-end vision pipelines (EMA averaging, auto-tuning, evaluators). | Out of Scope: Domain-specific pipelines live in downstream libraries (e.g., DPSynth). |
| Binaries & Runners | In Scope: Included Jaxline CLI entrypoints, launch scripts, and paper-specific experiment configs. | Out of Scope: Pure importable library; runnable scripts live in a standalone examples/ directory. |
Key Design Changes#
Click any pillar below to expand its technical details and Before / After comparisons:
Gradient Clipping (
clipping.py): Generalizes DpsgdGradientComputer into ajax.grad-styleclipped_gradprimitive supporting sum-based aggregation, microbatching, and pre-clipping transforms.Sum-Based Aggregation: Originally, gradient clipping averaged per-example gradients over the batch axis for fixed-size batches. To support variable-size batches (such as under Poisson subsampling, where dividing by a random batch size \(|B|\) changes the sensitivity of the aggregate),
clipped_grad()computes a sum over clipped gradients and returns aBoundedSensitivityCallablewhose sensitivity metadata can be inspected directly when calibrating noise (see Variable Batch Sizes and Common Pitfalls).Microbatching (
vmap\(\leftrightarrow\)scan): The original version offered separate vectorized (jax.vmap()) and loop (jax.lax.scan()) clipping modes alongside trainer-level gradient accumulation. In the rewrite,clipped_grad()buildsmicrobatch_sizedirectly into the gradient function, interpolating betweenvmapandscanin a single call.Pre-Clipping Transforms: To support newer adaptive DP optimizers like
scale_then_privatize()that precondition per-example gradients prior to clipping while preserving standard Euclidean \(L_2\) sensitivity bounds,clipped_gradprovides a dedicatedpre_clipping_transformhook that transforms per-example gradients before \(L_2\) clipping.Standard
jax.gradErgonomics: Previously,DpsgdGradientComputerwas designed around Haiku’s stateful trainer signature(params, network_state, rng_per_example, inputs). Today,clipped_grad()adopts standardjax.grad(fun, argnums=0, has_aux=False)conventions so it can be used as a drop-in replacement forjax.grad():# BEFORE (v0.x): 4-argument trainer wrapper and DpsgdGradientComputer from jax_privacy.dp_sgd import grad_clipping, gradients, typing def loss_fn(param, X, y): return 0.5 * jnp.mean((X @ param - y) ** 2) def wrapped_loss_fn(param, unused_network_state, unused_rng, inputs): return loss_fn(param, *inputs), (None, typing.Metrics()) grad_computer = gradients.DpsgdGradientComputer( clipping_norm=1.0, noise_multiplier=0.0, rescale_to_unit_norm=False, per_example_grad_method=grad_clipping.VECTORIZED, global_norm_fn=optax.global_norm, ) _, _, _, grads = grad_computer.loss_and_clipped_gradients( loss_fn=wrapped_loss_fn, params=param, network_state=None, rng_per_example=jax.random.PRNGKey(0), inputs=(X, y), )
# AFTER (v2.x): Drop-in replacement for jax.grad import jax_privacy def loss_fn(param, x, y): return 0.5 * (x @ param - y) ** 2 grad_fn = jax_privacy.clipped_grad(loss_fn, l2_clip_norm=1.0) grads = grad_fn(param, X, y)
Noise Addition (
noise_addition.py): Decouples noise addition from clipping and expresses stateful correlated noise as a standardoptax.GradientTransformation.Decoupled Clipping and Noise: Originally, GradientComputer combined per-example gradient clipping with i.i.d. Gaussian noise addition in a single class, which was natural for standard DP-SGD. In the rewrite,
clippingandnoise_additionare decoupled into independent primitives so i.i.d. Gaussian noise and stateful correlatedmatrix_factorizationmechanisms can be swapped seamlessly.Three-Line Framework Integrations (Case Study: Tunix): External training frameworks like Tunix manage their own training loops, checkpointing, and optimizer state containers, where plugging in an Optax transformation is much simpler than adopting a separate dp_updater.py or manually threading custom privatizer state. Because the current library expresses stateful correlated noise as a standard
optax.GradientTransformation, Tunix chains the privatizer with any base Optax optimizer in three lines of code:privatizer = self._dp_plan.noise_addition_transform noisy_optimizer = optax.chain(privatizer, optimizer) self.optimizer = nnx.Optimizer(self.model, noisy_optimizer, wrt=wrt)
The framework’s optimizer and checkpoint manager automatically initialize, shard, update, and checkpoint the stateful BandMF noise buffer alongside the base optimizer state.
Batch Selection (
batch_selection.py): Introduces first-classBatchSelectionStrategyclasses in the core library, aligning batch construction with privacy accounting assumptions.Following standard practice in the DP-ML literature at the time, the original package paired Poisson or replacement accounting with standard shuffled or fixed-size data loaders rather than providing a dedicated batch selection module. Subsequent research showed that mismatches between accounting assumptions and batch construction can materially affect privacy guarantees (see Common Pitfalls).
In the rewrite,
jax_privacy.batch_selectionprovides first-classBatchSelectionStrategyimplementations (CyclicPoissonSampling,BallsInBinsSampling,BMinSepSampling, and user-level grouping), as well as random-access and streaming partitioning utilities that handle padding and truncation cleanly. See Batch Selection for details.Mechanism Definition & Configuration (
execution_plan.py): Generalizes AlgorithmConfig and DpsgdConfig intoBandMFConfigand a verifiedDPExecutionPlan.While a single noise multiplier was convenient for parameterizing simple DP-SGD sweeps in the original package, it does not by itself characterize a DP-SGD mechanism: the formal guarantee depends jointly on the noise multiplier, the number of training iterations, the sampling probability, and the clipping norm.
In the rewrite,
BandMFConfig(which subsumes standard DP-SGD when using a single band) captures the complete mechanism definition and constructs a verifiedDPExecutionPlanthat couples the privacy accounting event, batch selection strategy, clipped gradient function, and noise addition transformation by construction.Privacy Accounting (
accounting.py): Streamlines the accounting and calibration subpackage into lightweightdp_accounting.DpEventbuilders.The original package maintained a five-file accounting subpackage with experiment-specific accountant classes, caching hierarchies, and custom binary search routines for calibrating noise multipliers, update counts, and batch sizes. As upstream
dp_accountingmatured to provide general-purpose calibration utilities, the rewrite consolidatedjax_privacy.accountinginto a lightweight module ofdp_accounting.DpEventbuilders paired directly with upstreamdp_accounting.calibrate_dp_mechanism.