Skip to content

Random utils

get_seed_from_rng(rng, dtype=np.int64)

Generates a deterministic random seed from an existing random generator.

This is useful in particular because setting the torch seed doesn't want to accept a tuple of numbers, we we often do in initializing a numpy random generator with epoch, index, and global seeds.

Used to seed a torch random generator from a numpy random generator.

Source code in bionemo/core/utils/random_utils.py
52
53
54
55
56
57
58
59
60
def get_seed_from_rng(rng: np.random.Generator, dtype: Type[np.signedinteger] = np.int64) -> int:
    """Generates a deterministic random seed from an existing random generator.

    This is useful in particular because setting the torch seed doesn't want to accept a tuple of numbers, we we often
    do in initializing a numpy random generator with epoch, index, and global seeds.

    Used to seed a torch random generator from a numpy random generator.
    """
    return int(rng.integers(np.iinfo(dtype).max))

random_numpy_context(seed=42)

Context manager for setting numpy random state.

The state is saved on entry and restored on exit to what it was. This way you can run code that needs random state in a with context using this function, and get back to whatever state was there before. This is useful for testing where you don't want the random state from one test to impact other tests.

Example

import numpy as np from bionemo.core.utils.random_utils import random_numpy_context ori_state = np.random.get_state() with random_numpy_context(45): np.random.randint(5) # this will change the state new_state = np.random.get_state() assert ori_state == new_state

Source code in bionemo/core/utils/random_utils.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@contextmanager
def random_numpy_context(seed: int = 42) -> Iterator[None]:
    """Context manager for setting numpy random state.

    The state is saved on entry and restored on exit to what it was. This way you can run code that needs random state
    in a `with` context using this function, and get back to whatever state was there before. This is useful for testing
    where you don't want the random state from one test to impact other tests.

    Example:
        >>> import numpy as np
        >>> from bionemo.core.utils.random_utils import random_numpy_context
        >>> ori_state = np.random.get_state()
        >>> with random_numpy_context(45):
            np.random.randint(5) # this will change the state
        >>> new_state = np.random.get_state()
        >>> assert ori_state == new_state
    """
    state = np.random.get_state()  # just fail if this fails
    try:
        np.random.seed(seed)
        yield
    finally:
        np.random.set_state(state)