-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
distributed_c10d.py
2129 lines (1762 loc) · 74.2 KB
/
distributed_c10d.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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pickle
import torch
import warnings
import contextlib
from torch._six import string_classes
from datetime import timedelta
# This module is wildcard imported from torch.distributed.
# TODO: specify __all__
from .constants import default_pg_timeout
from .rendezvous import rendezvous, register_rendezvous_handler # noqa: F401
from . import (
AllreduceOptions,
AllreduceCoalescedOptions,
AllToAllOptions,
BroadcastOptions,
GatherOptions,
ReduceOptions,
ReduceScatterOptions,
ScatterOptions,
)
from . import ReduceOp
from . import PrefixStore
_MPI_AVAILABLE = True
_NCCL_AVAILABLE = True
_GLOO_AVAILABLE = True
try:
from. import ProcessGroupMPI
except ImportError:
_MPI_AVAILABLE = False
try:
from. import ProcessGroupNCCL
except ImportError:
_NCCL_AVAILABLE = False
try:
from. import ProcessGroupGloo
except ImportError:
_GLOO_AVAILABLE = False
class Backend(object):
"""
An enum-like class of available backends: GLOO, NCCL, MPI, and other registered
backends.
The values of this class are lowercase strings, e.g., ``"gloo"``. They can
be accessed as attributes, e.g., ``Backend.NCCL``.
This class can be directly called to parse the string, e.g.,
``Backend(backend_str)`` will check if ``backend_str`` is valid, and
return the parsed lowercase string if so. It also accepts uppercase strings,
e.g., ``Backend("GLOO")`` returns ``"gloo"``.
.. note:: The entry ``Backend.UNDEFINED`` is present but only used as
initial value of some fields. Users should neither use it directly
nor assume its existence.
"""
UNDEFINED = "undefined"
GLOO = "gloo"
NCCL = "nccl"
MPI = "mpi"
TCP = "tcp"
def __new__(cls, name):
if not isinstance(name, string_classes):
raise ValueError("Backend name must be a string, but got: {}".format(name))
value = getattr(Backend, name.upper(), Backend.UNDEFINED)
if value == Backend.TCP:
raise ValueError("TCP backend has been deprecated. Please use "
"Gloo or MPI backend for collective operations "
"on CPU tensors.")
elif value == Backend.UNDEFINED:
raise ValueError("Invalid backend: '{}'".format(name))
elif value != Backend.GLOO and value != Backend.NCCL and value != Backend.MPI:
value = name
return value
@classmethod
def register_backend(cls, name, func):
"""
Registers a new backend.
This class method is used by 3rd party cpp extension to register new backend.
Arguments:
name (str): Backend name matching with the one in `init_process_group()`.
func (function): Function handler that instantiates the backend.
The function should be implemented in the backend cpp extension
and takes four arguments, including prefix_store, rank,
world_size, and timeout.
.. note:: This support of 3rd party backend is experimental and subject to change.
"""
setattr(Backend, name.upper(), func)
# `_backend`, `dist_backend`, and `reduce_op` are here to maintain backward
# compatibility with pre-c10d distributed package.
# TODO: remove them when users are ready to take a hard dependency on PyTorch 1.
_backend = Backend.UNDEFINED
dist_backend = Backend
class reduce_op(object):
r"""
Deprecated enum-like class for reduction operations: ``SUM``, ``PRODUCT``,
``MIN``, and ``MAX``.
:class:`~torch.distributed.ReduceOp` is recommended to use instead.
"""
def __init__(self):
# __members__ is a dict storing key-value pairs for enum classes
for k, v in ReduceOp.__members__.items():
setattr(self, k, v)
self.__members__ = ReduceOp.__members__
def __getattribute__(self, key):
warnings.warn("torch.distributed.reduce_op is deprecated, please use "
"torch.distributed.ReduceOp instead")
return object.__getattribute__(self, key)
reduce_op = reduce_op()
class group(object):
WORLD = object()
class GroupMember(object):
# Alias to group.WORLD for backward compatibility
WORLD = group.WORLD
NON_GROUP_MEMBER = object()
# Cached process groups
# For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)
# For MPI pg, it is a map from ProcessGroup to (Backend, None)
_pg_map = {}
# Process group's names, map from ProcessGroup to str
_pg_names = {}
# Process group's global rank to local rank mapping
_pg_group_ranks = {}
# Default process group state
_default_pg = None
_default_pg_init_method = None
# Process group count for default naming
_group_count = 0
def _rank_not_in_group(group):
"""
Helper that checks if the current process's rank is not in a given group.
"""
if group == GroupMember.WORLD:
return False
return group == GroupMember.NON_GROUP_MEMBER
def _get_group_rank(group, rank):
"""
Helper that gets a given group's local rank in the group from a given global
rank.
"""
if group is GroupMember.WORLD:
raise RuntimeError("group.WORLD does not have local rank to global "
"rank mapping")
if group not in _pg_group_ranks:
raise RuntimeError("The given group does not exist")
try:
group_rank = _pg_group_ranks[group][rank]
except KeyError:
raise RuntimeError(f"The global rank {rank} is not part of the group {group}") from None
return group_rank
def _get_global_rank(group, group_rank):
"""
Helper that gets a given group's global rank from a given local rank in the
group.
"""
if group is GroupMember.WORLD:
raise RuntimeError("group.WORLD does not have local rank to global "
"rank mapping")
group_rank_map = _pg_group_ranks[group]
for rank, grp_rank in group_rank_map.items():
if grp_rank == group_rank:
return rank
raise RuntimeError("The group rank is not part of the group")
def _check_default_pg():
"""
Helper that checks if the default ProcessGroup has been initialized, with
assertion.
"""
assert _default_pg is not None, \
"Default process group is not initialized"
def _get_group_size(group):
"""
Helper that gets a given group's world size.
"""
if group is GroupMember.WORLD:
_check_default_pg()
return _default_pg.size()
if group not in _pg_group_ranks:
raise RuntimeError("The given group does not exist")
return len(_pg_group_ranks[group])
def _check_single_tensor(param, param_name):
"""
Helper to check that the parameter ``param_name`` is a single tensor.
"""
if not isinstance(param, torch.Tensor):
raise RuntimeError("Invalid function argument. Expected parameter `{}` "
"to be of type torch.Tensor.".format(param_name))
def _check_tensor_list(param, param_name):
"""
Helper to check that the parameter ``param_name`` is a list of tensors.
"""
if not isinstance(param, list) or \
not all(isinstance(p, torch.Tensor) for p in param):
raise RuntimeError("Invalid function argument. Expected parameter `{}` "
"to be of type List[torch.Tensor].".format(param_name))
def _check_op_list(op_list, list_name):
"""
Helper to check that the ``op_list`` is a list of functions.
"""
if not isinstance(op_list, list) or \
not all(op in [isend, irecv] for op in op_list):
raise RuntimeError(f"Invalid function. Expected fucntion in `{op_list}` "
f"to be of type torch.distributed.isend or "
f"torch.distributed.irecv.")
def _check_input_length(op_list, tensor_list, peer_list, group_list, tag_list):
"""
Helper to check that all the inputs have the same length.
"""
expected_length = len(op_list)
check_list = [tensor_list, peer_list]
if group_list is not None:
check_list.append(group_list)
if tag_list is not None:
check_list.append(tag_list)
for curr_list in check_list:
if not isinstance(curr_list, list) or expected_length != len(curr_list):
raise RuntimeError(f"Expected parameters to be the same length, "
f"{expected_length} vs {len(curr_list)}, value: {curr_list}")
def _check_group_backend(group_list, backend_name):
"""
Helper to check that all groups in ``group_list`` use the same backend.
"""
if not isinstance(group_list, list) or \
not all(backend_name == get_backend(group) for group in group_list):
raise RuntimeError("All groups need to use the same backend.")
def is_mpi_available():
"""
Checks if the MPI backend is available.
"""
return _MPI_AVAILABLE
def is_nccl_available():
"""
Checks if the NCCL backend is available.
"""
return _NCCL_AVAILABLE
def is_gloo_available():
"""
Checks if the Gloo backend is available.
"""
return _GLOO_AVAILABLE
def is_initialized():
"""
Checking if the default process group has been initialized
"""
return _default_pg is not None
def _get_default_group():
"""
Getting the default process group created by init_process_group
"""
if not is_initialized():
raise RuntimeError("Default process group has not been initialized, "
"please make sure to call init_process_group.")
return _default_pg
def _get_default_store():
"""
Getting the default store created by init_process_group
"""
if not is_initialized():
raise RuntimeError("Default process group has not been initialized, "
"please make sure to call init_process_group.")
_, default_store = _pg_map[_default_pg]
return default_store
def get_backend(group=group.WORLD):
"""
Returns the backend of the given process group.
Arguments:
group (ProcessGroup, optional): The process group to work on. The
default is the general main process group. If another specific group
is specified, the calling process must be part of :attr:`group`.
Returns:
The backend of the given process group as a lower case string.
"""
_check_default_pg()
if group == GroupMember.WORLD:
pg = _default_pg
else:
pg = group
if _rank_not_in_group(pg):
raise RuntimeError("Invalid process group specified")
return _pg_map.get(pg, None)[0]
def init_process_group(backend,
init_method=None,
timeout=default_pg_timeout,
world_size=-1,
rank=-1,
store=None,
group_name=''):
"""
Initializes the default distributed process group, and this will also
initialize the distributed package.
There are 2 main ways to initialize a process group:
1. Specify ``store``, ``rank``, and ``world_size`` explicitly.
2. Specify ``init_method`` (a URL string) which indicates where/how
to discover peers. Optionally specify ``rank`` and ``world_size``,
or encode all required parameters in the URL and omit them.
If neither is specified, ``init_method`` is assumed to be "env://".
Arguments:
backend (str or Backend): The backend to use. Depending on
build-time configurations, valid values include ``mpi``, ``gloo``,
and ``nccl``. This field should be given as a lowercase string
(e.g., ``"gloo"``), which can also be accessed via
:class:`Backend` attributes (e.g., ``Backend.GLOO``). If using
multiple processes per machine with ``nccl`` backend, each process
must have exclusive access to every GPU it uses, as sharing GPUs
between processes can result in deadlocks.
init_method (str, optional): URL specifying how to initialize the
process group. Default is "env://" if no
``init_method`` or ``store`` is specified.
Mutually exclusive with ``store``.
world_size (int, optional): Number of processes participating in
the job. Required if ``store`` is specified.
rank (int, optional): Rank of the current process.
Required if ``store`` is specified.
store(Store, optional): Key/value store accessible to all workers, used
to exchange connection/address information.
Mutually exclusive with ``init_method``.
timeout (timedelta, optional): Timeout for operations executed against
the process group. Default value equals 30 minutes.
This is applicable for the ``gloo`` backend. For ``nccl``, this is
applicable only if the environment variable ``NCCL_BLOCKING_WAIT``
is set to 1.
group_name (str, optional, deprecated): Group name.
To enable ``backend == Backend.MPI``, PyTorch needs to be built from source
on a system that supports MPI.
"""
global _pg_group_ranks
global _backend
global _default_pg
global _default_pg_init_method
if not isinstance(timeout, timedelta):
raise RuntimeError("Expected timeout argument to be of type"
"datetime.timedelta")
if _default_pg is not None:
raise RuntimeError("trying to initialize the default process group "
"twice!")
assert (store is None) or (init_method is None), \
"Cannot specify both init_method and store."
if store is not None:
assert world_size > 0, 'world_size must be positive if using store'
assert rank >= 0, 'rank must be non-negative if using store'
elif init_method is None:
init_method = "env://"
backend = Backend(backend)
if backend == Backend.MPI:
if world_size != -1 or rank != -1:
warnings.warn(
"For MPI backend, world_size ({}) and rank ({}) "
"are ignored since they are assigned by the "
"MPI runtime.".format(world_size, rank))
_default_pg = _new_process_group_helper(
-1,
-1,
[],
Backend.MPI,
None,
group_name=group_name,
timeout=timeout)
else:
# backward compatible API
if store is None:
rendezvous_iterator = rendezvous(
init_method, rank, world_size, timeout=timeout
)
store, rank, world_size = next(rendezvous_iterator)
store.set_timeout(timeout)
_default_pg = _new_process_group_helper(
world_size,
rank,
[],
backend,
store,
group_name=group_name,
timeout=timeout)
_pg_group_ranks[_default_pg] = {i: i for i in range(_default_pg.size())}
_backend = _pg_map[_default_pg][0]
_default_pg_init_method = init_method
def _new_process_group_helper(world_size,
rank,
group_ranks,
backend,
store,
group_name=None,
timeout=default_pg_timeout):
"""
Create a new distributed process group.
This function must be called by ALL processes in the global group, even if
the calling process is not part of the newly created group. In that case,
this function returns GroupMember.NON_GROUP_MEMBER.
This function is called with ``group_ranks == []`` for the default group.
"""
global _pg_map
global _group_count
global _pg_names
if not group_name:
group_name = str(_group_count)
_group_count += 1
if group_name in _pg_names.values():
raise RuntimeError("The specified group name has already been "
"created, please use a different group name")
if not isinstance(timeout, timedelta):
raise RuntimeError("Expected timeout argument to be of type"
"datetime.timedelta")
# The list of group ranks is empty if we're creating the default group.
is_default_group = (len(group_ranks) == 0)
backend = Backend(backend)
if backend == Backend.MPI:
if not is_mpi_available():
raise RuntimeError(
"Distributed package doesn't have MPI built in."
" MPI is only included if you build PyTorch from"
" source on a host that has MPI installed.")
pg = ProcessGroupMPI.create(group_ranks)
if not pg:
return GroupMember.NON_GROUP_MEMBER
_pg_map[pg] = (Backend.MPI, None)
_pg_names[pg] = group_name
else:
# If this is a subgroup (which means group_ranks is specified),
# we check if the current process is a member of the new group.
if not is_default_group:
global_rank = _default_pg.rank()
if global_rank not in group_ranks:
return GroupMember.NON_GROUP_MEMBER
# Use the group name as prefix in the default store, such that
# a single store can be reused by multiple groups.
prefix_store = PrefixStore(group_name, store)
if backend == Backend.GLOO:
pg = ProcessGroupGloo(
prefix_store,
rank,
world_size,
timeout=timeout)
_pg_map[pg] = (Backend.GLOO, store)
_pg_names[pg] = group_name
elif backend == Backend.NCCL:
if not is_nccl_available():
raise RuntimeError("Distributed package doesn't have NCCL "
"built in")
pg = ProcessGroupNCCL(
prefix_store,
rank,
world_size,
timeout)
_pg_map[pg] = (Backend.NCCL, store)
_pg_names[pg] = group_name
else:
pg = getattr(Backend, backend.upper())(
prefix_store,
rank,
world_size,
timeout)
_pg_map[pg] = (backend, store)
_pg_names[pg] = group_name
return pg
def destroy_process_group(group=group.WORLD):
"""
Destroy a given process group, and deinitialize the distributed package
Arguments:
group (ProcessGroup, optional): The process group to be destroyed, if
group.WORLD is given, all process
groups including the default one will
be destroyed.
"""
global _pg_map
global _pg_names
global _pg_group_ranks
global _default_pg
global _default_pg_init_method
global _group_count
if group == GroupMember.NON_GROUP_MEMBER:
return
if group == GroupMember.WORLD:
pg = _default_pg
else:
pg = group
if _pg_map.get(pg, None) is None:
raise RuntimeError("Invalid process group specified")
if group == GroupMember.WORLD:
_default_pg = None
_default_pg_init_method = None
_pg_map.clear()
_pg_names.clear()
_pg_group_ranks.clear()
# when process group doesn't have an explicit name (only WORLD (default)
# process group can have an explicit name), we use global _group_counter
# to generate the name. We need to reset the counter on destruction to
# allow consistent value to be generated when we re-create process
# groups after some trainers recover from failure
#
# We only reset this when WORLD is being destroyed because if this
# process group is in good state, we aren't dealing with failures.
_group_count = 0
else:
del _pg_map[pg]
del _pg_names[pg]
del _pg_group_ranks[pg]
def get_rank(group=group.WORLD):
"""
Returns the rank of current process group
Rank is a unique identifier assigned to each process within a distributed
process group. They are always consecutive integers ranging from 0 to
``world_size``.
Arguments:
group (ProcessGroup, optional): The process group to work on
Returns:
The rank of the process group
-1, if not part of the group
"""
if _rank_not_in_group(group):
return -1
_check_default_pg()
if group == GroupMember.WORLD:
return _default_pg.rank()
return _get_group_rank(group, _default_pg.rank())
def get_world_size(group=group.WORLD):
"""
Returns the number of processes in the current process group
Arguments:
group (ProcessGroup, optional): The process group to work on
Returns:
The world size of the process group
-1, if not part of the group
"""
if _rank_not_in_group(group):
return -1
return _get_group_size(group)
def isend(tensor,
dst,
group=group.WORLD,
tag=0):
"""
Sends a tensor asynchronously.
Arguments:
tensor (Tensor): Tensor to send.
dst (int): Destination rank.
group (ProcessGroup, optional): The process group to work on
tag (int, optional): Tag to match send with remote recv
Returns:
A distributed request object.
None, if not part of the group
"""
_check_single_tensor(tensor, "tensor")
if _rank_not_in_group(group):
return
if group == GroupMember.WORLD:
_check_default_pg()
return _default_pg.send([tensor], dst, tag)
else:
group_dst_rank = _get_group_rank(group, dst)
return group.send([tensor], group_dst_rank, tag)
def irecv(tensor,
src,
group=group.WORLD,
tag=0):
"""
Receives a tensor asynchronously.
Arguments:
tensor (Tensor): Tensor to fill with received data.
src (int): Source rank.
group (ProcessGroup, optional): The process group to work on
tag (int, optional): Tag to match recv with remote send
Returns:
A distributed request object.
None, if not part of the group
"""
_check_single_tensor(tensor, "tensor")
if _rank_not_in_group(group):
return
if group == GroupMember.WORLD:
_check_default_pg()
return _default_pg.recv([tensor], src, tag)
else:
group_src_rank = _get_group_rank(group, src)
return group.recv([tensor], group_src_rank, tag)
def send(tensor,
dst,
group=group.WORLD,
tag=0):
"""
Sends a tensor synchronously.
Arguments:
tensor (Tensor): Tensor to send.
dst (int): Destination rank.
group (ProcessGroup, optional): The process group to work on
tag (int, optional): Tag to match send with remote recv
"""
_check_single_tensor(tensor, "tensor")
if _rank_not_in_group(group):
return
if group == GroupMember.WORLD:
_check_default_pg()
_default_pg.send([tensor], dst, tag).wait()
else:
group_dst_rank = _get_group_rank(group, dst)
group.send([tensor], group_dst_rank, tag).wait()
def recv(tensor,
src=None,
group=group.WORLD,
tag=0):
"""
Receives a tensor synchronously.
Arguments:
tensor (Tensor): Tensor to fill with received data.
src (int, optional): Source rank. Will receive from any
process if unspecified.
group (ProcessGroup, optional): The process group to work on
tag (int, optional): Tag to match recv with remote send
Returns:
Sender rank
-1, if not part of the group
"""
_check_single_tensor(tensor, "tensor")
if _rank_not_in_group(group):
return -1
if group == GroupMember.WORLD:
_check_default_pg()
pg = _default_pg
else:
pg = group
if src is None:
work = pg.recv_anysource([tensor], tag)
work.wait()
src_rank = work.source_rank()
if group == GroupMember.WORLD:
return src_rank
else:
return _get_global_rank(pg, src_rank)
else:
if group == GroupMember.WORLD:
pg.recv([tensor], src, tag).wait()
else:
group_src_rank = _get_group_rank(pg, src)
pg.recv([tensor], group_src_rank, tag).wait()
return src
@contextlib.contextmanager
def _batch_p2p_manager(backend):
if backend == Backend.NCCL:
ProcessGroupNCCL._group_start()
try:
yield
finally:
if backend == Backend.NCCL:
ProcessGroupNCCL._group_end()
def batch_isend_irecv(op_list,
tensor_list,
peer_list,
group_list=None,
tag_list=None):
"""
Send or Receive tensors asynchronously and return a list of requests.
Process the first item in each passed parameters, and then the second item
in each passed parameters, etc. Each of these lists should be the same length
as the op_list. The ``ith`` element in ``tensor_list``, ``peer_list``, ``group_list``,
and ``tag_list`` are the communication tensor, peer process, Process Group
group, tag, respectively, for the `ith` element of ``op_list``.
Arguments:
op_list: list of point-to-point operations(type of each operations is either
``torch.distributed.isend`` or ``torch.distributed.irecv``. The order of the
isend/irecv in the list matters and it needs to match with corresponding
isend/irecv on the remote end.
tensor_list (list[Tensor]): list of send or recv tensors.
peer_list (list[int]): list of peer ranks to send to or receive from.
group_list (list[ProcessGroup], Optional): list of groups to operator on. All
groups in ``group_list`` should use the same backend.
tag_list (list[int], Optional): list of tags to match send with recv.
Returns:
A list of distributed request objects returned by calling the corresponding
op in the op_list.
Examples:
>>> send_tensor = torch.arange(2) + 2 * rank
>>> recv_tensor = torch.randn(2)
>>> op_list = [dist.isend, dist.irecv]
>>> tensor_list = [send_tensor, recv_tensor]
>>> peer_list = [(rank + 1) % world_size, (rank + 1) % world_size]
>>> reqs = batch_isend_irecv(op_list, tensor_list, peer_list)
>>> for req in reqs:
>>> req.wait()
>>> recv_tensor
tensor([2, 3]) # Rank 0
tensor([0, 1]) # Rank 1
"""
_check_op_list(op_list, "op_list")
_check_input_length(op_list, tensor_list, peer_list, group_list, tag_list)
backend = get_backend(group.WORLD if group_list is None else group_list[0])
if group_list is not None:
_check_group_backend(group_list, backend)
reqs = []
with _batch_p2p_manager(backend):
for i in range(len(op_list)):
op = op_list[i]
tensor = tensor_list[i]
peer = peer_list[i]
curr_group = group.WORLD if group_list is None else group_list[i]
tag = 0 if tag_list is None else tag_list[i]
ret = op(tensor, peer, curr_group, tag)
if ret is not None:
reqs.append(ret)
return reqs
def broadcast_multigpu(tensor_list,
src,
group=group.WORLD,
async_op=False,
src_tensor=0):
"""
Broadcasts the tensor to the whole group with multiple GPU tensors
per node.
``tensor`` must have the same number of elements in all the GPUs from
all processes participating in the collective. each tensor in the list must
be on a different GPU
Only nccl and gloo backend are currently supported
tensors should only be GPU tensors
Arguments:
tensor_list (List[Tensor]): Tensors that participate in the collective
operation. If ``src`` is the rank, then the specified ``src_tensor``
element of ``tensor_list`` (``tensor_list[src_tensor]``) will be
broadcast to all other tensors (on different GPUs) in the src process
and all tensors in ``tensor_list`` of other non-src processes.
You also need to make sure that ``len(tensor_list)`` is the same
for all the distributed processes calling this function.
src (int): Source rank.
group (ProcessGroup, optional): The process group to work on
async_op (bool, optional): Whether this op should be an async op
src_tensor (int, optional): Source tensor rank within ``tensor_list``
Returns:
Async work handle, if async_op is set to True.
None, if not async_op or if not part of the group
"""
if _rank_not_in_group(group):
return
opts = BroadcastOptions()
opts.rootRank = src
opts.rootTensor = src_tensor
if group == GroupMember.WORLD:
_check_default_pg()
work = _default_pg.broadcast(tensor_list, opts)
else:
group_src_rank = _get_group_rank(group, src)
opts.rootRank = group_src_rank
work = group.broadcast(tensor_list, opts)
if async_op:
return work
else:
work.wait()
def broadcast(tensor,
src,
group=group.WORLD,
async_op=False):
"""
Broadcasts the tensor to the whole group.
``tensor`` must have the same number of elements in all processes
participating in the collective.
Arguments:
tensor (Tensor): Data to be sent if ``src`` is the rank of current
process, and tensor to be used to save received data otherwise.
src (int): Source rank.
group (ProcessGroup, optional): The process group to work on
async_op (bool, optional): Whether this op should be an async op
Returns:
Async work handle, if async_op is set to True.
None, if not async_op or if not part of the group
"""
_check_single_tensor(tensor, "tensor")
if _rank_not_in_group(group):
return
opts = BroadcastOptions()
opts.rootRank = src
opts.rootTensor = 0
if group == GroupMember.WORLD:
_check_default_pg()
work = _default_pg.broadcast([tensor], opts)
else:
group_src_rank = _get_group_rank(group, src)
opts.rootRank = group_src_rank
work = group.broadcast([tensor], opts)
if async_op:
return work
else:
work.wait()
def all_reduce_multigpu(tensor_list,
op=ReduceOp.SUM,
group=group.WORLD,
async_op=False):
r"""
Reduces the tensor data across all machines in such a way that all get
the final result. This function reduces a number of tensors on every node,
while each tensor resides on different GPUs.
Therefore, the input tensor in the tensor list needs to be GPU tensors.
Also, each tensor in the tensor list needs to reside on a different GPU.
After the call, all ``tensor`` in ``tensor_list`` is going to be bitwise
identical in all processes.
Only nccl and gloo backend is currently supported
tensors should only be GPU tensors
Arguments:
tensor list (List[Tensor]): List of input and output tensors of
the collective. The function operates in-place and requires that
each tensor to be a GPU tensor on different GPUs.
You also need to make sure that ``len(tensor_list)`` is the same for
all the distributed processes calling this function.
op (optional): One of the values from
``torch.distributed.ReduceOp``
enum. Specifies an operation used for element-wise reductions.
group (ProcessGroup, optional): The process group to work on
async_op (bool, optional): Whether this op should be an async op
Returns:
Async work handle, if async_op is set to True.
None, if not async_op or if not part of the group
"""
if _rank_not_in_group(group):
return
opts = AllreduceOptions()
opts.reduceOp = op
if group == GroupMember.WORLD:
_check_default_pg()
work = _default_pg.allreduce(tensor_list, opts)
else:
work = group.allreduce(tensor_list, opts)
if async_op: