Skip to content

API: RandomState deprecation, default_rng, and SPEC7 #9233

Closed

Description

@larsoner

np.random.RandomState is not a good choice for random number generation going forward:

RandomState is effectively frozen and will only receive updates that are required by changes in the the internals of Numpy. More substantial changes, including algorithmic improvements, are reserved for Generator.

I don't understand all the details, but the TL;DR I've gathered from monitoring some SciPy discussions is that it's not as good as the new default_rng / Generator-based way of making random numbers and it should be replaced in people's code.

In the long term I think we want to switch random_state=0 to use default_rng(random_state) instead of RandomState(random_state) internally. I propose:

  1. Have a mne.set_rng_backend(backend) that can be 'RandomState' or 'Generator', maybe with a use_rng_backend context manager. The context manager is maybe overkill, but I do think it might help people transition code from old to new, and it's only a few lines for us.
  2. If this has not been called by the user yet, if they do random_state=<int> they will see a DeprecationWarning stating that the default is 'RandomState' in 0.23 but will change to 'Generator' in 0.24 (or maybe this is a good case for making it 0.25 to give people more time to change over), and we will call set_rng_backend('RandomState').
  3. In 0.24 (or 0.25) we no longer emit this warning and just use 'Generator'.

I think this is a workable solution for modernizing our random_state params.

