quantumlib / Cirq

A Python framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
Apache License 2.0
4.27k stars 1.01k forks source link

Passing a random number generator to simulator/sampler methods should VS maintaing an internal random state #6567

Open NoureldinYosri opened 6 months ago

NoureldinYosri commented 6 months ago

All Cirq simulators maintain an internal np.random.RandomState https://github.com/quantumlib/Cirq/blob/e1b03ef63af4270d6a185df3db6e43c8232c6a71/cirq-core/cirq/sim/sparse_simulator.py#L130

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 ways


Suggested solution: Start to prefer passing prngs to methods/functions over maitaining an internal state. this prng should be an np.random.Generator instead of an np.random.RandomState so that we get a spawn method to use when starting threads/processes.

related: https://github.com/quantumlib/Cirq/issues/6531

verult commented 6 months ago

From Cirq Cynque: look into a way to convert between np.random.RandomState and np.random.Generator as an alternative approach.

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.