Repository navigation
Closed
Description
I would like to be able to write code that can generate reproducible random numbers either by seeding a local RandomState or by falling back to the global state if a seed is not provided. This turns out to be more difficult than expected, despite being a common pattern. A number of libraries have implented the following function:
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, numbers.Integral):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)I believe this code originated in scikit-learn, and has since been propagated into scipy and, if you search on google, several other projects.
There is one problem with this approach, which is that the default behavior is to use np.random.mtrand._rand. That is to say, it depends on access to a private numpy object.
I think there are two implications here:
- Given the widespread public usage of this private object, I'd suggest adding a comment to mtrand indicating that this is (for better or worse) a functionally public API, in that changing it would break a lot of projects.
- Numpy itself could formally support such a usecase:
a. Minimally, this could take the form of exposing the globalRandomStateas part of the public API. Then, downstream packages would need only make a simple change tocheck_random_statethat would eliminate the risk of using a private object.
b. Alternatively, numpy itself could add a similar convenience function that offers one-stop-shopping for a reproducibleRandomState.
Activity
seberg commentedon Jan 13, 2020
I think for better or worse it is fixed, so we could probably document it. I am curious as to this pattern and the new random API...
However,we probably want to discourage the fall-back of the global "seed" and instead encourage passing around at least aSeedSequenceobject (sklearn, etc. should then doSeedSequence.spawn())? That removes the need to pass around an actual random number generation objects, while also only having to seed once per program (the originalSeedSequence).This has a huge advantage over the current use case. If you insert new (unrelated) random number code before the call (e.g. to
sklearn) you will still get the identical results!EDIT: In other words, the new API has no global state, and that is for the better. In the long run it would be nice if we can move users away from it, so that we do not want to add a global state to the new API. Of course that actual move will be very slow...
mwaskom commentedon Jan 13, 2020
I am not aware of the details of the new API but isn't a major disadvantage that if you're calling a function that does not expose its random number generation, there's no way to get reproducible results?
Anyway, the point of this issue isn't to relitigate any decisions you've made about the API, but I do find each of the specific set of options that
check_random_stateprovides has an appropriate usecase.seberg commentedon Jan 13, 2020
In the new API the user is supposed to always create a generator:
If you want to call into sklearn, the pattern should be:
Within sklearn what will happen is:
Note a few things here:
user codewill not effect on the random numbers generated by sklearn, the user can thus change (unrelated) code freely without changing the sklearn result. The other way around, if sklearn changes their algorithm, the user code coming after the sklearn call is unaffected.SeedSequencecall at the top, the only difference is that this needs to be passed around by the user.This removes any brittle global state. I believe it was a specific decision that we should not have global state but instead encourage the use of SeedSequence (and passing it around) when fixed random streams are desired.
seberg commentedon Jan 13, 2020
If a function does not have any possible input, then
check_random_statewill use the global state anyway, so it is boring?It brings up another thing that I think has been mentioned before: Whether or not we should provide something like
check_random_stateas an API within NumPy.rkern commentedon Jan 13, 2020
_randexplicitly in thenumpy.randomdocumentation) as I don't want to encourage its use outside of functions like that. And I don't particularly care to spend much more effort on the use of the old RNG system.@seberg I would recommend just using
default_rng()in pretty much exactly the same manner ascheck_random_state(). I do not really recommend spawning profligately at the head of every RNG-using API. Generally, trying to stick to one RNG per process/thread is still a good idea.seberg commentedon Jan 13, 2020
Right, I guess if users want that, they should be the ones who do spawn...
rkern commentedon Jan 13, 2020
I mean,
sklearnought to spawn if it's splitting up work a lajoblib, of course. I just don't think it ought to spawn everywhere thatcheck_random_state()is currently used.mwaskom commentedon Jan 13, 2020
Sure, it is a slightly different observation prompted by the new (to me) information that lots of things about random number generation are changing in numpy. I'm not going to try to convince you that global state is good, but I'll be sad to see it go.
mwaskom commentedon Jan 13, 2020
I don't think it needs user-facing documentation, I was just suggesting that noting the presence of such a blessing in the code itself might decrease the risk of inadvertently breaking lots of things down the road. Anyway, it was a bit alarming to discover, but it sounds like key people are aware of what's going on so probably not a big deal ...
rkern commentedon Jan 13, 2020
There's still an open question as to what
default_rng(None)ought to do. Currently, it just instantiates a completely newGeneratorfrom OS entropy. Right now, the semantics are "give aGenerator, and I don't care what it's state is". We have some freedom to tighten up our guarantees about that, I think, if we feel like we want to introduce an implicit default global somewhere. We had a discussion about this somewhere in the megathreads, and decided on this option as the one that left us the most freedom to modify if we want to.On the one hand, it is old PRNG wisdom to grab a single PRNG state and draw from it sequentially instead of grabbing a fresh PRNG state every time (parallel streams being an exception to be carefully considered). But all of our PRNGs are of a healthy size and our entropy seeding is good enough that that old lore about PRNGs is less relevant. In addition, if we encourage people to follow good practices and use
default_rng()to get theGeneratorand pass it down to the functions it calls, then there are a limited number of entrypoints wheredefault_rng(None)would actually be called. I do have one concern about making system calls, which might fight for global OS resources in a large parallel processing context, but I think we'll have to see if that is a problem in practice rather than theory.On the other hand, global state really does place a lot of limitation on how the API can be used to get reproducible numbers. Code that uses the
numpy.random.*functions can't be used (reproducibly) in any parallel/concurrent context. The contortions that I've seen in the wild to get locally-fixed-seed numbers are really, uh, "creative" when not broken. The mental overhead required to achieve those effects are rather complicated and context-dependent. On the other hand, there are simple rules for getting reproducible numbers in the new API:seedargument.rng = default_rng(seed)seed=rngfor any functions you call that need random numbers.mwaskom commentedon Jan 13, 2020
In my experience, there are numerous situations where setting a global seed saves effort and reduces noise without causing any problems. Situations that immediately come to mind include bug reports, examples, and short analysis scripts. Searching for
numpy.random.seedon github turns up 4M+ public hits so there are probably other use cases that people have grown accustomed to. But I agree there are situations where it is not a good idea...albertcthomas commentedon Jan 19, 2020
I was also uncertain about good practices and the
check_random_statefunction. Thanks for the clarification @rkern and @seberg. Thanks @mwaskom for raising some of my concerns :)albertcthomas commentedon May 10, 2020
I am really thankful that there are now easy ways to do independent parallel number generations in
numpy. I am also relying a lot on thecheck_random_statefunction to pass around the already created RNG and I am happy to see that it is possible to now usedefault_rngfor almost the same purpose. About the following recommendations made by @rkernand
As I am using
check_random_stateto pass the RNG around I am of course convinced by the first one. However one advantage that I see with @seberg's approach about passing a SeedSequence instead of the existing RNG is that I can easily spawn at any point in my script or in any function that I want to call. For instance if I have a function where I want to do multi-processing, using e.g.joblib, then I would be able to spawn from the passed SeedSequence whereas I don't think I can do that with the passed RNG. Is there something particular that I missed and that you would recommend for such a case?seberg commentedon May 10, 2020
But the last part is something we could fix. Maybe we should expose the initial state/seed sequence. I think we had talked before or considered for later to expose
Generator.spawn(). Alternatively, maybeSeedSequence.spawned(Generator|SeedSequence|seed)as a classmethod could work. That seems better than asking the user to put in a SeedSequence?albertcthomas commentedon May 10, 2020
Thanks for the quick reply @seberg. Something like
Generator.spawn()or other equivalent alternatives would indeed allow to produce independent streams from the passed RNG. It would maybe be better that I open a new issue to discuss about the use case that I mentioned above and the possible ways to deal with it.seberg commentedon May 10, 2020
@albertcthomas yes, that would be good, do you want to do that?
rkern commentedon May 10, 2020
Yes, we definitely talked about it and decided to deliberately not expose it for the first release. Since this is a very new pattern (to our community), we wanted to see some use first, build some trust in the algorithm and implementation, and then lift it up in the API when there was visible demand for it. Thank you, @albertcthomas for doing exactly the kind of exploration and feedback that we needed.
At the moment, the
SeedSequenceis stored on theBitGenerator. It's nominally private, but for exploration purposes, you can access it like so:albertcthomas commentedon May 11, 2020
Great thanks for the info @rkern. Indeed I should have thought about looking at the
bit_generatorattribute. I am not sure that we need a new issue then but let me know if you think it is better to have a trace of this discussion in a new opened issue, in which case I will open one.