"""乱数の固定(SPEC_02「学習」.原本: `legacy/source/utils.py` の `fix_rand`).
学習の入口(`training/experiment.py`)からだけ呼ぶ(`.claude/rules/coding-style.md`
「機械学習コードの規則」).
"""
from __future__ import annotations
import os
import random
import numpy as np
import torch
def fix_random_seed(seed: int) -> None:
"""Python・NumPy・PyTorch(CPU・GPU)の乱数の種と cuDNN の決定的な動作を設定する.
原本の `fix_rand` と同じ範囲を同じ順に設定する.`torch.use_deterministic_algorithms` は
有効にしない(原本は `False` を明示している).`PYTHONHASHSEED` は実行中のプロセスには
効かないが,原本どおり設定する(子プロセスに引き継がれる).
Args:
seed: 乱数の種(`train.seed`.0〜2**32−1).
"""
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ["PYTHONHASHSEED"] = str(seed)
torch.use_deterministic_algorithms(False)