-
Notifications
You must be signed in to change notification settings - Fork 487
/
launch.py
executable file
·281 lines (249 loc) · 10.2 KB
/
launch.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/python
from __future__ import print_function
import os
import re
import subprocess
import threading
import sys
import time
from functools import reduce
class PropagatingThread(threading.Thread):
""" propagate exceptions to the parent's thread
refer to https://stackoverflow.com/a/31614591/9601110
"""
def __init__(self, callback=None, idx=-1, **kwargs):
super().__init__(**kwargs)
self.callback = callback
self.idx = idx
def run(self):
self.exc = None
try:
if hasattr(self, '_Thread__target'):
# python 2.x
self.ret = self._Thread__target(
*self._Thread__args, **self._Thread__kwargs)
else:
# python 3.x
self.ret = self._target(*self._args, **self._kwargs)
except BaseException as e:
self.exc = e
if self.callback is not None:
self.callback(self.idx)
def join(self):
super(PropagatingThread, self).join()
if self.exc:
raise self.exc
return self.exc
COMMON_REQUIRED_ENVS = ["DMLC_ROLE", "DMLC_NUM_WORKER", "DMLC_NUM_SERVER",
"DMLC_PS_ROOT_URI", "DMLC_PS_ROOT_PORT"]
WORKER_REQUIRED_ENVS = ["DMLC_WORKER_ID"]
NUMA_PATH = "/sys/devices/system/node"
def allocate_cpu(local_size):
cpu_mt = os.getenv("BYTEPS_MULTITHREADED_CPU", "1").lower() in ["1", "true"]
def get_numa_info():
"""
returns a list of list, each sub list is the cpu ids of a numa node. e.g
[[0,1,2,3], [4,5,6,7]]
"""
ret = []
if os.path.exists(NUMA_PATH):
items = os.listdir(NUMA_PATH)
nodes = list(filter(lambda str: str.startswith("node"), items))
if nodes:
for node in nodes:
items = os.listdir(os.path.join(NUMA_PATH, node))
cpus = [re.findall("cpu\d+", cpu) for cpu in items]
cpus = list(filter(lambda x: x, cpus))
cpu_ids = [int(cpu[0].split('cpu')[1]) for cpu in cpus]
cpu_ids = sorted(cpu_ids)
if cpu_mt:
cpu_ids = cpu_ids[:len(cpu_ids) // 2]
ret.append(cpu_ids)
else:
print("NUMA PATH %s NOT FOUND" % NUMA_PATH)
return ret
def _get_allocation(nodes, quota, cpu_num, cpu_blacklist):
if quota < 1:
raise ValueError("quota should be no less than 1")
ret = []
for node in nodes:
if len(node) < quota:
continue
split_index = []
for i in range(1, quota):
if node[i] != node[i-1] + 1:
split_index.append(i)
quota_bck = quota
last_idx = 0
for idx in split_index:
ret.append(node[last_idx:idx])
quota -= idx - last_idx
last_idx = idx
curr_alloc = node[last_idx:last_idx+quota]
curr_alloc = [item for item in curr_alloc if item not in cpu_blacklist]
ret.append(curr_alloc)
if cpu_mt:
curr_alloc = [x + cpu_num for x in curr_alloc]
curr_alloc = [item for item in curr_alloc if item not in cpu_blacklist]
ret.append(curr_alloc)
for idx in sorted(range(quota_bck), reverse=True):
del node[idx]
return ret
return ret
def _get_quota(nodes, local_size):
# default quota is the number of physical cores for non-root processess
default_quota = cpu_num // local_size
default_quota = int(os.getenv("BYTEPS_NUMA_DEFAULT_QUOTA", default_quota))
while default_quota >= 1 and default_quota * local_size > cpu_num:
default_quota -= 1
# root quota is the number of cpus for root processess
# root does more work, thus using more cpus
root_quota = cpu_num - default_quota * (local_size - 1)
if int(os.getenv("BYTEPS_NUMA_ROOT_QUOTA", 0)):
root_quota = int(os.getenv("BYTEPS_NUMA_ROOT_QUOTA", 0))
node_size = len(nodes[0])
if cpu_mt:
node_size //= 2
while root_quota >= 1 and root_quota > node_size:
root_quota -= 1
return [default_quota] * (local_size - 1) + [root_quota]
nodes = get_numa_info()
if not nodes:
return None
cpu_num = reduce(lambda x, y: (x + len(y)), nodes, 0)
quota_list = _get_quota(nodes, local_size)
cpu_blacklist = os.getenv("BYTEPS_CPU_BLACKLIST", "-1")
cpu_blacklist = [int(item) for item in cpu_blacklist.split(",")]
ret = []
for quota in quota_list:
while quota > 0:
allocation = _get_allocation(nodes, quota, cpu_num, cpu_blacklist)
if allocation:
ret.append(allocation)
break
else:
quota -= 1
return ret
def check_env():
assert "DMLC_ROLE" in os.environ and \
os.environ["DMLC_ROLE"].lower() in ["worker", "server", "scheduler"]
required_envs = COMMON_REQUIRED_ENVS
if os.environ["DMLC_ROLE"] == "worker":
assert "DMLC_NUM_WORKER" in os.environ
num_worker = int(os.environ["DMLC_NUM_WORKER"])
assert num_worker >= 1
if num_worker == 1:
required_envs = []
required_envs += WORKER_REQUIRED_ENVS
for env in required_envs:
if env not in os.environ:
print("The env " + env + " is missing")
os._exit(0)
def worker(local_rank, local_size, command, allocation=None):
my_env = os.environ.copy()
my_env["BYTEPS_LOCAL_RANK"] = str(local_rank)
my_env["BYTEPS_LOCAL_SIZE"] = str(local_size)
if int(os.getenv("BYTEPS_ENABLE_GDB", 0)):
if command.find("python") != 0:
command = "python " + command
command = "gdb -ex 'run' -ex 'bt' -batch --args " + command
if allocation:
print("enable NUMA finetune...")
retval = subprocess.call(
["dpkg", "-s", "numactl"], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if retval == 0:
numa = "numactl --physcpubind "
for cpu_set in allocation:
if len(cpu_set) == 1:
numa += "{},".format(cpu_set[0])
else:
numa += "{}-{},".format(cpu_set[0], cpu_set[-1])
numa = numa.strip(',') + ' '
command = numa + command
print("Command: %s\n" % command)
else:
print("Warning: numactl not found. try `sudo apt-get install numactl`.")
if os.environ.get("BYTEPS_TRACE_ON", "") == "1":
print("\n!!!Enable profiling for WORKER_ID: %s and local_rank: %d!!!" %
(os.environ.get("DMLC_WORKER_ID"), local_rank))
print("BYTEPS_TRACE_START_STEP: %s\tBYTEPS_TRACE_END_STEP: %s\t BYTEPS_TRACE_DIR: %s" % (os.environ.get(
"BYTEPS_TRACE_START_STEP", ""), os.environ.get("BYTEPS_TRACE_END_STEP", ""), os.environ.get("BYTEPS_TRACE_DIR", "")))
print("Command: %s\n" % command)
sys.stdout.flush()
trace_path = os.path.join(os.environ.get(
"BYTEPS_TRACE_DIR", "."), str(local_rank))
if not os.path.exists(trace_path):
os.makedirs(trace_path)
subprocess.check_call(command, env=my_env,
stdout=sys.stdout, stderr=sys.stderr, shell=True)
def parse_num_range(core_list):
# core_list is a colon-seperated string. each section is the physical
# core assignment for the corresponding byteps worker.
# example input: 1,4-5,7-11,12:20-25
# example output: [[[1], [4, 5], [7, 8, 9, 10, 11], [12]], [[20, 21, 22, 23, 24, 25]]]
core_list = core_list.split(':')
ret = []
for item in core_list:
temp = [(lambda sub: range(sub[0], sub[-1] + 1))(list(map(int, elem.split('-')))) for elem in item.split(',')]
ret.append([list(a) for a in temp])
return ret
cv = threading.Condition(lock=threading.Lock())
done_threads = []
def done_callback(idx):
with cv:
done_threads.append(idx)
cv.notify()
def join_threads(threads):
count = 0
num = len(threads)
while count < num:
with cv:
while not done_threads:
cv.wait()
idx = done_threads[-1]
done_threads.pop()
threads[idx].join()
print("BytePS launcher: joined local rank ", idx)
count += 1
def launch_bps():
print("BytePS launching " + os.environ["DMLC_ROLE"])
sys.stdout.flush()
check_env()
os.environ["PYTHONUNBUFFERED"] = "1"
os.environ["UCX_HANDLE_ERRORS"] = os.getenv("UCX_HANDLE_ERRORS", "none")
if os.environ["DMLC_ROLE"] == "worker":
if "NVIDIA_VISIBLE_DEVICES" in os.environ:
local_size = len(os.environ["NVIDIA_VISIBLE_DEVICES"].split(","))
else:
local_size = 1
t = [None] * local_size
bind_to_cores = os.getenv("BYTEPS_NUMA_ON", "1") == "1"
if bind_to_cores:
user_override = os.getenv("BYTEPS_VISIBLE_CPU_CORES", "").strip()
if user_override:
allocations = parse_num_range(user_override)
else:
allocations = allocate_cpu(local_size)
for i in range(local_size):
command = ' '.join(sys.argv[1:])
if bind_to_cores:
t[i] = PropagatingThread(idx=i, callback=done_callback,
target=worker,
args=[i, local_size, command, allocations[i]])
else:
t[i] = PropagatingThread(idx=i, callback=done_callback,
target=worker, args=[i, local_size, command])
t[i].daemon = True
t[i].start()
join_threads(t)
elif os.environ.get("BYTEPS_FORCE_DISTRIBUTED", "") == "1" or \
int(os.environ.get("DMLC_NUM_WORKER", "1")) > 1:
command = "python3 -c 'import byteps.server'"
if int(os.getenv("BYTEPS_ENABLE_GDB", 0)):
command = "gdb -ex 'run' -ex 'bt' -batch --args " + command
print("Command: %s\n" % command, flush=True)
my_env = os.environ.copy()
subprocess.check_call(command, env=my_env,
stdout=sys.stdout, stderr=sys.stderr, shell=True)
if __name__ == "__main__":
launch_bps()