Skip to content

BUG: BitGenerator.seed_seq doesn't round-trip through pickle #26234

Closed

Description

@levbishop

Describe the issue:

The seed_seq of a BitGenerator that's been round-tripped through pickle dump/load does not match with the source. This is despite the fact that the BitGenerator.state (and hence the sequence of variates generated) do round-trip, as does a bare SeedSequence.

This also shows up as a deviation of child bitgens from BitGenerator.spawn()

I'm assuming this is an oversight, since the pickle bytestream generated from a BitGenerator just doesn't mention the seed_seq element at all, and I'm assuming it gets generated from the SeedSequence default initializer by fetching fresh entropy from the OS, which presumably adds a few us delay to the unpickle path.

Reproduce the code example:

import numpy as np
import pickle

bg = np.random.PCG64(np.random.SeedSequence(1))
bg2 = pickle.loads(pickle.dumps(bg))

assert bg.seed_seq == bg2.seed_seq

Error message:

No response

Python and NumPy Versions:

1.26.4
3.11.8 (main, Feb 26 2024, 15:43:17) [Clang 14.0.6 ]

Runtime Environment:

[{'numpy_version': '1.26.4',
  'python': '3.11.8 (main, Feb 26 2024, 15:43:17) [Clang 14.0.6 ]',
  'uname': uname_result(system='Darwin', node='LSB-MAC.local', release='22.6.0', version='Darwin Kernel Version 22.6.0: Mon Feb 19 19:48:53 PST 2024; root:xnu-8796.141.3.704.6~1/RELEASE_X86_64', machine='x86_64')},
 {'simd_extensions': {'baseline': ['SSE', 'SSE2', 'SSE3'],
                      'found': ['SSSE3',
                                'SSE41',
                                'POPCNT',
                                'SSE42',
                                'AVX',
                                'F16C',
                                'FMA3',
                                'AVX2'],
                      'not_found': ['AVX512F',
                                    'AVX512CD',
                                    'AVX512_KNL',
                                    'AVX512_SKX',
                                    'AVX512_CLX',
                                    'AVX512_CNL',
                                    'AVX512_ICL']}},
 {'architecture': 'Haswell',
  'filepath': '/usr/local/Caskroom/miniconda/base/envs/rng-seeding/lib/python3.11/site-packages/numpy/.dylibs/libopenblas64_.0.dylib',
  'internal_api': 'openblas',
  'num_threads': 4,
  'prefix': 'libopenblas',
  'threading_layer': 'pthreads',
  'user_api': 'blas',
  'version': '0.3.23.dev'}]

Context for the issue:

The new numpy 1.25 functionality to allow spawning directly from generators (introduced in #23195)rather than needing to pass around a SeedSequence could simplify some multiprocessing/multithreading workflows, but we lose reproducibility due to this bug.

Activity

  1. rkern commented on Apr 9, 2024

    @rkern
    Member

    Yes, that's an oversight.

  2. added this to the 1.26.5 release milestone on Apr 9, 2024
  3. seberg commented on Apr 9, 2024

    @seberg
    Member

    Hmmm, fixing it shouldn't be hard. Glancing at the code, is there a reason why this doesn't use type(self) in __reduce__ (i.e. calling the normal __init__?). The custom __bit_generator_ctor seems unnecessary (@bashtage).

    If we change that part (returning the type as the callable), that would make things a bit nicer I think, because it will be possible to load the fixed pickle on older versions of NumPy also. I am thinking of changing:

        def __reduce__(self):
            from ._pickle import __bit_generator_ctor
            return __bit_generator_ctor, (self.state['bit_generator'],), self.state
    

    to:

        def __reduce__(self):
            return type(self), (self.seed_seq,), self.state
    

    (Pickling is confusing, so I am half suspecting we can just do that and get rid of the __bit_generator_ctor in the mid-term, but also not 100% sure.)

  4. bashtage commented on Apr 9, 2024

    @bashtage
    Contributor

    I might not be recalling correctly, and would need to check, but I think this is the reason. BitGenerator is an abstract base class, Cython then compiles type(self) as a BitGenerator rather than the derived class.

  5. bashtage commented on Apr 9, 2024

    @bashtage
    Contributor

    I think fixing is going to require come versioning work since

    : bg.__reduce__()
    Out[5]:
    (<function numpy.random._pickle.__bit_generator_ctor(bit_generator_name='MT19937')>,
     ('PCG64',),
     {'bit_generator': 'PCG64',
      'state': {'state': 207833532711051698738587646355624148094,
       'inc': 194290289479364712180083596243593368443},
      'has_uint32': 0,
      'uinteger': 0})

    does not capture the information needed to recreate the SeedSequence, and so the fix will need to be able to handle the existing pickle structure as well as the extended pickle.

  6. seberg commented on Apr 9, 2024

    @seberg
    Member

    Cython then compiles type(self) as a BitGenerator rather than the derived class

    Ahh, thanks, that could be. Then maybe that is still a good approach, but if Cython does something weird, we may need tinkering around how to get the correct class exactly (e.g. self.__class__, or type(<object>self) or some funny trick).

  7. seberg commented on Apr 11, 2024

    @seberg
    Member

    If we accept that we pickle as numpy.random._pcg64.PCG... (with the _ module) then type(<object>self) does indeed work and only fails some tests which explicitly check the __reduce__ result. Although I think we may be relying on those to test pickle.
    (I tried patching the __module__ to remove the _pcg64 there, but didn't find a way and it doesn't seem to be super important, to me.)

    I am not quite sure if the __name__ of the class is stable enough. I guess that should be OK, but maybe there needs to be an additional sanity check to see that the state['bit_generator'] name didn't change?

  8. added a commit that references this issue on Apr 11, 2024
    f039e85
  9. bashtage commented on Apr 11, 2024

    @bashtage
    Contributor

    I just pushed a first attempt at fixing this.

    The only concern with significantly refactoring __reduce__ is preserving backward compatability. Preserving it in this case is simple since we only need to add some information for the seed sequence.

  10. added a commit that references this issue on Apr 11, 2024
    3ca64f5
  11. seberg commented on Apr 11, 2024

    @seberg
    Member

    The thing is that if we return the type() then that is also backwards compatible (since BitGenerator(seed_seq) was always valid and in practice identical. We would have to keep the __bit_generator_ctor function to unpickle old files indefinitely, though. (and who knows, it could well be that we go back to needing it for new reasons...)

  12. added 3 commits that reference this issue on Apr 12, 2024
    907bbbd
    4bd32ed
    85108f9
  13. added a commit that references this issue on Apr 16, 2024
    d567754
  14. added a commit that references this issue on Apr 16, 2024
    44ba7ca
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions