Upload random_utils.py with huggingface_hub
Browse files- random_utils.py +24 -13
random_utils.py
CHANGED
@@ -5,35 +5,46 @@ import threading
|
|
5 |
|
6 |
__default_seed__ = 42
|
7 |
_thread_local = threading.local()
|
8 |
-
_thread_local.seed = __default_seed__
|
9 |
-
_thread_local.random = python_random.Random()
|
10 |
-
random = _thread_local.random
|
11 |
|
12 |
|
13 |
-
def
|
14 |
-
|
15 |
-
|
|
|
|
|
|
|
16 |
|
17 |
|
18 |
-
def
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
|
22 |
def get_random_string(length):
|
23 |
letters = string.ascii_letters
|
24 |
-
|
25 |
-
return result_str
|
26 |
|
27 |
|
28 |
@contextlib.contextmanager
|
29 |
def nested_seed(sub_seed=None):
|
30 |
-
|
31 |
old_global_seed = get_seed()
|
32 |
sub_seed = sub_seed or get_random_string(10)
|
33 |
new_global_seed = str(old_global_seed) + "/" + sub_seed
|
34 |
set_seed(new_global_seed)
|
35 |
try:
|
36 |
-
yield
|
37 |
finally:
|
38 |
set_seed(old_global_seed)
|
39 |
-
|
|
|
5 |
|
6 |
__default_seed__ = 42
|
7 |
_thread_local = threading.local()
|
|
|
|
|
|
|
8 |
|
9 |
|
10 |
+
def get_seed():
|
11 |
+
try:
|
12 |
+
return _thread_local.seed
|
13 |
+
except AttributeError:
|
14 |
+
_thread_local.seed = __default_seed__
|
15 |
+
return _thread_local.seed
|
16 |
|
17 |
|
18 |
+
def get_random():
|
19 |
+
try:
|
20 |
+
return _thread_local.random
|
21 |
+
except AttributeError:
|
22 |
+
_thread_local.random = python_random.Random(get_seed())
|
23 |
+
return _thread_local.random
|
24 |
+
|
25 |
+
|
26 |
+
random = get_random()
|
27 |
+
|
28 |
+
|
29 |
+
def set_seed(seed):
|
30 |
+
_thread_local.seed = seed
|
31 |
+
get_random().seed(seed)
|
32 |
|
33 |
|
34 |
def get_random_string(length):
|
35 |
letters = string.ascii_letters
|
36 |
+
return "".join(get_random().choice(letters) for _ in range(length))
|
|
|
37 |
|
38 |
|
39 |
@contextlib.contextmanager
|
40 |
def nested_seed(sub_seed=None):
|
41 |
+
old_state = get_random().getstate()
|
42 |
old_global_seed = get_seed()
|
43 |
sub_seed = sub_seed or get_random_string(10)
|
44 |
new_global_seed = str(old_global_seed) + "/" + sub_seed
|
45 |
set_seed(new_global_seed)
|
46 |
try:
|
47 |
+
yield get_random()
|
48 |
finally:
|
49 |
set_seed(old_global_seed)
|
50 |
+
get_random().setstate(old_state)
|