{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XAVN6c8prKOL"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "SassPC7WQAUO"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KwDK47gfLsYf"
      },
      "source": [
        "# Implement Differential Privacy with TensorFlow Privacy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/responsible_ai/privacy/tutorials/classification_privacy\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/privacy/blob/master/tutorials/Classification_Privacy.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/privacy/blob/master/tutorials/Classification_Privacy.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/privacy/g3doc/tutorials/classification_privacy.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "00fQV7e0Unz3"
      },
      "source": [
        "## Overview"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vsCUvXP0W4j2"
      },
      "source": [
        "[Differential privacy](https://en.wikipedia.org/wiki/Differential_privacy) (DP) is a framework for measuring the privacy guarantees provided by an algorithm. Through the lens of differential privacy, you can design machine learning algorithms that responsibly train models on private data. Learning with differential privacy provides measurable guarantees of privacy, helping to mitigate the risk of exposing sensitive training data in machine learning. Intuitively, a model trained with differential privacy should not be affected by any single training example, or small set of training examples, in its data set. This helps mitigate the risk of exposing sensitive training data in ML."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6vd8qUwEW5pP"
      },
      "source": [
        "The basic idea of this approach, called differentially private stochastic gradient descent (DP-SGD), is to modify the gradients\n",
        "used in stochastic gradient descent (SGD), which lies at the core of almost all deep learning algorithms. Models trained with DP-SGD provide provable differential privacy guarantees for their input data. There are two modifications made to the vanilla SGD algorithm:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TUphKzYu01O9"
      },
      "source": [
        "1. First, the sensitivity of each gradient needs to be bounded. In other words, you need to limit how much each individual training point sampled in a minibatch can influence gradient computations and the resulting updates applied to model parameters. This can be done by *clipping* each gradient computed on each training point.\n",
        "2. *Random noise* is sampled and added to the clipped gradients to make it statistically impossible to know whether or not a particular data point was included in the training dataset by comparing the updates SGD applies when it operates with or without this particular data point in the training dataset.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jXU7MZhhW-aL"
      },
      "source": [
        "This tutorial uses [tf.keras](https://www.tensorflow.org/guide/keras) to train a convolutional neural network (CNN) to recognize handwritten digits with the DP-SGD optimizer provided by the TensorFlow Privacy library. TensorFlow Privacy provides code that wraps an existing TensorFlow optimizer to create a variant that implements DP-SGD."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ijJYKVc05DYX"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CKuHPYQCsV-x"
      },
      "source": [
        "Begin by importing the necessary libraries:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ef56gCUqrdVn"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "tf.compat.v1.disable_v2_behavior()\n",
        "\n",
        "import numpy as np\n",
        "\n",
        "tf.get_logger().setLevel('ERROR')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r_fVhfUyeI3d"
      },
      "source": [
        "Install TensorFlow Privacy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "r56BqqyEqA16"
      },
      "outputs": [],
      "source": [
        "!pip install tensorflow-privacy"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RseeuA7veIHU"
      },
      "outputs": [],
      "source": [
        "import tensorflow_privacy\n",
        "\n",
        "from tensorflow_privacy.privacy.analysis import compute_dp_sgd_privacy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mU1p8N7M5Mmn"
      },
      "source": [
        "## Load and pre-process the dataset\n",
        "\n",
        "Load the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset and prepare the data for training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_1ML23FlueTr"
      },
      "outputs": [],
      "source": [
        "train, test = tf.keras.datasets.mnist.load_data()\n",
        "train_data, train_labels = train\n",
        "test_data, test_labels = test\n",
        "\n",
        "train_data = np.array(train_data, dtype=np.float32) / 255\n",
        "test_data = np.array(test_data, dtype=np.float32) / 255\n",
        "\n",
        "train_data = train_data.reshape(train_data.shape[0], 28, 28, 1)\n",
        "test_data = test_data.reshape(test_data.shape[0], 28, 28, 1)\n",
        "\n",
        "train_labels = np.array(train_labels, dtype=np.int32)\n",
        "test_labels = np.array(test_labels, dtype=np.int32)\n",
        "\n",
        "train_labels = tf.keras.utils.to_categorical(train_labels, num_classes=10)\n",
        "test_labels = tf.keras.utils.to_categorical(test_labels, num_classes=10)\n",
        "\n",
        "assert train_data.min() == 0.\n",
        "assert train_data.max() == 1.\n",
        "assert test_data.min() == 0.\n",
        "assert test_data.max() == 1."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xVDcswOCtlr3"
      },
      "source": [
        "## Define the hyperparameters\n",
        "Set learning model hyperparamter values. \n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "E14tL1vUuTRV"
      },
      "outputs": [],
      "source": [
        "epochs = 3\n",
        "batch_size = 250"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qXNp_25y7JP2"
      },
      "source": [
        "DP-SGD has three privacy-specific hyperparameters and one existing hyperamater that you must tune:\n",
        "\n",
        "1. `l2_norm_clip` (float) - The maximum Euclidean (L2) norm of each gradient that is applied to update model parameters. This hyperparameter is used to bound the optimizer's sensitivity to individual training points. \n",
        "2. `noise_multiplier` (float) - The amount of noise sampled and added to gradients during training. Generally, more noise results in better privacy (often, but not necessarily, at the expense of lower utility).\n",
        "3.   `microbatches` (int) - Each batch of data is split in smaller units called microbatches. By default, each microbatch should contain a single training example. This allows us to clip gradients on a per-example basis rather than after they have been averaged across the minibatch. This in turn decreases the (negative) effect of clipping on signal found in the gradient and typically maximizes utility. However, computational overhead can be reduced by increasing the size of microbatches to include more than one training examples. The average gradient across these multiple training examples is then clipped. The total number of examples consumed in a batch, i.e., one step of gradient descent, remains the same. The number of microbatches should evenly divide the batch size. \n",
        "4. `learning_rate` (float) - This hyperparameter already exists in vanilla SGD. The higher the learning rate, the more each update matters. If the updates are noisy (such as when the additive noise is large compared to the clipping threshold), a low learning rate may help the training procedure converge. \n",
        "\n",
        "Use the hyperparameter values below to obtain a reasonably accurate model (95% test accuracy):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pVw_r2Mq7ntd"
      },
      "outputs": [],
      "source": [
        "l2_norm_clip = 1.5\n",
        "noise_multiplier = 1.3\n",
        "num_microbatches = 250\n",
        "learning_rate = 0.25\n",
        "\n",
        "if batch_size % num_microbatches != 0:\n",
        "  raise ValueError('Batch size should be an integer multiple of the number of microbatches')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wXAmHcNOmHc5"
      },
      "source": [
        "## Build the model\n",
        "\n",
        "Define a convolutional neural network as the learning model. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oCOo8aOLmFta"
      },
      "outputs": [],
      "source": [
        "model = tf.keras.Sequential([\n",
        "    tf.keras.layers.Conv2D(16, 8,\n",
        "                           strides=2,\n",
        "                           padding='same',\n",
        "                           activation='relu',\n",
        "                           input_shape=(28, 28, 1)),\n",
        "    tf.keras.layers.MaxPool2D(2, 1),\n",
        "    tf.keras.layers.Conv2D(32, 4,\n",
        "                           strides=2,\n",
        "                           padding='valid',\n",
        "                           activation='relu'),\n",
        "    tf.keras.layers.MaxPool2D(2, 1),\n",
        "    tf.keras.layers.Flatten(),\n",
        "    tf.keras.layers.Dense(32, activation='relu'),\n",
        "    tf.keras.layers.Dense(10)\n",
        "])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FT4lByFg-I_r"
      },
      "source": [
        "Define the optimizer and loss function for the learning model. Compute the loss as a vector of losses per-example rather than as the mean over a minibatch to support gradient manipulation over each training point. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bqBvjCf5-ZXy"
      },
      "outputs": [],
      "source": [
        "optimizer = tensorflow_privacy.DPKerasSGDOptimizer(\n",
        "    l2_norm_clip=l2_norm_clip,\n",
        "    noise_multiplier=noise_multiplier,\n",
        "    num_microbatches=num_microbatches,\n",
        "    learning_rate=learning_rate)\n",
        "\n",
        "loss = tf.keras.losses.CategoricalCrossentropy(\n",
        "    from_logits=True, reduction=tf.losses.Reduction.NONE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LI_3nXzEGmrP"
      },
      "source": [
        "## Train the model\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "z4iV03VqG1Bo"
      },
      "outputs": [],
      "source": [
        "model.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])\n",
        "\n",
        "model.fit(train_data, train_labels,\n",
        "          epochs=epochs,\n",
        "          validation_data=(test_data, test_labels),\n",
        "          batch_size=batch_size)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0kkzQH2LXNjF"
      },
      "source": [
        "## Measure the differential privacy guarantee\n",
        "\n",
        "Perform a privacy analysis to measure the DP guarantee achieved by a training algorithm. Knowing the level of DP achieved enables the objective comparison of two training runs to determine which of the two is more privacy-preserving. At a high level, the privacy analysis measures how much a potential adversary can improve their guess about properties of any individual training point by observing the outcome of the training procedure (e.g., model updates and parameters). \n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TL7_lX5sHCTI"
      },
      "source": [
        "This guarantee is sometimes referred to as the **privacy budget**. A lower privacy budget bounds more tightly an adversary's ability to improve their guess. This ensures a stronger privacy guarantee. Intuitively, this is because it is harder for a single training point to affect the outcome of learning: for instance, the information contained in the training point cannot be memorized by the ML algorithm and the privacy of the individual who contributed this training point to the dataset is preserved.\n",
        "\n",
        "In this tutorial, the privacy analysis is performed in the framework of Rényi Differential Privacy (RDP), which is a relaxation of pure DP based on [this paper](https://arxiv.org/abs/1702.07476) that is particularly well suited for DP-SGD.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wUEk25pgmnm-"
      },
      "source": [
        "Two metrics are used to express the DP guarantee of an ML algorithm:\n",
        "\n",
        "1.   Delta ($\\delta$) - Bounds the probability of the privacy guarantee not holding. A rule of thumb is to set it to be less than the inverse of the size of the training dataset. In this tutorial, it is set to **10^-5** as the MNIST dataset has 60,000 training points.\n",
        "2.   Epsilon ($\\epsilon$) - This is the privacy budget. It measures the strength of the privacy guarantee by bounding how much the probability of a particular model output can vary by including (or excluding) a single training point. A smaller value for $\\epsilon$ implies a better privacy guarantee. However, the $\\epsilon$ value is only an upper bound and a large value could still mean good privacy in practice."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PczVdKsGyRQM"
      },
      "source": [
        "Tensorflow Privacy provides a tool, `compute_dp_sgd_privacy`, to compute the value of $\\epsilon$ given a fixed value of $\\delta$ and the following hyperparameters from the training process:\n",
        "\n",
        "1.   The total number of points in the training data, `n`.\n",
        "2. The `batch_size`.\n",
        "3.   The `noise_multiplier`.\n",
        "4. The number of `epochs` of training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ws8-nVuVDgtJ"
      },
      "outputs": [],
      "source": [
        "compute_dp_sgd_privacy.compute_dp_sgd_privacy(n=train_data.shape[0],\n",
        "                                              batch_size=batch_size,\n",
        "                                              noise_multiplier=noise_multiplier,\n",
        "                                              epochs=epochs,\n",
        "                                              delta=1e-5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c-KyttEWFRDc"
      },
      "source": [
        "The tool reports that for the hyperparameters chosen above, the trained model has an $\\epsilon$ value of 1.18."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SA_9HMGBWFM3"
      },
      "source": [
        "## Summary\n",
        "In this tutorial, you learned about differential privacy (DP) and how you can implement DP principles in existing ML algorithms to provide privacy guarantees for training data. In particular, you learned how to:\n",
        "*   Wrap existing optimizers (e.g., SGD, Adam) into their differentially private counterparts using TensorFlow Privacy\n",
        "*   Tune hyperparameters introduced by differentially private machine learning\n",
        "*   Measure the privacy guarantee provided using analysis tools included in TensorFlow Privacy"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "classification_privacy.ipynb",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
