Control test random determinacy with environment variable
+import os
import atexit
import numpy
@@ -9,6 +10,9 @@ import cupy
# work only in the outermost setUp/tearDown pair.
_nest_count = 0
+_old_numpy_random_state = None
+_old_cupy_random_states = None
+
@atexit.register
def _check_teardown():
@@ -21,7 +25,24 @@ def setup_random():
"""
global _nest_count
+ global _old_numpy_random_state
+ global _old_cupy_random_states
if _nest_count == 0:
+ _old_numpy_random_state = numpy.random.get_state()
+ _old_cupy_random_states = cupy.random.generator._random_states
+ cupy.random.reset_states()
+ # Check that _random_state has been recreated in
+ # cupy.random.reset_states(). Otherwise the contents of
+ # _old_cupy_random_states would be overwritten.
+ assert (cupy.random.generator._random_states is not
+ _old_cupy_random_states)
+
+ nondeterministic = bool(int(os.environ.get(
+ 'CUPY_TEST_RANDOM_NONDETERMINISTIC', '0')))
+ if nondeterministic:
+ numpy.random.seed()
+ cupy.random.seed()
+ else:
numpy.random.seed(100)
cupy.random.seed(101)
_nest_count += 1
@@ -32,8 +53,12 @@ def teardown_random():
"""
global _nest_count
+ global _old_numpy_random_state
+ global _old_cupy_random_states
assert _nest_count > 0
_nest_count -= 1
if _nest_count == 0:
- numpy.random.seed(None)
- cupy.random.reset_states()
+ numpy.random.set_state(_old_numpy_random_state)
+ cupy.random.generator._random_states = _old_cupy_random_states
+ _old_numpy_random_state = None
+ _old_cupy_random_states = None