Activity

  1. added this to the 0.23 milestone on Apr 1, 2021
  2. drammock commented on Apr 1, 2021

    @drammock
    Member

    The new Generator class docstring says:

    No Compatibility Guarantee

    Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change.

    I think it's worth asking what we use RNGs for.

    • reproducibility of examples / analyses Here, sticking with the frozen RandomState approach is actually better than switching to the new Generator / default_rng approach, right?
    • in our tests This should be unaffected (usually for generating small fake data, the actual data values shouldn't matter)
    • permutations, bootstrapping, random parcellation Here it's not clear to me whether the old/new RNG approaches will make much difference to us, but my instinct is that the results will technically change (same script before/after will have slightly different results) but in practice it shouldn't actually matter.
    • numerics.random_permutation This is a utility designed to emulate MATLAB's randperm for sanity-check comparisions. This will probably break?
    • mxne, ICA Here I don't think I understand well enough how the randomness is used to say what the situation is.
  3. larsoner commented on Apr 1, 2021

    @larsoner
    MemberAuthor

    I think for us we want everything to always be reproducible for a given int random_state (and a given mne.set_rng_backend). I hadn't looked at Generator / default_rng, it is indeed a problem that it does not guarantee stability.

    I wonder if we should just switch EDIT: via deprecation as above to PCG64, which is guaranteed to be stable:

    Compatibility Guarantee

    PCG64 makes a guarantee that a fixed seed and will always produce the same random integer stream.

    But is better than RandomState:

    By default, Generator uses bits provided by PCG64 which has better statistical properties than the legacy MT19937 used in RandomState.

  4. drammock commented on Apr 1, 2021

    @drammock
    Member

    agree on the plan to switch (with deprecation cycle) to explicitly use PCG64 (which happens be be the current default for np.random.default_rng, but that might change).

  5. agramfort commented on Apr 1, 2021

    @agramfort
    SponsorMember
  6. larsoner commented on Apr 1, 2021

    @larsoner
    MemberAuthor

    scipy will deprecate RandomState ?

    There is a long ongoing discussion in the SciPy PR DOC: remove references to RandomState (#13778). The short version so far to me is that RandomState will continue to work at least for some time but should not (and will not) be the preferred way to do things in examples and parameters.

  7. rkern commented on Apr 1, 2021

    @rkern

    Hi everyone! I'm the cause of everyone's problems here. As you work through these issues, I do recommend reading NEP 19 which goes into more detail about why we had the old backwards-compatibility policy and why we moved away from it. The concerns you have brought up here were definitely in our thoughts. I'm happy to answer any questions that the NEP doesn't answer.

    I can't speak definitively as to when/how/if scipy really deprecates RandomState per se, but I have my guess as to where we're going on the aforementioned PR. Some time after we drop support for numpy 1.16, I expect that we will transition the code to use Generator instead of RandomState. I expect that we'll still accept RandomState instances, but we will wrap its core uniform PRNG in Generator and call its methods instead. So if you call scipy.stats.norm.rvs(random_state=RandomState(1234)), you will get the results from Generator.standard_normal()'s improved algorithm rather than the older, slower RandomState.standard_normal(). The core Mersenne Twister PRNG underneath the passed RandomState will still be used, however. Again, we haven't made any decisions, yet, but I think that's where we are going.

  8. larsoner commented on Apr 2, 2021

    @larsoner
    MemberAuthor

    Thanks for the info @rkern . After some reading and discussion I think our plan is to shelve this for now until we bump our minimum numpy requirement to 1.17+ and then switch everything over to using Generator syntax internally (probably still using MT19937 for backward compat), which will likely happen in the next year.

  9. rkern commented on Apr 2, 2021

    @rkern

    Sounds like a good plan.

  10. modified the milestones: 0.23, 0.24 on Apr 19, 2021
  11. modified the milestones: 0.24, 1.0 on Oct 22, 2021
  12. removed this from the 1.0 milestone on Feb 11, 2022
  13. 9 remaining items

  14. sappelhoff commented on Nov 20, 2024

    @sappelhoff
    Member

    Just a note that I have recently learned a bit more about setting RNG seeds thanks to this document: https://blog.scientific-python.org/numpy/numpy-rng/

    And the current state in MNE-Python regarding this is, that we use a lot of RNG seeds that are not recommended. That is, seeds like 0, 1, 42, 97.

    This is not only done in tests, but also in examples+tutorials, where I see this as a problem. We should set a good example in those scripts and use longer and more random seeds (not the common ones like 42, 1337, ...). @larsoner do you think we could/should touch those examples before tackling the brunt of this issue?

    PS: When I recently tried to run my mne ICA with a seed generated by secrets.randbits(128), I got an issue that the seed is too long. So that is also something that is not great and that we should fix.

  15. rkern commented on Nov 20, 2024

    @rkern

    The legacy RandomState is limited to 31-bit integers (the positive half of the signed 32-bit integers) for historical reasons. You can also pass in sequences of uint32s for larger state space, but that's not worth it for examples. If you want to make changes to your examples now, with RandomState, for the promotion of good practices, using unique, non-jokey numbers pulled from secrets.randbits(31) would be sufficient to get the point across.

  16. modified the milestones: 1.9, 1.10 on Dec 9, 2024
  17. modified the milestones: 1.10, 1.11 on Jun 26, 2025
  18. removed this from the 1.11 milestone on Nov 13, 2025
  19. bruAristimunha commented on Aug 24, 2026

    @bruAristimunha
    Contributor

    I am interested if nobody assume

  20. bruAristimunha commented on Aug 24, 2026

    @bruAristimunha
    Contributor

    RNG audit

    Shared RNG handling

    Source Current behavior Migration implication
    check_random_state None returns NumPy's global legacy RandomState; integers construct legacy RandomState; both RandomState and Generator instances are accepted. Central transition point.
    rng_uniform Bridges Generator.integers and RandomState.randint. Remove when internal code uses Generator only.
    random_state docstring Says None uses OS entropy. Incorrect today: the implementation uses global state.
    seed docstring Says None uses OS entropy. Incorrect today for the same reason.

    User-facing RNG parameters

    API group Current argument Source
    Epoch equalization random_state BaseEpochs.equalize_event_counts, equalize_epoch_counts
    Epoch bootstrap random_state bootstrap
    Simulation random_state select_source_in_label, simulate_sparse_stc, simulate_evoked, add_noise, add_eog, add_ecg
    Labels random_state random_parcellation, select_sources
    ICA and inverse methods random_state ICA.__init__, infomax, mixed_norm
    Statistics seed permutation_t_test, permutation_cluster_test, permutation_cluster_1samp_test, spatio_temporal_cluster_1samp_test, spatio_temporal_cluster_test
    Statistics and utility random_state bootstrap_confidence_interval, random_permutation

    Private and internal RNG use

    Area Private implementation RNG behavior Migration note
    Epoch equalization _get_drop_indices choice after check_random_state. Receive or create a Generator.
    Simulated noise _generate_noise Gaussian samples after check_random_state. Receive a normalized Generator.
    Simulated ECG/EOG _add_exg uniform and normal samples. Receive a normalized Generator.
    Label parcellation _cortex_parcellation Random seed vertices via choice. Receive a normalized Generator.
    Infomax ICA infomax Random permutations and uniform samples. Normalize once per fitting run.
    MxNE power_iteration_kron, _compute_mxne_sure Gaussian initialization/perturbation. Migrate internal arguments directly.
    Cluster permutation _permutation_cluster_test, _get_1samp_orders Permutations, choices, and uniform sign flips. Internal variable should consistently be rng.
    Bootstrap CI _ci Forwards state for the bootstrap path. Rename alongside public transition.
    MATLAB compatibility utility random_permutation Uniform values plus argsort. Preserve its explicitly MATLAB-compatible behavior in dedicated tests.
    Circle-plot jitter plot_connectivity_circle internals Direct fixed RandomState(0). Use a fixed local Generator; no public parameter is required.
    Visualization sampling _compute_scalings internals Fresh default_rng() selects display epochs. Decide whether nondeterministic display-only behavior is acceptable.

    Third-party RNG boundaries

    MNE-owned constructor/call Source Finding
    sklearn PCA _auto_low_rank_model PCA(random_state=None) can choose randomized SVD and use sklearn/NumPy global state. This was verified by fitting identical data after different np.random.seed calls.
    sklearn FactorAnalysis _auto_low_rank_model sklearn's default random_state=0 is deterministic, but the seed policy is implicit.
    sklearn LogisticRegression LinearModel.fit solver="liblinear" is created without random_state; sklearn documents this state as controlling liblinear shuffling.
    sklearn MultiTaskLasso _mixed_norm_solver_cd It has random_state=None, but MNE selects selection="cyclic", so random coordinate selection is inactive.
    sklearn FastICA / Picard / Infomax ICA._fit MNE correctly forwards its normalized state.
  21. moved this from Ideas to In Progress in 2026 MNE-Python Maintainers Sprinton Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions