-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
70 lines (53 loc) · 1.7 KB
/
util.py
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
70
from typing import Tuple, Dict
import time
from collections import defaultdict
KeyT = Tuple[int, str]
class Timer:
state: str
sum: int
n: int
def __init__(self, state: str):
self.state = state
self.sum = 0
self.n = 0
def __enter__(self):
self.start = time.time()
self.n += 1
return self
def __exit__(self, *args):
interval = time.time() - self.start
self.sum += interval
class ManyTimer:
timers: Dict[str, Timer]
def __init__(self):
self.timers = {}
def __call__(self, key: str) -> Timer:
if key not in self.timers:
self.timers[key] = Timer(key)
return self.timers[key]
def set_params_proxy(model, proxy):
"""Set a 'proxy' on the internal ParamServer object for the model and
its children. Experimental.
"""
for node in model.walk():
node._params.proxy = None
for name in node.param_names:
if node.has_param(name):
proxy.set_param(node.id, name, node.get_param(name))
node._params.proxy = proxy
def make_key(model_id: int, name: str) -> Tuple[int, str]:
return (model_id, name)
def divide_params(model, num_workers):
keys_by_node = defaultdict(list)
for node in model.walk():
keys = [make_key(node.id, name) for name in node.param_names]
if keys:
keys_by_node[node.id].extend(keys)
key_groups = list(keys_by_node.values())
worker_keys = []
for _ in range(num_workers):
worker_keys.append([])
for kg in key_groups:
worker_keys[-1].extend(kg)
assert len(worker_keys) == num_workers, (len(worker_keys), num_workers)
return worker_keys