File size: 1,927 Bytes
d06fa57 8956871 d06fa57 8956871 d06fa57 8956871 d06fa57 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | # Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.
import os
import random
import builtins
__all__ = [
"softmax",
"seed_all",
"bounded_value",
]
def bounded_value(value, min, max, default, converter=None):
"""Convert ``value`` (when ``converter`` is given) and clamp it to the inclusive range ``[min, max]``.
Args:
value: Raw input value (returns ``default`` if ``value is None``).
min: Lower inclusive bound (or ``None`` for no lower bound).
max: Upper inclusive bound (or ``None`` for no upper bound).
default: Fallback value returned when ``value is None``.
converter: Optional callable (such as ``int`` or ``float``) applied before clamping.
Returns:
Any: Clamped value within ``[min, max]``.
"""
try:
parsed = converter(value) if converter is not None else value
except (TypeError, ValueError):
parsed = default
return builtins.max(min, builtins.min(max, parsed))
def softmax(x):
"""Compute the numerically stable softmax probability distribution over array ``x``.
Args:
x: Input 1D or N-D numeric array.
Returns:
np.ndarray: Softmax probabilities summing to 1.
"""
import numpy as np
x = np.exp(x - x.max())
return x / x.sum()
def seed_all(seed):
"""Seed Python's ``random``, NumPy, and PyTorch (when installed) for reproducible experiments.
Args:
seed: Integer random seed.
"""
os.environ["PL_GLOBAL_SEED"] = str(seed)
random.seed(seed)
try:
import numpy as np
np.random.seed(seed)
except ImportError:
pass
try:
import torch
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
except ImportError:
pass
|