Random
coola.random ¶
Contain functionalities to manage randomness.
coola.random.BaseRandomManager ¶
Bases: ABC
Implement the base class to manage randomness.
Each child class must implement the methods:
- get_rng_state.
- manual_seed.
- set_rng_state.
Example
>>> from coola.random import TorchRandomManager
>>> manager = TorchRandomManager()
>>> manager.manual_seed(42)
coola.random.BaseRandomManager.get_rng_state
abstractmethod
¶
get_rng_state() -> object
Get the current RNG state.
Returns:
| Type | Description |
|---|---|
object
|
The current RNG state. |
Example
>>> from coola.random import TorchRandomManager
>>> manager = TorchRandomManager()
>>> state = manager.get_rng_state()
>>> state
{'torch': tensor([...], dtype=torch.uint8), 'torch.cuda': ...}
coola.random.BaseRandomManager.manual_seed
abstractmethod
¶
manual_seed(seed: int) -> None
Set the seed for generating random numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The desired seed. |
required |
Example
>>> from coola.random import TorchRandomManager
>>> manager = TorchRandomManager()
>>> manager.manual_seed(42)
coola.random.BaseRandomManager.set_rng_state
abstractmethod
¶
set_rng_state(state: object) -> None
Set the RNG state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
object
|
The new RNG state. |
required |
Example
>>> import torch
>>> from coola.random import TorchRandomManager
>>> manager = TorchRandomManager()
>>> state = manager.get_rng_state()
>>> manager.set_rng_state(state)
coola.random.NumpyRandomManager ¶
Bases: BaseRandomManager
Implement a random manager for the library numpy.
The seed must be between 0 and 2**32 - 1, so a modulo
operator to convert an integer to an integer between 0 and
2**32 - 1.
Example
>>> from coola.random import NumpyRandomManager
>>> manager = NumpyRandomManager()
>>> manager.manual_seed(42)
coola.random.RandomManagerRegistry ¶
Bases: BaseRandomManager
Registry that manages random number generator managers.
This registry maintains a mapping from string keys to random manager instances, enabling centralized control of random number generator states across multiple libraries. It provides methods to seed all managers, get and set their states, and check for registered managers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state
|
dict[str, BaseRandomManager] | None
|
Optional initial mapping of string keys to managers. If provided, the state is copied to prevent external mutations. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
_state |
Registry[str, BaseRandomManager]
|
Internal registry mapping keys to random managers |
Example
Basic usage with a random manager:
>>> from coola.random import RandomManagerRegistry, RandomRandomManager
>>> registry = RandomManagerRegistry({"random": RandomRandomManager()})
>>> registry
RandomManagerRegistry(
(state): Registry(
(random): RandomRandomManager()
)
)
>>> registry.manual_seed(42)
coola.random.RandomManagerRegistry.has_manager ¶
has_manager(key: str) -> bool
Check if a random manager is registered for the given key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The string key to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if a manager is registered for this key, False otherwise |
Example
>>> from coola.random import RandomManagerRegistry, RandomRandomManager
>>> registry = RandomManagerRegistry()
>>> registry.register("random", RandomRandomManager())
>>> registry.has_manager("random")
True
>>> registry.has_manager("torch")
False
coola.random.RandomManagerRegistry.register ¶
register(
key: str,
manager: BaseRandomManager,
exist_ok: bool = False,
) -> None
Register a random manager with a given key.
This method associates a manager instance with a specific string key. The manager will be used to control the random number generator state for its corresponding library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The string key to register (e.g., "random", "torch", "numpy") |
required |
manager
|
BaseRandomManager
|
The random manager instance that handles RNG state |
required |
exist_ok
|
bool
|
If False (default), raises an error if the key is already registered. If True, overwrites the existing registration silently. |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the key is already registered and exist_ok is False |
Example
>>> from coola.random import RandomManagerRegistry, RandomRandomManager
>>> registry = RandomManagerRegistry()
>>> registry.register("random", RandomRandomManager())
>>> registry.has_manager("random")
True
coola.random.RandomManagerRegistry.register_many ¶
register_many(
mapping: Mapping[str, BaseRandomManager],
exist_ok: bool = False,
) -> None
Register multiple random managers at once.
This is a convenience method for bulk registration that internally calls register() for each key-manager pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[str, BaseRandomManager]
|
Dictionary mapping string keys to random manager instances |
required |
exist_ok
|
bool
|
If False (default), raises an error if any key is already registered. If True, overwrites existing registrations silently. |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any key is already registered and exist_ok is False |
Example
>>> from coola.random import (
... RandomManagerRegistry,
... RandomRandomManager,
... TorchRandomManager,
... )
>>> registry = RandomManagerRegistry()
>>> registry.register_many(
... {
... "random": RandomRandomManager(),
... "torch": TorchRandomManager(),
... }
... )
>>> registry
RandomManagerRegistry(
(state): Registry(
(random): RandomRandomManager()
(torch): TorchRandomManager()
)
)
coola.random.RandomRandomManager ¶
Bases: BaseRandomManager
Implement a random manager for the python standard library
random.
Example
>>> from coola.random import RandomRandomManager
>>> manager = RandomRandomManager()
>>> manager.manual_seed(42)
coola.random.TorchRandomManager ¶
Bases: BaseRandomManager
Implement a random manager for the library torch.
Example
>>> from coola.random import TorchRandomManager
>>> manager = TorchRandomManager()
>>> manager.manual_seed(42)
coola.random.get_default_registry ¶
get_default_registry() -> RandomManagerRegistry
Get or create the default global registry with common random managers.
Returns a singleton registry instance that is pre-configured with managers for common random number generation libraries including Python's random module, NumPy (if available), and PyTorch (if available).
This function uses a singleton pattern to ensure the same registry instance is returned on subsequent calls, which is efficient and maintains consistency across an application.
Returns:
| Type | Description |
|---|---|
RandomManagerRegistry
|
A RandomManagerRegistry instance with managers registered for: - "random": Python's random module (always available) - "numpy": NumPy random (if NumPy is installed) - "torch": PyTorch random (if PyTorch is installed) |
Notes
The singleton pattern means modifications to the returned registry affect all future calls to this function. If you need an isolated registry, create a new RandomManagerRegistry instance directly.
Example
>>> from coola.random import get_default_registry
>>> registry = get_default_registry()
>>> # Registry is ready to use with available random managers
>>> registry
RandomManagerRegistry(
(state): Registry(
(random): RandomRandomManager()
(numpy): NumpyRandomManager()
(torch): TorchRandomManager()
)
)
coola.random.get_rng_state ¶
get_rng_state() -> dict[str, Any]
Get the current RNG state.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The current RNG state. |
Example
>>> from coola.random import get_rng_state
>>> state = get_rng_state()
>>> state
{'random': ...}
coola.random.manual_seed ¶
manual_seed(seed: int) -> None
Set the seed for generating random numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The desired random seed. |
required |
Example
>>> import torch
>>> from coola.random import manual_seed
>>> manual_seed(42)
>>> torch.randn(3)
tensor([...])
>>> torch.randn(3)
tensor([...])
>>> manual_seed(42)
>>> torch.randn(3)
tensor([...])
coola.random.numpy_seed ¶
numpy_seed(seed: int) -> Generator[None, None, None]
Implement a context manager to manage the NumPy random seed and random number generator (RNG) state.
The context manager sets the specified random seed and restores the original RNG state afterward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The random number generator seed to use while using this context manager. |
required |
Example
>>> import numpy
>>> from coola.random import numpy_seed
>>> with numpy_seed(42):
... print(numpy.random.randn(2, 4))
...
[[...]]
>>> with numpy_seed(42):
... print(numpy.random.randn(2, 4))
...
[[...]]
coola.random.random_seed ¶
random_seed(
seed: int, manager: RandomManagerRegistry | None = None
) -> Generator[None, None, None]
Implement a context manager to manage the random seed and random number generator (RNG) state.
The context manager sets the specified random seed and restores the original RNG state afterward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The random number generator seed to use while using this context manager. |
required |
manager
|
RandomManagerRegistry | None
|
An optional RandomManagerRegistry instance to use. If not provided, the default random manager will be used. |
None
|
Example
>>> import numpy
>>> from coola.random import random_seed
>>> with random_seed(42):
... print(numpy.random.randn(2, 4))
...
[[...]]
>>> with random_seed(42):
... print(numpy.random.randn(2, 4))
...
[[...]]
coola.random.register_managers ¶
register_managers(
mapping: Mapping[str, BaseRandomManager],
exist_ok: bool = False,
) -> None
Register custom managers to the default global registry.
This allows users to add support for custom random number generators without modifying global state directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[str, BaseRandomManager]
|
Dictionary mapping manager names to manager instances |
required |
exist_ok
|
bool
|
If False, raises error if any manager name already registered |
False
|
Example
>>> from coola.random import register_managers, RandomRandomManager
>>> register_managers({"custom": RandomRandomManager()}) # doctest: +SKIP
coola.random.set_rng_state ¶
set_rng_state(state: dict[str, Any]) -> None
Set the RNG state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
The new RNG state. |
required |
Example
>>> import torch
>>> from coola.random import get_rng_state, set_rng_state
>>> st = get_rng_state()
>>> set_rng_state(st)
coola.random.torch_seed ¶
torch_seed(seed: int) -> Generator[None, None, None]
Implement a context manager to manage the PyTorch random seed and random number generator (RNG) state.
The context manager sets the specified random seed and restores the original RNG state afterward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The random number generator seed to use while using this context manager. |
required |
Example
>>> import torch
>>> from coola.random import torch_seed
>>> with torch_seed(42):
... print(torch.randn(2, 4))
...
tensor([[...]])
>>> with torch_seed(42):
... print(torch.randn(2, 4))
...
tensor([[...]])