Skip to main content

Train PyTorch models with Differential Privacy

Project description



Opacus is a library that enables training PyTorch models with differential privacy. It supports training with minimal code changes required on the client, has little impact on training performance and allows the client to online track the privacy budget expended at any given moment.

Target audience

This code release is aimed at two target audiences:

  1. ML practitioners will find this to be a gentle introduction to training a model with differential privacy as it requires minimal code changes.
  2. Differential Privacy scientists will find this easy to experiment and tinker with, allowing them to focus on what matters.


The latest release of Opacus can be installed via pip:

pip install opacus

:warning: NOTE: This will bring in the latest version of our deps, which are on Cuda 10.2. This will not work if you environment is using an older Cuda version (for example, Google Colab is still on Cuda 10.1).

To install on Colab, run this cell first:

pip install torchcsprng==0.1.3+cu101 -f

Then you can just pip install opacus like before. See more context in this issue.

You can also install directly from the source for the latest features (along with its quirks and potentially ocassional bugs):

git clone
cd opacus
pip install -e .

Getting started

To train your model with differential privacy, all you need to do is to declare a PrivacyEngine and attach it to your optimizer before running, eg:

model = Net()
optimizer = SGD(model.parameters(), lr=0.05)
privacy_engine = PrivacyEngine(
    alphas=[10, 100],
# Now it's business as usual

The MNIST example shows an end-to-end run using opacus. The examples folder contains more such examples.


Checkout the FAQ page for answers to some of the most frequently asked questions about Differential Privacy and Opacus.


See the CONTRIBUTING file for how to help out.

Do also check out our README files inside the repo to learn how the code is organized.



This code is released under Apache 2.0, as found in the LICENSE file.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for opacus, version 0.14.0
Filename, size File type Python version Upload date Hashes
Filename, size opacus-0.14.0-py3-none-any.whl (114.3 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size opacus-0.14.0.tar.gz (80.6 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page