|
| 1 | +# Copyright 2023, The TensorFlow Authors. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from absl.testing import parameterized |
| 16 | +import numpy as np |
| 17 | +import tensorflow as tf |
| 18 | +from tensorflow_privacy.privacy.fast_gradient_clipping import common_test_utils |
| 19 | +from tensorflow_privacy.privacy.fast_gradient_clipping import layer_registry |
| 20 | +from tensorflow_privacy.privacy.fast_gradient_clipping.registry_functions import dense |
| 21 | +from tensorflow_privacy.privacy.fast_gradient_clipping.registry_functions import layer_normalization |
| 22 | + |
| 23 | + |
| 24 | +# ============================================================================== |
| 25 | +# Helper functions. |
| 26 | +# ============================================================================== |
| 27 | +def get_layer_norm_layer_generators(): |
| 28 | + return { |
| 29 | + 'defaults': lambda x: tf.keras.layers.LayerNormalization(axis=x), |
| 30 | + } |
| 31 | + |
| 32 | + |
| 33 | +def get_layer_norm_model_generators(): |
| 34 | + return { |
| 35 | + # TODO(b/274483956): Test more complex models once the we can support |
| 36 | + # `nD` inputs for `tf.keras.layers.Dense`. |
| 37 | + 'func1': common_test_utils.make_one_layer_functional_model, |
| 38 | + } |
| 39 | + |
| 40 | + |
| 41 | +def get_layer_norm_parameter_tuples(): |
| 42 | + """Consists of (input_dims, parameter_axes).""" |
| 43 | + return [ |
| 44 | + # Rank-2 |
| 45 | + ([3], -1), |
| 46 | + ([3], [1]), |
| 47 | + # Rank-3 |
| 48 | + ([3, 4], -1), |
| 49 | + ([3, 4], [1]), |
| 50 | + ([3, 4], [2]), |
| 51 | + ([3, 4], [1, 2]), |
| 52 | + # Rank-4 |
| 53 | + ([3, 4, 5], -1), |
| 54 | + ([3, 4, 5], [1]), |
| 55 | + ([3, 4, 5], [2]), |
| 56 | + ([3, 4, 5], [3]), |
| 57 | + ([3, 4, 5], [1, 2]), |
| 58 | + ([3, 4, 5], [1, 3]), |
| 59 | + ([3, 4, 5], [2, 3]), |
| 60 | + ([3, 4, 5], [1, 2, 3]), |
| 61 | + ] |
| 62 | + |
| 63 | + |
| 64 | +def get_layer_norm_registries(): |
| 65 | + ln_registry = layer_registry.LayerRegistry() |
| 66 | + ln_registry.insert(tf.keras.layers.Dense, dense.dense_layer_computation) |
| 67 | + ln_registry.insert( |
| 68 | + tf.keras.layers.LayerNormalization, |
| 69 | + layer_normalization.layer_normalization_computation, |
| 70 | + ) |
| 71 | + return { |
| 72 | + 'layer_norm_only': ln_registry, |
| 73 | + } |
| 74 | + |
| 75 | + |
| 76 | +# ============================================================================== |
| 77 | +# Main tests. |
| 78 | +# ============================================================================== |
| 79 | +class GradNormTest(tf.test.TestCase, parameterized.TestCase): |
| 80 | + |
| 81 | + def setUp(self): |
| 82 | + super().setUp() |
| 83 | + self.strategy = tf.distribute.get_strategy() |
| 84 | + |
| 85 | + @parameterized.product( |
| 86 | + model_name=list(get_layer_norm_model_generators().keys()), |
| 87 | + layer_name=list(get_layer_norm_layer_generators().keys()), |
| 88 | + parameter_tuple=get_layer_norm_parameter_tuples(), |
| 89 | + layer_registry_name=list(get_layer_norm_registries().keys()), |
| 90 | + is_eager=[True, False], |
| 91 | + ) |
| 92 | + def test_gradient_norms_on_various_models( |
| 93 | + self, |
| 94 | + model_name, |
| 95 | + layer_name, |
| 96 | + parameter_tuple, |
| 97 | + layer_registry_name, |
| 98 | + is_eager, |
| 99 | + ): |
| 100 | + # Parse inputs to generate test data. |
| 101 | + input_dims, parameter_axes = parameter_tuple |
| 102 | + |
| 103 | + def curried_generator(a, b): |
| 104 | + del a, b # Unused by the generator. |
| 105 | + layer_norm_generator = get_layer_norm_layer_generators()[layer_name] |
| 106 | + return layer_norm_generator(parameter_axes) |
| 107 | + |
| 108 | + # Load shared assets to all devices. |
| 109 | + with self.strategy.scope(): |
| 110 | + dummy_output_dim = 1 |
| 111 | + model = common_test_utils.get_model_from_generator( |
| 112 | + model_generator=get_layer_norm_model_generators()[model_name], |
| 113 | + layer_generator=curried_generator, |
| 114 | + input_dims=input_dims, |
| 115 | + output_dims=[dummy_output_dim], |
| 116 | + is_eager=is_eager, |
| 117 | + ) |
| 118 | + |
| 119 | + # Define the main testing ops. These may be later compiled to a Graph op. |
| 120 | + def test_op(x_batch): |
| 121 | + return common_test_utils.get_computed_and_true_norms_from_model( |
| 122 | + model=model, |
| 123 | + per_example_loss_fn=None, |
| 124 | + num_microbatches=None, |
| 125 | + x_batch=[x_batch, x_batch] if model_name == 'tower2' else x_batch, |
| 126 | + weight_batch=None, |
| 127 | + registry=get_layer_norm_registries()[layer_registry_name], |
| 128 | + ) |
| 129 | + |
| 130 | + # TPUs can only run `tf.function`-decorated functions. |
| 131 | + using_tpu = isinstance(self.strategy, tf.distribute.TPUStrategy) |
| 132 | + if using_tpu: |
| 133 | + test_op = tf.function(test_op, jit_compile=True, autograph=False) |
| 134 | + |
| 135 | + # TPUs use lower precision than CPUs, so we relax our criterion (see |
| 136 | + # `dense_test.py` for additional discussions). |
| 137 | + rtol = 1e-2 if using_tpu else 1e-3 |
| 138 | + atol = 1e-1 if using_tpu else 1e-2 |
| 139 | + |
| 140 | + # Each batched input is a reshape of a `tf.range()` call. |
| 141 | + batch_size = 2 |
| 142 | + example_size = np.prod(input_dims) |
| 143 | + example_values = tf.range(batch_size * example_size, dtype=tf.float32) |
| 144 | + x_batch = tf.reshape(example_values, [batch_size] + input_dims) |
| 145 | + batch_size = x_batch.shape[0] |
| 146 | + # Set up the device ops and run the test. |
| 147 | + computed_norms, true_norms = self.strategy.run(test_op, args=(x_batch,)) |
| 148 | + # TPUs return replica contexts, which must be unwrapped. |
| 149 | + if using_tpu: |
| 150 | + common_test_utils.assert_replica_values_are_close(self, computed_norms) |
| 151 | + common_test_utils.assert_replica_values_are_close(self, true_norms) |
| 152 | + computed_norms = computed_norms.values[0] |
| 153 | + true_norms = true_norms.values[0] |
| 154 | + self.assertEqual(tf.shape(computed_norms)[0], batch_size) |
| 155 | + self.assertAllClose(computed_norms, true_norms, rtol=rtol, atol=atol) |
| 156 | + |
| 157 | + |
| 158 | +if __name__ == '__main__': |
| 159 | + tf.test.main() |
0 commit comments