-
Notifications
You must be signed in to change notification settings - Fork 197
/
comms.py
644 lines (507 loc) · 18.3 KB
/
comms.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import time
import uuid
import warnings
from collections import OrderedDict
from dask.distributed import default_client, get_worker
from pylibraft.common.handle import Handle
from .comms_utils import (
inject_comms_on_handle,
inject_comms_on_handle_coll_only,
)
from .nccl import nccl
from .ucx import UCX
from .utils import parse_host_port
logger = logging.getLogger(__name__)
class Comms:
"""
Initializes and manages underlying NCCL and UCX comms handles across
the workers of a Dask cluster. It is expected that `init()` will be
called explicitly. It is recommended to also call `destroy()` when
the comms are no longer needed so the underlying resources can be
cleaned up. This class is not meant to be thread-safe.
Examples
--------
.. code-block:: python
# The following code block assumes we have wrapped a C++
# function in a Python function called `run_algorithm`,
# which takes a `raft::handle_t` as a single argument.
# Once the `Comms` instance is successfully initialized,
# the underlying `raft::handle_t` will contain an instance
# of `raft::comms::comms_t`
from dask_cuda import LocalCUDACluster
from dask.distributed import Client
from raft.dask.common import Comms, local_handle
cluster = LocalCUDACluster()
client = Client(cluster)
def _use_comms(sessionId):
return run_algorithm(local_handle(sessionId))
comms = Comms(client=client)
comms.init()
futures = [client.submit(_use_comms,
comms.sessionId,
workers=[w],
pure=False) # Don't memoize
for w in cb.worker_addresses]
wait(dfs, timeout=5)
comms.destroy()
client.close()
cluster.close()
"""
valid_nccl_placements = ("client", "worker", "scheduler")
def __init__(
self,
comms_p2p=False,
client=None,
verbose=False,
streams_per_handle=0,
nccl_root_location="scheduler",
):
"""
Construct a new CommsContext instance
Parameters
----------
comms_p2p : bool
Initialize UCX endpoints?
client : dask.distributed.Client [optional]
Dask client to use
verbose : bool
Print verbose logging
nccl_root_location : string
Indicates where the NCCL's root node should be located.
['client', 'worker', 'scheduler' (default)]
"""
self.client = client if client is not None else default_client()
self.comms_p2p = comms_p2p
self.nccl_root_location = nccl_root_location.lower()
if self.nccl_root_location not in Comms.valid_nccl_placements:
raise ValueError(
f"nccl_root_location must be one of: "
f"{Comms.valid_nccl_placements}"
)
self.streams_per_handle = streams_per_handle
self.sessionId = uuid.uuid4().bytes
self.nccl_initialized = False
self.ucx_initialized = False
self.verbose = verbose
if verbose:
print("Initializing comms!")
def __del__(self):
if self.nccl_initialized or self.ucx_initialized:
self.destroy()
def create_nccl_uniqueid(self):
if self.nccl_root_location == "client":
self.uniqueId = nccl.get_unique_id()
elif self.nccl_root_location == "worker":
self.uniqueId = self.client.run(
_func_set_worker_as_nccl_root,
sessionId=self.sessionId,
verbose=self.verbose,
workers=[self.worker_addresses[0]],
wait=True,
)[self.worker_addresses[0]]
else:
self.uniqueId = self.client.run_on_scheduler(
_func_set_scheduler_as_nccl_root,
sessionId=self.sessionId,
verbose=self.verbose,
)
def worker_info(self, workers):
"""
Builds a dictionary of { (worker_address, worker_port) :
(worker_rank, worker_port ) }
"""
ranks = _func_worker_ranks(workers)
ports = (
_func_ucp_ports(self.client, workers) if self.comms_p2p else None
)
output = {}
for k in ranks.keys():
output[k] = {"rank": ranks[k]}
if self.comms_p2p:
output[k]["port"] = ports[k]
return output
def init(self, workers=None):
"""
Initializes the underlying comms. NCCL is required but
UCX is only initialized if `comms_p2p == True`
Parameters
----------
workers : Sequence
Unique collection of workers for initializing comms.
"""
self.worker_addresses = list(
OrderedDict.fromkeys(
self.client.scheduler_info()["workers"].keys()
if workers is None
else workers
)
)
if self.nccl_initialized or self.ucx_initialized:
warnings.warn("Comms have already been initialized.")
return
worker_info = self.worker_info(self.worker_addresses)
worker_info = {w: worker_info[w] for w in self.worker_addresses}
self.create_nccl_uniqueid()
self.client.run(
_func_init_all,
self.sessionId,
self.uniqueId,
self.comms_p2p,
worker_info,
self.verbose,
self.streams_per_handle,
workers=self.worker_addresses,
wait=True,
)
self.nccl_initialized = True
if self.comms_p2p:
self.ucx_initialized = True
if self.verbose:
print("Initialization complete.")
def destroy(self):
"""
Shuts down initialized comms and cleans up resources. This will
be called automatically by the Comms destructor, but may be called
earlier to save resources.
"""
self.client.run(
_func_destroy_all,
self.sessionId,
self.comms_p2p,
self.verbose,
wait=True,
workers=self.worker_addresses,
)
if self.nccl_root_location == "scheduler":
self.client.run_on_scheduler(
_func_destroy_scheduler_session, self.sessionId
)
if self.verbose:
print("Destroying comms.")
self.nccl_initialized = False
self.ucx_initialized = False
def local_handle(sessionId):
"""
Simple helper function for retrieving the local handle_t instance
for a comms session on a worker.
Parameters
----------
sessionId : str
session identifier from an initialized comms instance
Returns
-------
handle : raft.Handle or None
"""
state = get_raft_comm_state(sessionId, get_worker())
return state["handle"] if "handle" in state else None
def get_raft_comm_state(sessionId, state_object=None):
"""
Retrieves cuML comms state on the scheduler node, for the given sessionId,
creating a new session if it does not exist. If no session id is given,
returns the state dict for all sessions.
Parameters
----------
sessionId : SessionId value to retrieve from the dask_scheduler instances
state_object : Object (either Worker, or Scheduler) on which the raft
comm state will retrieved (or created)
Returns
-------
session state : str
session state associated with sessionId
"""
state_object = state_object if state_object is not None else get_worker()
if not hasattr(state_object, "_raft_comm_state"):
state_object._raft_comm_state = {}
if (
sessionId is not None
and sessionId not in state_object._raft_comm_state
):
state_object._raft_comm_state[sessionId] = {"ts": time.time()}
if sessionId is not None:
return state_object._raft_comm_state[sessionId]
return state_object._raft_comm_state
def set_nccl_root(sessionId, state_object):
if sessionId is None:
raise ValueError("sessionId cannot be None.")
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=state_object
)
if "nccl_uid" not in raft_comm_state:
raft_comm_state["nccl_uid"] = nccl.get_unique_id()
return raft_comm_state["nccl_uid"]
def get_ucx():
"""
A simple convenience wrapper to make sure UCP listener and
endpoints are only ever assigned once per worker.
"""
raft_comm_state = get_raft_comm_state(
sessionId="ucp", state_object=get_worker()
)
if "ucx" not in raft_comm_state:
raft_comm_state["ucx"] = UCX.get()
return raft_comm_state["ucx"]
def _func_destroy_scheduler_session(sessionId, dask_scheduler):
"""
Remove session date from _raft_comm_state, associated with sessionId
Parameters
----------
sessionId : session Id to be destroyed.
dask_scheduler : dask_scheduler object
(Note: this is supplied by DASK, not the client)
"""
if sessionId is not None and sessionId in dask_scheduler._raft_comm_state:
del dask_scheduler._raft_comm_state[sessionId]
else:
return 1
return 0
def _func_set_scheduler_as_nccl_root(sessionId, verbose, dask_scheduler):
"""
Creates a persistent nccl uniqueId on the scheduler node.
Parameters
----------
sessionId : Associated session to attach the unique ID to.
verbose : Indicates whether or not to emit additional information
dask_scheduler : dask scheduler object,
(Note: this is supplied by DASK, not the client)
Return
------
uniqueId : byte str
NCCL uniqueId, associating the DASK scheduler as its root node.
"""
if verbose:
logger.info(
msg=f"Setting scheduler as NCCL "
f"root for sessionId, '{sessionId}'"
)
nccl_uid = set_nccl_root(sessionId=sessionId, state_object=dask_scheduler)
if verbose:
logger.info("Done setting scheduler as NCCL root.")
return nccl_uid
def _func_set_worker_as_nccl_root(sessionId, verbose):
"""
Creates a persistent nccl uniqueId on the scheduler node.
Parameters
----------
sessionId : Associated session to attach the unique ID to.
verbose : Indicates whether or not to emit additional information
Return
------
uniqueId : byte str
NCCL uniqueId, associating this DASK worker as its root node.
"""
worker = get_worker()
if verbose:
worker.log_event(
topic="info",
msg=f"Setting worker as NCCL root for session, '{sessionId}'",
)
nccl_uid = set_nccl_root(sessionId=sessionId, state_object=worker)
if verbose:
worker.log_event(
topic="info", msg="Done setting scheduler as NCCL root."
)
return nccl_uid
def _func_ucp_listener_port():
return get_ucx().listener_port()
async def _func_init_all(
sessionId, uniqueId, comms_p2p, worker_info, verbose, streams_per_handle
):
worker = get_worker()
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=worker
)
raft_comm_state["nccl_uid"] = uniqueId
raft_comm_state["wid"] = worker_info[get_worker().address]["rank"]
raft_comm_state["nworkers"] = len(worker_info)
if verbose:
worker.log_event(topic="info", msg="Initializing NCCL.")
start = time.time()
_func_init_nccl(sessionId, uniqueId)
if verbose:
elapsed = time.time() - start
worker.log_event(
topic="info", msg=f"NCCL Initialization took: {elapsed} seconds."
)
if comms_p2p:
if verbose:
worker.log_event(topic="info", msg="Initializing UCX Endpoints")
if verbose:
start = time.time()
await _func_ucp_create_endpoints(sessionId, worker_info)
if verbose:
elapsed = time.time() - start
msg = (
f"Done initializing UCX endpoints."
f"Took: {elapsed} seconds.\nBuilding handle."
)
worker.log_event(topic="info", msg=msg)
_func_build_handle_p2p(sessionId, streams_per_handle, verbose)
if verbose:
worker.log_event(topic="info", msg="Done building handle.")
else:
_func_build_handle(sessionId, streams_per_handle, verbose)
def _func_init_nccl(sessionId, uniqueId):
"""
Initialize ncclComm_t on worker
Parameters
----------
sessionId : str
session identifier from a comms instance
uniqueId : array[byte]
The NCCL unique Id generated from the
client.
"""
worker = get_worker()
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=get_worker()
)
wid = raft_comm_state["wid"]
nWorkers = raft_comm_state["nworkers"]
try:
n = nccl()
n.init(nWorkers, uniqueId, wid)
raft_comm_state["nccl"] = n
except Exception as e:
worker.log_event(
topic="error", msg=f"An error occurred initializing NCCL: {e}."
)
raise
def _func_build_handle_p2p(sessionId, streams_per_handle, verbose):
"""
Builds a handle_t on the current worker given the initialized comms
Parameters
----------
sessionId : str id to reference state for current comms instance.
streams_per_handle : int number of internal streams to create
verbose : bool print verbose logging output
"""
worker = get_worker()
if verbose:
worker.log_event(topic="info", msg="Building p2p handle.")
ucp_worker = get_ucx().get_worker()
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=worker
)
handle = Handle(n_streams=streams_per_handle)
nccl_comm = raft_comm_state["nccl"]
eps = raft_comm_state["ucp_eps"]
nWorkers = raft_comm_state["nworkers"]
workerId = raft_comm_state["wid"]
if verbose:
worker.log_event(topic="info", msg="Injecting comms on handle.")
inject_comms_on_handle(
handle, nccl_comm, ucp_worker, eps, nWorkers, workerId, verbose
)
if verbose:
worker.log_event(
topic="info", msg="Finished injecting comms on handle."
)
raft_comm_state["handle"] = handle
def _func_build_handle(sessionId, streams_per_handle, verbose):
"""
Builds a handle_t on the current worker given the initialized comms
Parameters
----------
sessionId : str id to reference state for current comms instance.
streams_per_handle : int number of internal streams to create
verbose : bool print verbose logging output
"""
worker = get_worker()
if verbose:
worker.log_event(
topic="info", msg="Finished injecting comms on handle."
)
handle = Handle(n_streams=streams_per_handle)
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=worker
)
workerId = raft_comm_state["wid"]
nWorkers = raft_comm_state["nworkers"]
nccl_comm = raft_comm_state["nccl"]
inject_comms_on_handle_coll_only(
handle, nccl_comm, nWorkers, workerId, verbose
)
raft_comm_state["handle"] = handle
def _func_store_initial_state(nworkers, sessionId, uniqueId, wid):
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=get_worker()
)
raft_comm_state["nccl_uid"] = uniqueId
raft_comm_state["wid"] = wid
raft_comm_state["nworkers"] = nworkers
async def _func_ucp_create_endpoints(sessionId, worker_info):
"""
Runs on each worker to create ucp endpoints to all other workers
Parameters
----------
sessionId : str
uuid unique id for this instance
worker_info : dict
Maps worker addresses to NCCL ranks & UCX ports
"""
eps = [None] * len(worker_info)
count = 1
for k in worker_info:
ip, port = parse_host_port(k)
ep = await get_ucx().get_endpoint(ip, worker_info[k]["port"])
eps[worker_info[k]["rank"]] = ep
count += 1
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=get_worker()
)
raft_comm_state["ucp_eps"] = eps
async def _func_destroy_all(sessionId, comms_p2p, verbose=False):
worker = get_worker()
if verbose:
worker.log_event(topic="info", msg="Destroying NCCL session state.")
raft_comm_state = get_raft_comm_state(
sessionId=sessionId, state_object=worker
)
if "nccl" in raft_comm_state:
raft_comm_state["nccl"].destroy()
del raft_comm_state["nccl"]
if verbose:
worker.log_event(topic="info", msg="NCCL session state destroyed.")
else:
if verbose:
worker.log_event(
topic="warning",
msg=f"Session state for, '{sessionId}', "
f"does not contain expected 'nccl' element",
)
if verbose:
worker.log_event(
topic="info",
msg=f"Destroying CUDA handle for sessionId, '{sessionId}.'",
)
if "handle" in raft_comm_state:
del raft_comm_state["handle"]
else:
if verbose:
worker.log_event(
topic="warning",
msg=f"Session state for, '{sessionId}', "
f"does not contain expected 'handle' element",
)
def _func_ucp_ports(client, workers):
return client.run(_func_ucp_listener_port, workers=workers)
def _func_worker_ranks(workers):
"""
Builds a dictionary of { (worker_address, worker_port) : worker_rank }
"""
return dict(list(zip(workers, range(len(workers)))))