-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Passing a random number generator to simulator/sampler methods should VS maintaing an internal random state #6567
Comments
From Cirq Cynque: look into a way to convert between We agreed that adding an RNG argument to each method call (with a default) is useful, but to maintain backward compatibility for the initializer RNG argument, and to make it easier to share the random distribution across method calls, we should still keep an internal RNG as the default fallback if an RNG is not passed into a method call. |
Hi team, I'm trying to address this in draft PR #6944. Here's the basic approach: if isinstance(seed, np.random.RandomState):
self._prng = np.random.default_rng(seed.get_state()[1][0])
elif isinstance(seed, np.random.Generator):
self._prng = seed
else:
self._prng = np.random.default_rng(seed) Plus, run and sample method would accept an optional RNG parameter while falling back to the internal RNG when none is provided. Please let me know any feedback or concerns about the implementation or backward compat, thanks! |
@justinpan0 it doesn't look like the changes in #6944 are backward compatible. @pavoljuhas I think supporting generators should be part of cirq 2.0, what do you think? |
I think we are dealing with three aspects of incompatibility:
To work around point 3, I extracted the seed from the RandomState object using its if isinstance(random_state, np.random.RandomState):
return np.random.default_rng(random_state.get_state()[1][0]) # type: ignore[index] While this aligns original RandomState with the Generator using the same seed, the sequences will still differ due to reason in point 3. And if we are changing lots of unit test all at once, it might introduce regression risks for point 2. Any insights? |
All Cirq simulators maintain an internal
np.random.RandomState
Cirq/cirq-core/cirq/sim/sparse_simulator.py
Line 130 in e1b03ef
This is fine when running in a single thread, however we are starting to have more places where use multiprocessing/multithreads (e.g. using
multiprocessing.Pool
,concurrent.futures.ThreadPoolExecutor
, or other multiprocessing/multithreading libraries) and in these cases this internal random state negatively affects the simulations in two waysSuggested solution: Start to prefer passing
prng
s to methods/functions over maitaining an internal state. thisprng
should be annp.random.Generator
instead of annp.random.RandomState
so that we get aspawn
method to use when starting threads/processes.related: #6531
The text was updated successfully, but these errors were encountered: