XanaduAI / strawberryfields

Strawberry Fields is a full-stack Python library for designing, simulating, and optimizing continuous variable (CV) quantum optical circuits.
https://strawberryfields.ai
Apache License 2.0
737 stars 187 forks source link

Reproducible pseudorandom numbers on `sf.engine` #693

Open sduquemesa opened 2 years ago

sduquemesa commented 2 years ago

Before posting a feature request

Feature details

Currently, in order to get reproducible results from the execution of a program the global numpy seed needs to be set by the user. For example, this test requires to reset the global seed before re-executing the program to check for equivalence between executions

    np.random.seed(42)
    x = singleloop(sq_r, alpha, phi, theta, shots)
    np.random.seed(42)
    y = singleloop(sq_r, alpha, phi, theta, shots, shift=1)
    assert np.allclose(x, y)

However, this is not the recommended approach as it can lead to hard to track side-effects related to modification of the global state. From the numpy docs

numpy.random.seed This is a convenience, legacy function. The best practice is to not reseed a BitGenerator, rather to recreate a new one. This method is here for legacy reasons.

following numpy's random number generator policy on NEP 19

The preferred best practice for getting reproducible pseudorandom numbers is to instantiate a generator object with a seed and pass it around. The implicit global RandomState behind the numpy.random.* convenience functions can cause problems, especially when threads or other forms of concurrency are involved. Global state is always problematic. We categorically recommend avoiding using the convenience functions when reproducibility is involved.

To avoid this and ensure execution reproducibility protected against modifications of the global random number generator state, the engine should create its own instance of a random generator object and pass it to the backend executing the program. The random generator can be seeded via a new seed keyword argument.

Implementation

No response

How important would you say this feature is?

1: Not important. Would be nice to have.

Additional information

No response