2019-02-26 10:20:09 -07:00
|
|
|
# Copyright 2019, The TensorFlow Authors.
|
|
|
|
#
|
|
|
|
# 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
|
|
|
|
#
|
|
|
|
# http://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.
|
|
|
|
"""Training a CNN on MNIST in TF Eager mode with DP-SGD optimizer."""
|
|
|
|
|
2019-04-29 15:00:20 -06:00
|
|
|
from absl import app
|
|
|
|
from absl import flags
|
2022-07-08 13:06:47 -06:00
|
|
|
import dp_accounting
|
2019-02-26 10:20:09 -07:00
|
|
|
import numpy as np
|
2022-02-07 17:05:45 -07:00
|
|
|
import tensorflow as tf
|
2019-10-14 16:29:21 -06:00
|
|
|
from tensorflow_privacy.privacy.optimizers.dp_optimizer import DPGradientDescentGaussianOptimizer
|
2019-02-26 10:20:09 -07:00
|
|
|
|
2022-02-07 17:05:45 -07:00
|
|
|
GradientDescentOptimizer = tf.compat.v1.train.GradientDescentOptimizer
|
|
|
|
tf.compat.v1.enable_eager_execution()
|
2019-03-18 23:41:42 -06:00
|
|
|
|
2022-01-28 12:56:55 -07:00
|
|
|
flags.DEFINE_boolean(
|
|
|
|
'dpsgd', True, 'If True, train with DP-SGD. If False, '
|
|
|
|
'train with vanilla SGD.')
|
2019-04-29 15:00:20 -06:00
|
|
|
flags.DEFINE_float('learning_rate', 0.15, 'Learning rate for training')
|
|
|
|
flags.DEFINE_float('noise_multiplier', 1.1,
|
|
|
|
'Ratio of the standard deviation to the clipping norm')
|
|
|
|
flags.DEFINE_float('l2_norm_clip', 1.0, 'Clipping norm')
|
|
|
|
flags.DEFINE_integer('batch_size', 250, 'Batch size')
|
|
|
|
flags.DEFINE_integer('epochs', 60, 'Number of epochs')
|
2022-01-28 12:56:55 -07:00
|
|
|
flags.DEFINE_integer(
|
|
|
|
'microbatches', 250, 'Number of microbatches '
|
|
|
|
'(must evenly divide batch_size)')
|
2019-02-26 10:20:09 -07:00
|
|
|
|
2019-04-29 15:00:20 -06:00
|
|
|
FLAGS = flags.FLAGS
|
2019-02-26 10:20:09 -07:00
|
|
|
|
|
|
|
|
|
|
|
def compute_epsilon(steps):
|
|
|
|
"""Computes epsilon value for given hyperparameters."""
|
|
|
|
if FLAGS.noise_multiplier == 0.0:
|
|
|
|
return float('inf')
|
|
|
|
orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64))
|
2022-07-01 11:33:52 -06:00
|
|
|
accountant = dp_accounting.rdp.RdpAccountant(orders)
|
2022-04-27 17:09:01 -06:00
|
|
|
|
2019-02-26 10:20:09 -07:00
|
|
|
sampling_probability = FLAGS.batch_size / 60000
|
2022-07-01 11:33:52 -06:00
|
|
|
event = dp_accounting.SelfComposedDpEvent(
|
|
|
|
dp_accounting.PoissonSampledDpEvent(
|
2022-04-27 17:09:01 -06:00
|
|
|
sampling_probability,
|
2022-07-01 11:33:52 -06:00
|
|
|
dp_accounting.GaussianDpEvent(FLAGS.noise_multiplier)), steps)
|
2022-04-27 17:09:01 -06:00
|
|
|
|
|
|
|
accountant.compose(event)
|
|
|
|
|
2019-02-26 10:20:09 -07:00
|
|
|
# Delta is set to 1e-5 because MNIST has 60000 training points.
|
2022-04-27 17:09:01 -06:00
|
|
|
return accountant.get_epsilon(target_delta=1e-5)
|
2019-02-26 10:20:09 -07:00
|
|
|
|
|
|
|
|
|
|
|
def main(_):
|
2019-06-04 11:14:09 -06:00
|
|
|
if FLAGS.dpsgd and FLAGS.batch_size % FLAGS.microbatches != 0:
|
|
|
|
raise ValueError('Number of microbatches should divide evenly batch_size')
|
|
|
|
|
2019-02-26 10:20:09 -07:00
|
|
|
# Fetch the mnist data
|
|
|
|
train, test = tf.keras.datasets.mnist.load_data()
|
|
|
|
train_images, train_labels = train
|
|
|
|
test_images, test_labels = test
|
|
|
|
|
|
|
|
# Create a dataset object and batch for the training data
|
|
|
|
dataset = tf.data.Dataset.from_tensor_slices(
|
2022-01-28 12:56:55 -07:00
|
|
|
(tf.cast(train_images[..., tf.newaxis] / 255,
|
|
|
|
tf.float32), tf.cast(train_labels, tf.int64)))
|
2019-02-26 10:20:09 -07:00
|
|
|
dataset = dataset.shuffle(1000).batch(FLAGS.batch_size)
|
|
|
|
|
|
|
|
# Create a dataset object and batch for the test data
|
|
|
|
eval_dataset = tf.data.Dataset.from_tensor_slices(
|
2022-01-28 12:56:55 -07:00
|
|
|
(tf.cast(test_images[..., tf.newaxis] / 255,
|
|
|
|
tf.float32), tf.cast(test_labels, tf.int64)))
|
2019-02-26 10:20:09 -07:00
|
|
|
eval_dataset = eval_dataset.batch(10000)
|
|
|
|
|
|
|
|
# Define the model using tf.keras.layers
|
|
|
|
mnist_model = tf.keras.Sequential([
|
2022-01-28 12:56:55 -07:00
|
|
|
tf.keras.layers.Conv2D(
|
|
|
|
16, 8, strides=2, padding='same', activation='relu'),
|
2019-02-26 10:20:09 -07:00
|
|
|
tf.keras.layers.MaxPool2D(2, 1),
|
|
|
|
tf.keras.layers.Conv2D(32, 4, strides=2, activation='relu'),
|
|
|
|
tf.keras.layers.MaxPool2D(2, 1),
|
|
|
|
tf.keras.layers.Flatten(),
|
|
|
|
tf.keras.layers.Dense(32, activation='relu'),
|
|
|
|
tf.keras.layers.Dense(10)
|
|
|
|
])
|
|
|
|
|
|
|
|
# Instantiate the optimizer
|
|
|
|
if FLAGS.dpsgd:
|
2019-06-04 11:14:09 -06:00
|
|
|
opt = DPGradientDescentGaussianOptimizer(
|
|
|
|
l2_norm_clip=FLAGS.l2_norm_clip,
|
|
|
|
noise_multiplier=FLAGS.noise_multiplier,
|
|
|
|
num_microbatches=FLAGS.microbatches,
|
2019-02-26 10:20:09 -07:00
|
|
|
learning_rate=FLAGS.learning_rate)
|
|
|
|
else:
|
2019-03-18 23:41:42 -06:00
|
|
|
opt = GradientDescentOptimizer(learning_rate=FLAGS.learning_rate)
|
2019-02-26 10:20:09 -07:00
|
|
|
|
|
|
|
# Training loop.
|
|
|
|
steps_per_epoch = 60000 // FLAGS.batch_size
|
|
|
|
for epoch in range(FLAGS.epochs):
|
|
|
|
# Train the model for one epoch.
|
|
|
|
for (_, (images, labels)) in enumerate(dataset.take(-1)):
|
|
|
|
with tf.GradientTape(persistent=True) as gradient_tape:
|
|
|
|
# This dummy call is needed to obtain the var list.
|
|
|
|
logits = mnist_model(images, training=True)
|
|
|
|
var_list = mnist_model.trainable_variables
|
|
|
|
|
|
|
|
# In Eager mode, the optimizer takes a function that returns the loss.
|
|
|
|
def loss_fn():
|
|
|
|
logits = mnist_model(images, training=True) # pylint: disable=undefined-loop-variable,cell-var-from-loop
|
2019-04-29 15:00:20 -06:00
|
|
|
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
|
|
|
|
labels=labels, logits=logits) # pylint: disable=undefined-loop-variable,cell-var-from-loop
|
2019-02-26 10:20:09 -07:00
|
|
|
# If training without privacy, the loss is a scalar not a vector.
|
|
|
|
if not FLAGS.dpsgd:
|
2019-10-30 13:32:39 -06:00
|
|
|
loss = tf.reduce_mean(input_tensor=loss)
|
2019-02-26 10:20:09 -07:00
|
|
|
return loss
|
|
|
|
|
|
|
|
if FLAGS.dpsgd:
|
2022-01-28 12:56:55 -07:00
|
|
|
grads_and_vars = opt.compute_gradients(
|
|
|
|
loss_fn, var_list, gradient_tape=gradient_tape)
|
2019-02-26 10:20:09 -07:00
|
|
|
else:
|
|
|
|
grads_and_vars = opt.compute_gradients(loss_fn, var_list)
|
|
|
|
|
2019-04-30 14:22:35 -06:00
|
|
|
opt.apply_gradients(grads_and_vars)
|
2019-02-26 10:20:09 -07:00
|
|
|
|
|
|
|
# Evaluate the model and print results
|
|
|
|
for (_, (images, labels)) in enumerate(eval_dataset.take(-1)):
|
|
|
|
logits = mnist_model(images, training=False)
|
2019-10-30 13:32:39 -06:00
|
|
|
correct_preds = tf.equal(tf.argmax(input=logits, axis=1), labels)
|
2019-02-26 10:20:09 -07:00
|
|
|
test_accuracy = np.mean(correct_preds.numpy())
|
|
|
|
print('Test accuracy after epoch %d is: %.3f' % (epoch, test_accuracy))
|
|
|
|
|
|
|
|
# Compute the privacy budget expended so far.
|
|
|
|
if FLAGS.dpsgd:
|
2019-06-04 11:14:09 -06:00
|
|
|
eps = compute_epsilon((epoch + 1) * steps_per_epoch)
|
2019-02-26 10:20:09 -07:00
|
|
|
print('For delta=1e-5, the current epsilon is: %.2f' % eps)
|
|
|
|
else:
|
|
|
|
print('Trained with vanilla non-private SGD optimizer')
|
|
|
|
|
2022-01-28 12:56:55 -07:00
|
|
|
|
2019-02-26 10:20:09 -07:00
|
|
|
if __name__ == '__main__':
|
2019-04-29 15:00:20 -06:00
|
|
|
app.run(main)
|