Skip to content

Public access to global state for numpy.random #15322

Closed

Description

@mwaskom

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:

  1. 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.
  2. Numpy itself could formally support such a usecase:
    a. Minimally, this could take the form of exposing the global RandomState as part of the public API. Then, downstream packages would need only make a simple change to check_random_state that 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 reproducible RandomState.

Activity

  1. seberg commented on Jan 13, 2020

    @seberg
    Member

    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 a SeedSequence object (sklearn, etc. should then do SeedSequence.spawn())? That removes the need to pass around an actual random number generation objects, while also only having to seed once per program (the original SeedSequence).

    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...

  2. mwaskom commented on Jan 13, 2020

    @mwaskom
    Author

    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_state provides has an appropriate usecase.

  3. seberg commented on Jan 13, 2020

    @seberg
    Member

    In the new API the user is supposed to always create a generator:

    rng = np.random.default_rng()  # may provide a seed.
    
    rng.uniform(size=100)
    

    If you want to call into sklearn, the pattern should be:

    seedsequence = np.random.SeedSequence(1728372974834221)
    
    rng = np.random.default_rng()
    # user code.
    
    call_to_sklearn(..., seed=seedsequence)
    

    Within sklearn what will happen is:

    def call_to_sklearn(..., seed=None):
         if isinstance(seed, np.random.SeedSequence):
             seed = seed.spawn(1)[0]
         rng = np.random.default_gen(seed)
    

    Note a few things here:

    1. user code will 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.
    2. sklearn may even use a completly different RNG without any issues, or create multiple parallel streams.
    3. The starting point is explicitly defined by a single SeedSequence call 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.

  4. seberg commented on Jan 13, 2020

    @seberg
    Member

    If a function does not have any possible input, then check_random_state will 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_state as an API within NumPy.

  5. rkern commented on Jan 13, 2020

    @rkern
    Member
    1. This usage is indeed documented as officially blessed. I'm ambivalent about making it more prominent in the documentation (e.g. documenting _rand explicitly in the numpy.random documentation) 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 as check_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.

  6. seberg commented on Jan 13, 2020

    @seberg
    Member

    Right, I guess if users want that, they should be the ones who do spawn...

  7. rkern commented on Jan 13, 2020

    @rkern
    Member

    Right, I guess if users want that, they should be the ones who do spawn...

    I mean, sklearn ought to spawn if it's splitting up work a la joblib, of course. I just don't think it ought to spawn everywhere that check_random_state() is currently used.

  8. mwaskom commented on Jan 13, 2020

    @mwaskom
    Author

    If a function does not have any possible input, then check_random_state will use the global state anyway, so it is boring?

    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.

  9. mwaskom commented on Jan 13, 2020

    @mwaskom
    Author

    This usage is indeed documented as officially blessed. I'm ambivalent about making it more prominent in the documentation (e.g. documenting _rand explicitly in the numpy.random documentation) as I don't want to encourage its use outside of functions like that.

    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 ...

  10. rkern commented on Jan 13, 2020

    @rkern
    Member

    There's still an open question as to what default_rng(None) ought to do. Currently, it just instantiates a completely new Generator from OS entropy. Right now, the semantics are "give a Generator, 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 the Generator and pass it down to the functions it calls, then there are a limited number of entrypoints where default_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:

    1. Accept a seed argument.
    2. rng = default_rng(seed)
    3. Pass down seed=rng for any functions you call that need random numbers.
  11. mwaskom commented on Jan 13, 2020

    @mwaskom
    Author

    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.seed on 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...

  12. albertcthomas commented on Jan 19, 2020

    @albertcthomas
    Contributor

    I was also uncertain about good practices and the check_random_state function. Thanks for the clarification @rkern and @seberg. Thanks @mwaskom for raising some of my concerns :)

  13. albertcthomas commented on May 10, 2020

    @albertcthomas
    Contributor

    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 the check_random_state function to pass around the already created RNG and I am happy to see that it is possible to now use default_rng for almost the same purpose. About the following recommendations made by @rkern

    I would recommend just using default_rng() in pretty much exactly the same manner as check_random_state()

    and

    I mean, sklearn ought to spawn if it's splitting up work a la joblib, of course

    As I am using check_random_state to 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?

  14. seberg commented on May 10, 2020

    @seberg
    Member

    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, maybe SeedSequence.spawned(Generator|SeedSequence|seed) as a classmethod could work. That seems better than asking the user to put in a SeedSequence?

  15. albertcthomas commented on May 10, 2020

    @albertcthomas
    Contributor

    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.

  16. seberg commented on May 10, 2020

    @seberg
    Member

    @albertcthomas yes, that would be good, do you want to do that?

  17. rkern commented on May 10, 2020

    @rkern
    Member

    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 SeedSequence is stored on the BitGenerator. It's nominally private, but for exploration purposes, you can access it like so:

    >>> rg = np.random.default_rng()
    >>> rg.bit_generator._seed_seq
    SeedSequence(
        entropy=156559746268636088056780713359175458950,
    )
    
  18. albertcthomas commented on May 11, 2020

    @albertcthomas
    Contributor

    Great thanks for the info @rkern. Indeed I should have thought about looking at the bit_generator attribute. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions