Это даёт воспроизводимость экспериментов без глобальных побочек. С
from contextlib import contextmanager
@contextmanager
def temp_seed(seed: int):
# Сохраняем состояния
py_state = random.getstate()
try:
import numpy as np
np_state = np.random.get_state()
except Exception:
np = None
np_state = None
try:
import torch
torch_state = torch.random.get_rng_state()
torch_cuda_state = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None
except Exception:
torch = None
torch_state = torch_cuda_state = None
# Устанавливаем семена
random.seed(seed)
if np: np.random.seed(seed)
if torch:
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
try:
yield
finally:
# Восстанавливаем состояния
random.setstate(py_state)
if np_state is not None: np.random.set_state(np_state)
if torch_state is not None: torch.random.set_rng_state(torch_state)
if torch_cuda_state is not None and torch.cuda.is_available():
torch.cuda.set_rng_state_all(torch_cuda_state)
# Пример использования
if __name__ == "__main__":
import numpy as np
with temp_seed(123):
print("Блок A:", random.random(), np.random.randint(0, 10))
with temp_seed(123):
print("Блок B:", random.random(), np.random.randint(0, 10)) # те же значения
print("Вне блока:", random.random()) # обычный глобальный поток случайности