CoolFace
Apppublic

lenML/ChatTTS-Forge

sourceHugging Faceagpl-3.0updated 2y agoView on Hugging Face
301likes
SeedContext.py104 linesDownload Raw Back to utils
1import logging2import random3 4import numpy as np5import torch6 7from modules.utils import rng8 9logger = logging.getLogger(__name__)10 11 12def deterministic(seed=0, cudnn_deterministic=False):13    random.seed(seed)14    np.random.seed(seed)15    torch_rn = rng.convert_np_to_torch(seed)16    torch.manual_seed(torch_rn)17    if torch.cuda.is_available():18        torch.cuda.manual_seed_all(torch_rn)19 20        if cudnn_deterministic:21            torch.backends.cudnn.deterministic = True22            torch.backends.cudnn.benchmark = False23 24 25def is_numeric(obj):26    if isinstance(obj, str):27        try:28            float(obj)29            return True30        except ValueError:31            return False32    elif isinstance(obj, (np.integer, np.signedinteger, np.unsignedinteger)):33        return True34    elif isinstance(obj, np.floating):35        return True36    elif isinstance(obj, (int, float)):37        return True38    else:39        return False40 41 42class SeedContext:43    def __init__(self, seed, cudnn_deterministic=False):44        assert is_numeric(seed), "Seed must be an number."45 46        try:47            self.seed = int(np.clip(int(seed), -1, 2**32 - 1, out=None, dtype=np.int64))48        except Exception as e:49            raise ValueError(f"Seed must be an integer, but: {type(seed)}")50 51        self.seed = seed52        self.cudnn_deterministic = cudnn_deterministic53        self.state = None54 55        if isinstance(seed, str) and seed.isdigit():56            self.seed = int(seed)57 58        if isinstance(self.seed, float):59            self.seed = int(self.seed)60 61        if self.seed == -1:62            self.seed = random.randint(0, 2**32 - 1)63 64    def __enter__(self):65        self.state = (66            torch.get_rng_state(),67            random.getstate(),68            np.random.get_state(),69            torch.backends.cudnn.deterministic,70            torch.backends.cudnn.benchmark,71        )72 73        try:74            deterministic(self.seed, cudnn_deterministic=self.cudnn_deterministic)75        except Exception as e:76            # raise ValueError(77            #     f"Seed must be an integer, but: <{type(self.seed)}> {self.seed}"78            # )79            logger.warning(80                f"Deterministic field, with: <{type(self.seed)}> {self.seed}"81            )82 83    def __exit__(self, exc_type, exc_value, traceback):84        torch.set_rng_state(self.state[0])85        random.setstate(self.state[1])86        np.random.set_state(self.state[2])87        torch.backends.cudnn.deterministic = self.state[3]88        torch.backends.cudnn.benchmark = self.state[4]89 90 91if __name__ == "__main__":92    print(is_numeric("1234"))  # True93    print(is_numeric("12.34"))  # True94    print(is_numeric("-1234"))  # True95    print(is_numeric("abc123"))  # False96    print(is_numeric(np.int32(10)))  # True97    print(is_numeric(np.float64(10.5)))  # True98    print(is_numeric(10))  # True99    print(is_numeric(10.5))  # True100    print(is_numeric(np.int8(10)))  # True101    print(is_numeric(np.uint64(10)))  # True102    print(is_numeric(np.float16(10.5)))  # True103    print(is_numeric([1, 2, 3]))  # False104