Tensorflow enable ops determinism Medium

Deterministic ops will have consistent outputs if the same inputs are ran multiple times on the same hardware.

Detector ID
python/tensorflow-enable-op-determinism@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def tensorflow_enable_op_determinism_noncompliant():
2    import tensorflow as tf
3    # Noncompliant: seed is not set and doesn't use enable_op_determinism().
4    data = tf.ones((1, 1))
5    layer = tf.keras.layers.Input(shape=[1])
6    model = tf.keras.models.Model(inputs=layer, outputs=layer)
7    model.compile(loss="categorical_crossentropy", metrics="AUC")
8    model.fit(x=data, y=data)

Compliant example

1def tensorflow_enable_op_determinism_compliant():
2    import tensorflow as tf
3    # Compliant: sets the seed and enable_op_determinism() is used.
4    tf.keras.utils.set_random_seed(1)
5    tf.config.experimental.enable_op_determinism()
6    data = tf.ones((1, 1))
7    layer = tf.keras.layers.Input(shape=[1])
8    model = tf.keras.models.Model(inputs=layer, outputs=layer)
9    model.compile(loss="categorical_crossentropy", metrics="AUC")
10    model.fit(x=data, y=data)