|
18 | 18 | import numpy as np
|
19 | 19 | import tensorflow as tf
|
20 | 20 | from tensorflow_addons.activations import gelu
|
| 21 | +from tensorflow_addons.activations.gelu import _gelu_py |
21 | 22 | from tensorflow_addons.utils import test_utils
|
22 | 23 |
|
23 | 24 |
|
@@ -51,6 +52,25 @@ def test_theoretical_gradients(self, dtype):
|
51 | 52 | )
|
52 | 53 | self.assertAllCloseAccordingToType(theoretical, numerical, atol=1e-4)
|
53 | 54 |
|
| 55 | + @parameterized.named_parameters(("float32", np.float32), ("float64", np.float64)) |
| 56 | + def test_same_as_py_func(self, dtype): |
| 57 | + np.random.seed(100) |
| 58 | + for _ in range(20): |
| 59 | + self.verify_funcs_are_equivalent(dtype) |
| 60 | + |
| 61 | + def verify_funcs_are_equivalent(self, dtype): |
| 62 | + x_np = np.random.uniform(-10, 10, size=(4, 4)).astype(dtype) |
| 63 | + x = tf.convert_to_tensor(x_np) |
| 64 | + for approximate in [True, False]: |
| 65 | + with tf.GradientTape(persistent=True) as t: |
| 66 | + t.watch(x) |
| 67 | + y_native = gelu(x, approximate=approximate) |
| 68 | + y_py = _gelu_py(x, approximate=approximate) |
| 69 | + self.assertAllCloseAccordingToType(y_native, y_py, atol=1e-4) |
| 70 | + grad_native = t.gradient(y_native, x) |
| 71 | + grad_py = t.gradient(y_py, x) |
| 72 | + self.assertAllCloseAccordingToType(grad_native, grad_py, atol=1e-4) |
| 73 | + |
54 | 74 |
|
55 | 75 | if __name__ == "__main__":
|
56 | 76 | tf.test.main()
|
0 commit comments