-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
distributed_test.py
10125 lines (9115 loc) · 415 KB
/
distributed_test.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 copy
import itertools
import math
import os
import random
import sys
import tempfile
import time
from collections import namedtuple, OrderedDict
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from datetime import timedelta
from functools import reduce
from typing import Union, NamedTuple, Callable, Any
import numpy as np
import torch
import torch.cuda
import torch.distributed as dist
import torch.distributed.algorithms.model_averaging.averagers as averagers
import torch.distributed.algorithms.model_averaging.hierarchical_model_averager as hierarchicalSGD
import torch.distributed.algorithms.model_averaging.utils as model_averaging_utils
import torch.nn as nn
import torch.nn.functional as F
from torch._utils_internal import TEST_MASTER_ADDR as MASTER_ADDR
from torch._utils_internal import TEST_MASTER_PORT as MASTER_PORT
from torch.cuda.amp import GradScaler, autocast
from torch.distributed.algorithms.ddp_comm_hooks import (
post_localSGD_hook as post_localSGD,
powerSGD_hook as powerSGD,
default_hooks as default,
quantization as quantization_hooks,
)
from torch.distributed.optim import _apply_optimizer_in_backward
from torch.distributed.distributed_c10d import (
get_world_size,
_get_default_group,
AllreduceOptions,
GroupMember,
)
from torch.distributed.utils import (
_verify_param_shape_across_processes,
_sync_module_states,
)
from torch.nn.parallel import DistributedDataParallel
from torch.nn.parallel.distributed import _dump_DDP_relevant_env_vars, _MixedPrecision
from torch.testing._internal.common_distributed import (
MultiProcessTestCase,
TEST_SKIPS,
init_multigpu_helper,
initialize_temp_directories,
cleanup_temp_dir,
simple_sparse_reduce_tests,
skip_if_rocm,
skip_if_small_worldsize,
skip_if_odd_worldsize,
skip_if_lt_x_gpu,
nccl_skip_if_lt_x_gpu,
skip_if_no_gpu,
require_n_gpus_for_nccl_backend,
requires_nccl_version,
captured_output,
with_nccl_blocking_wait,
with_dist_debug_levels,
verify_ddp_error_logged,
DistTestCases,
)
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
IS_MACOS,
IS_WINDOWS,
FILE_SCHEMA,
IS_FBCODE,
NO_MULTIPROCESSING_SPAWN,
IS_SANDCASTLE,
skip_but_pass_in_sandcastle,
skip_but_pass_in_sandcastle_if,
)
import torch.distributed.optim.post_localSGD_optimizer as post_localSGD_optimizer
from torch.utils.data.distributed import DistributedSampler
try:
import torchvision
HAS_TORCHVISION = True
except ImportError:
HAS_TORCHVISION = False
if sys.platform == "win32":
import msvcrt
else:
import fcntl
class NetWithBuffers(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(10, 10, bias=False)
self.b = nn.Linear(10, 1, bias=False)
self.register_buffer("buffer", torch.randn(1, 2))
def forward(self, x):
self.buffer.add_(1)
return self.b(self.a(x))
class Foo:
def __init__(self, x):
# Can be tensor or int
self.x = x
def __eq__(self, other):
def eq(value, other):
if isinstance(value, torch.Tensor):
return torch.equal(value, other)
return value == other
for attr, value in self.__dict__.items():
other_value = other.__dict__[attr]
if not eq(value, other_value):
return False
return True
f = Foo(10)
f.bar = 1
foo_cpu_tensor = Foo(torch.randn(3, 3))
COLLECTIVES_OBJECT_TEST_LIST = [
{"key1": 3, "key2": 4, "key3": {"nested": True}},
f,
foo_cpu_tensor,
"foo",
[1, 2, True, "string", [4, 5, "nested"]],
]
# Allowlist of distributed backends where profiling collectives is supported.
PROFILING_SUPPORTED_BACKENDS = [
dist.Backend.NCCL,
dist.Backend.GLOO,
dist.Backend.MPI,
dist.Backend.UCC,
]
# Allowlist of distributed backends where profiling is supported with use_cuda=True
CUDA_PROFILING_SUPPORTED_BACKENDS = [
dist.Backend.GLOO,
dist.Backend.MPI,
dist.Backend.NCCL,
dist.Backend.UCC,
]
# Allowlist of distributed backends where profiling is supported for p2p ops
SEND_RECV_PROFILING_SUPPORTED_BACKENDS = [
dist.Backend.MPI,
dist.Backend.GLOO,
dist.Backend.NCCL,
dist.Backend.UCC,
]
# Dummy NamedTuple data structures to test DDP support for NamedTuple types.
EXPECTED_FIELDS = ("a", "b")
TestNamedTupleInput_0 = namedtuple("NamedTuple", EXPECTED_FIELDS)
class TestNamedTupleInput_1(NamedTuple):
a: torch.tensor
b: torch.tensor
skipIfNoTorchVision = skip_but_pass_in_sandcastle_if(
not HAS_TORCHVISION, "no torchvision"
)
BACKEND = os.environ["BACKEND"]
INIT_METHOD = os.getenv("INIT_METHOD", "env://")
DEFAULT_TIMEOUT = 300
CUSTOMIZED_TIMEOUT = {"test_DistributedDataParallel": 500}
def get_profiling_event(postfix, profiler):
event_list = (
profiler.events()
if isinstance(profiler, torch.profiler.profile)
else profiler.function_events
)
return [event for event in event_list if event.name.endswith(postfix)]
# Base error message substring on unfinished reductions.
ddp_prev_reduction_unfinished_str = (
"Expected to have finished reduction in the prior iteration"
)
# Error message substring when find_unused_parameters=True has not been passed
ddp_recommend_find_unused_params_str = (
"passing the keyword argument `find_unused_parameters=True`"
)
# Error message substring when find_unused_parameters=True is enabled
ddp_find_unused_params_enabled_str = "Since `find_unused_parameters=True` is enabled"
# Error message substring for possibility of not all model outputs being used
# in loss computation
ddp_outputs_not_used_in_loss_str = (
"`forward` function outputs participate in calculating loss"
)
# Error message substring suggesting to use TORCH_DISTRIBUTED_DEBUG
ddp_suggest_debug_mode_str = (
"set the environment variable TORCH_DISTRIBUTED_DEBUG to either INFO or DETAIL"
)
class DDPUnevenTestInput(NamedTuple):
name: str
model: nn.Module
inp: Union[torch.tensor, tuple]
sync_interval: int
throw_on_early_termination: bool = False
hook: Callable = None
state: Any = None
class _FC2(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(10, 50, bias=True)
self.fc.bias.requires_grad = False
def forward(self, x):
x = self.fc(x)
return x
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2, 10, bias=False)
self.fc2 = _FC2()
self.fc3 = nn.Linear(50, 4, bias=False)
self.relu = nn.ReLU()
self.no_grad_param = nn.Parameter(
torch.tensor([2, 2]).long(), requires_grad=False
)
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return F.softmax(x, dim=1)
class LargeNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(1000, 2000, bias=False)
self.fc2 = nn.Linear(2000, 500, bias=False)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
return x
class Task(nn.Module):
def __init__(self):
super().__init__()
self.p = nn.Parameter(torch.ones(2, 2))
def forward(self, x):
return self.p + x
class BatchNormNet(nn.Module):
def __init__(self, affine=True):
super().__init__()
self.fc1 = nn.Linear(2, 40, bias=False)
self.bn = nn.BatchNorm1d(4, affine=affine)
self.fc2 = nn.Linear(40, 4, bias=False)
def forward(self, x):
x = torch.reshape(self.fc1(x), (-1, 4, 10))
x = self.bn(x)
x = torch.reshape(x, (-1, 40))
x = self.fc2(x)
return F.softmax(x, dim=1)
class UnusedParamTwoLinLayerNet(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(10, 10, bias=False)
self.b = nn.Linear(10, 10, bias=False)
self.c = nn.Linear(5, 5, bias=False)
def forward(self, x):
a = self.a(x)
b = self.b(x)
return (a, b)
class DictOutputModule(nn.Module):
def __init__(self):
super().__init__()
self.module = UnusedParamTwoLinLayerNet()
def forward(self, x):
predictions = self.module(x)
loss = (predictions[0] + predictions[1]).sum()
return {
"predictions": predictions,
"loss": loss,
}
class TwoLinLayerNet(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(10, 10, bias=False)
self.b = nn.Linear(10, 1, bias=False)
def forward(self, x):
a = self.a(x)
b = self.b(x)
return (a, b)
class EmbeddingNetDifferentParams(nn.Module):
"""
A module containing an embedding with different dimension or different # of
parameters depending on the rank.
"""
def __init__(self, rank, diff_num_params=False):
super().__init__()
embedding_dim = 500 if diff_num_params or rank == 0 else 50
self.embedding = nn.Embedding(num_embeddings=10, embedding_dim=embedding_dim)
self.lin = nn.Linear(embedding_dim, 1)
if diff_num_params:
self.lin2 = nn.Linear(1, 1, bias=False)
def forward(self, x):
x = self.embedding(x)
return self.lin(x)
class ControlFlowToyModel(nn.Module):
def __init__(self):
super().__init__()
self.lin1 = nn.Linear(10, 10, bias=False)
self.lin2 = nn.Linear(10, 10, bias=False)
def forward(self, x):
# Second layer is used dependent on input x.
use_second_layer = torch.equal(x, torch.ones(20, 10, device=x.device))
if use_second_layer:
return self.lin2(F.relu(self.lin1(x)))
else:
return F.relu(self.lin1(x))
DDP_NET = Net()
BN_NET = BatchNormNet()
BN_NET_NO_AFFINE = BatchNormNet(affine=False)
ONLY_SBN_NET = nn.SyncBatchNorm(2, momentum=0.99)
def get_timeout(test_id):
test_name = test_id.split(".")[-1]
if test_name in CUSTOMIZED_TIMEOUT:
return CUSTOMIZED_TIMEOUT[test_name]
else:
return DEFAULT_TIMEOUT
default_pg_timeout = 60
CUSTOM_PG_TIMEOUT = {
# This test runs slowly and needs additional time to complete, otherwise can
# be taken down by NCCL_ASYNC_ERROR_HANDLING
"test_ddp_uneven_inputs": 300,
# This test has a short timeout since it tests being taken down by
# NCCL_ASYNC_ERROR_HANDLING which we want to happen quickly.
"test_ddp_model_diff_across_ranks": 5,
# This test has a short timeout since it tests being taken down by
# NCCL_ASYNC_ERROR_HANDLING which we want to happen quickly.
"test_ddp_has_finalized": 5,
}
def require_backend_is_available(backends):
def check(backend):
if backend == dist.Backend.GLOO:
return dist.is_gloo_available()
if backend == dist.Backend.NCCL:
return dist.is_nccl_available()
if backend == dist.Backend.MPI:
return dist.is_mpi_available()
if backend == dist.Backend.UCC:
return dist.is_ucc_available()
if backend in DistTestCases.backend_feature["plugin"]:
return True
return False
if BACKEND not in backends:
return skip_but_pass_in_sandcastle(
f"Test requires backend {BACKEND} to be one of {backends}"
)
if not check(dist.Backend(BACKEND)):
return skip_but_pass_in_sandcastle(
f"Test requires backend {BACKEND} to be available"
)
return lambda func: func
def require_world_size(world_size):
if int(os.environ["WORLD_SIZE"]) < world_size:
return skip_but_pass_in_sandcastle(
"Test requires world size of %d" % world_size
)
return lambda func: func
@contextmanager
def _lock():
TEMP_DIR = os.environ["TEMP_DIR"]
lockfile = os.path.join(TEMP_DIR, "lockfile")
with open(lockfile, "w") as lf:
try:
if sys.platform == "win32":
msvcrt.locking(lf.fileno(), msvcrt.LK_RLCK, 1)
yield
else:
fcntl.flock(lf.fileno(), fcntl.LOCK_EX)
yield
finally:
if sys.platform == "win32":
msvcrt.locking(lf.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(lf.fileno(), fcntl.LOCK_UN)
lf.close()
@contextmanager
def _rank_temp_file():
if dist.get_rank() == 0:
fd, name = tempfile.mkstemp()
os.close(fd)
else:
name = None
object_list = [name]
dist.broadcast_object_list(object_list)
name = object_list[0]
try:
yield name
finally:
if dist.get_rank() == 0:
os.remove(name)
def _build_tensor(size, value=None, dtype=torch.float, device_id=None):
if value is None:
value = size
if device_id is None:
return torch.empty(size, size, size, dtype=dtype).fill_(value)
else:
return torch.empty(size, size, size, dtype=dtype).fill_(value).cuda(device_id)
def _build_multidim_tensor(dim, dim_size, value=None, dtype=torch.float):
if value is None:
value = dim
return torch.empty(size=[dim_size for _ in range(dim)], dtype=dtype).fill_(value)
def _create_autograd_profiler():
return torch.autograd.profiler.profile(record_shapes=True)
def _create_torch_profiler():
return torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
],
record_shapes=True,
)
class Barrier:
barrier_id = 0
@classmethod
def init(cls):
cls.barrier_id = 0
barrier_dir = os.path.join(os.environ["TEMP_DIR"], "barrier")
for f_name in os.listdir(barrier_dir):
os.unlink(os.path.join(barrier_dir, f_name))
@classmethod
def sync(cls, wait_for=None, timeout=10):
if wait_for is None:
wait_for = dist.get_world_size()
cls.barrier_id += 1
barrier_dir = os.path.join(os.environ["TEMP_DIR"], "barrier")
pid = str(os.getpid())
barrier_file = os.path.join(barrier_dir, pid)
with _lock():
with open(barrier_file, "w") as f:
f.write(str(cls.barrier_id))
start_time = time.time()
while True:
arrived = 0
with _lock():
for f_name in os.listdir(barrier_dir):
with open(os.path.join(barrier_dir, f_name), "r") as f:
data = f.read()
if int(data) >= cls.barrier_id:
arrived += 1
if arrived == wait_for:
break
if time.time() - start_time > timeout:
raise RuntimeError("barrier timeout")
time.sleep(0.1)
class TestDistBackend(MultiProcessTestCase):
@classmethod
def setUpClass(cls):
os.environ["MASTER_ADDR"] = str(MASTER_ADDR)
# Not setting MASTER_PORT and get a random free port
super().setUpClass()
def setUp(self):
super().setUp()
# initialize temp directories
initialize_temp_directories()
# initialize Barrier
Barrier.init()
# Skip return code checking for following tests as they are expected to
# crash a process due to NCCL_ASYNC_ERROR_HANDLING.
self.skip_return_code_checks = [self.test_ddp_has_finalized.__wrapped__]
def tearDown(self):
cleanup_temp_dir()
super().tearDown()
@property
def init_method(self):
return "{}{file_name}".format(FILE_SCHEMA, file_name=self.file_name)
@classmethod
def _run(cls, rank, test_name, file_name, pipe):
if BACKEND == "nccl" and not torch.cuda.is_available():
sys.exit(TEST_SKIPS["no_cuda"].exit_code)
self = cls(test_name)
self.rank = rank
self.file_name = file_name
if torch.cuda.is_available() and torch.cuda.device_count() < int(
self.world_size
):
sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code)
try:
pg_timeout_seconds = CUSTOM_PG_TIMEOUT.get(test_name, default_pg_timeout)
timeout = timedelta(seconds=pg_timeout_seconds)
dist.init_process_group(
init_method=self.init_method,
backend=BACKEND,
world_size=int(self.world_size),
rank=self.rank,
timeout=timeout,
)
except RuntimeError as e:
if "recompile" in e.args[0]:
sys.exit(TEST_SKIPS["backend_unavailable"].exit_code)
raise
# Execute barrier prior to running test to ensure that every process
# has finished initialization and that the following test
# immediately exiting due to a skip doesn't cause flakiness.
self._barrier()
self.run_test(test_name, pipe)
self._barrier()
dist.destroy_process_group()
sys.exit(0)
# Needed since MultiProcessTestCase assumes a world_size of 4, but we
# run these tests under other various world_sizes.
@property
def world_size(self):
return os.environ["WORLD_SIZE"]
class DistributedTest:
class _DistTestBase:
def _barrier(self, *args, **kwargs):
Barrier.sync(*args, **kwargs)
def _init_group_test(self, **kwargs):
group = [1, 2]
group_id = dist.new_group(group, **kwargs)
rank = dist.get_rank()
if rank not in group:
return ([], None, rank)
return (group, group_id, rank)
def _init_full_group_test(self, **kwargs):
group = list(range(0, dist.get_world_size()))
group_id = dist.new_group(**kwargs)
rank = dist.get_rank()
return (group, group_id, rank)
def _init_global_test(self):
group = list(range(0, dist.get_world_size()))
group_id = dist.group.WORLD
rank = dist.get_rank()
return (group, group_id, rank)
def _verify_buffers_equal(self, m1, m2):
# verify buffers across models
m1_buf_dict = dict(m1.module.named_buffers())
for name, buf in m2.module.named_buffers():
self.assertEqual(buf, m1_buf_dict[name])
# Verify buffers across ranks.
m1_buffers = list(m1.buffers())
m2_buffers = list(m2.buffers())
for (buf1, buf2) in zip(m1_buffers, m2_buffers):
gathered_bufs = [
torch.empty_like(buf1) for _ in range(dist.get_world_size())
]
dist.all_gather(gathered_bufs, buf1)
gathered_bufs_m2 = [
torch.empty_like(buf2) for _ in range(dist.get_world_size())
]
for b in gathered_bufs:
self.assertEqual(b, buf1)
dist.all_gather(gathered_bufs_m2, buf2)
for b in gathered_bufs_m2:
self.assertEqual(b, buf2)
def test_dump_DDP_relevant_env_vars(self):
with captured_output() as (out, _):
_dump_DDP_relevant_env_vars()
lines = out.getvalue().splitlines()
def format_line(var):
return "env:%s=%s" % (
var,
os.environ[var] if var in os.environ else "N/A",
)
# Check relevant env vars
vars = [
"MASTER_ADDR",
"MASTER_PORT",
"WORLD_SIZE",
"NCCL_TOPO_DUMP_FILE", # N/A
"NCCL_ASYNC_ERROR_HANDLING",
]
for var in vars:
line = format_line(var)
self.assertIn(line, lines)
# Check irrelevant env vars
vars = [
"xxx",
"yyy",
"zzz",
]
for var in vars:
line = format_line(var)
self.assertNotIn(line, lines)
# GET RANK
def test_get_rank(self):
test_dir = os.path.join(os.environ["TEMP_DIR"], "test_dir")
pid = str(os.getpid())
num_processes = dist.get_world_size()
with open(os.path.join(test_dir, pid), "w") as f:
f.write(str(dist.get_rank()))
self._barrier()
all_ranks = set()
for f_name in os.listdir(test_dir):
with open(os.path.join(test_dir, f_name), "r") as f:
all_ranks.add(int(f.read()))
self.assertEqual(len(all_ranks), num_processes)
self._barrier()
if dist.get_rank() == 0:
for f_name in os.listdir(test_dir):
os.unlink(os.path.join(test_dir, f_name))
self._barrier()
def test_get_backend(self):
if dist.get_world_size() > 2:
group = [1, 2]
else:
group = [0, 1]
group_id = dist.new_group(group)
backend_str = BACKEND.lower()
self.assertEqual(dist.get_backend(), backend_str)
if dist.get_rank() in group:
self.assertEqual(dist.get_backend(group_id), backend_str)
else:
with self.assertRaisesRegex(
RuntimeError, "Invalid process group specified"
):
dist.get_backend(group_id)
def test_Backend_enum_class(self):
# test parsing
backend = BACKEND.lower()
self.assertEqual(dist.Backend(BACKEND.upper()), backend)
self.assertEqual(dist.Backend(BACKEND), backend)
with self.assertRaises(ValueError):
dist.Backend(None)
with self.assertRaises(ValueError):
dist.Backend(3)
with self.assertRaises(ValueError):
dist.Backend(["gloo"])
# Test destroy
def test_destroy_group(self):
if dist.get_world_size() > 2:
group = [1, 2]
else:
group = [0, 1]
group_id = dist.new_group(group)
self._barrier()
dist.destroy_process_group(group_id)
# Test get rank and size of group
def test_get_rank_size_group(self):
if dist.get_world_size() > 2:
group = [1, 2]
else:
group = [0, 1]
group_id = dist.new_group(group)
if dist.get_rank() in group:
self.assertEqual(dist.get_world_size(group_id), 2)
self.assertTrue(dist.get_rank(group_id) in list(range(2)))
else:
self.assertEqual(dist.get_world_size(group_id), -1)
self.assertEqual(dist.get_rank(group_id), -1)
# Test destroy full groups
def test_destroy_full_group(self):
_, group_id, _ = self._init_full_group_test()
self._barrier()
dist.destroy_process_group(group_id)
# Test get rank and size of full group
def test_get_rank_size_full_group(self):
_, group_id, _ = self._init_full_group_test()
self.assertEqual(dist.get_world_size(group_id), dist.get_world_size())
self.assertEqual(dist.get_rank(group_id), dist.get_rank())
def _test_barrier_timeout(self, group_id, timeout):
local_rank = dist.get_rank(group_id)
# Only execute barrier on rank == 0, causing it to timeout
if local_rank == 0:
expected_time = time.time() + timeout.total_seconds()
# In debug mode, we execute a monitored_barrier before the
# collective, so assert on that.
if dist.get_debug_level() == dist.DebugLevel.DETAIL:
exception_ctx = self.assertRaisesRegex(
Exception, "failed to pass monitoredBarrier"
)
else:
exception_ctx = self.assertRaisesRegex(
Exception, " (Timed out|closed|timeout) "
)
with exception_ctx:
dist.barrier(group_id)
self.assertGreaterAlmostEqual(time.time(), expected_time, delta=0.1)
else:
pass
@skip_but_pass_in_sandcastle_if(
BACKEND != "gloo", "Only gloo backend supports timeouts"
)
@skip_but_pass_in_sandcastle_if(
not INIT_METHOD.startswith("file://"),
"Requires file:// initialization method. "
+ "Both tcp:// and env:// rely on the TCP store for which "
"reinitialization has proven racy.",
)
def test_barrier_timeout_global(self):
dist.destroy_process_group()
# Explicitly pass world size to the barrier because we've
# just destroyed any state in torch.distributed.
self._barrier(wait_for=int(os.environ["WORLD_SIZE"]))
# Reinitialize global process group
timeout = timedelta(seconds=1)
dist.init_process_group(
init_method=INIT_METHOD,
backend=BACKEND,
world_size=int(os.environ["WORLD_SIZE"]),
rank=self.rank,
timeout=timeout,
)
self._test_barrier_timeout(dist.group.WORLD, timeout)
@skip_if_small_worldsize
@skip_but_pass_in_sandcastle_if(
BACKEND != "gloo", "Only gloo backend supports timeouts"
)
def test_barrier_timeout_group(self):
timeout = timedelta(seconds=5)
_, group_id, _ = self._init_group_test(timeout=timeout)
if group_id is not None:
self._test_barrier_timeout(group_id, timeout)
@skip_but_pass_in_sandcastle_if(
BACKEND != "gloo", "Only gloo backend supports timeouts"
)
def test_barrier_timeout_full_group(self):
timeout = timedelta(seconds=1)
_, group_id, _ = self._init_full_group_test(timeout=timeout)
if group_id is not None:
self._test_barrier_timeout(group_id, timeout)
# This test helper can only be used when using the Gloo or NCCL backend
# **and** both the Gloo and NCCL backends are available.
# See the @skip annotations below.
def _test_group_override_backend(self, initializer):
if BACKEND == "gloo":
new_backend = "nccl"
elif BACKEND == "nccl":
new_backend = "gloo"
elif BACKEND in DistTestCases.backend_feature["plugin"]:
new_backend = "gloo"
group, group_id, rank = initializer(backend=new_backend)
if group_id is None:
return
if new_backend == "gloo":
self.assertTrue(isinstance(group_id, dist.ProcessGroupGloo))
if new_backend == "nccl":
self.assertTrue(isinstance(group_id, dist.ProcessGroupNCCL))
self.assertEqual(rank, group[dist.get_rank(group_id)])
self.assertEqual(len(group), dist.get_world_size(group_id))
# Pin device (so we avoid NCCL race conditions/deadlocks).
group_rank = dist.get_rank(group_id)
torch.cuda.set_device(group_rank)
# Run broadcast of CUDA tensor (so it works for both Gloo and NCCL).
tensor = _build_tensor(2, value=group_rank).cuda()
dist.broadcast(tensor, src=group[0], group=group_id)
self.assertEqual(_build_tensor(2, value=0), tensor.to("cpu"))
@require_backend_is_available(DistTestCases.backend_feature["gpu"])
@require_world_size(3)
@skip_if_lt_x_gpu(2)
def test_backend_group(self):
self._test_group_override_backend(self._init_group_test)
@require_backend_is_available(DistTestCases.backend_feature["gpu"])
@skip_if_lt_x_gpu(3)
def test_backend_full_group(self):
self._test_group_override_backend(self._init_full_group_test)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@require_world_size(4)
@skip_if_lt_x_gpu(2)
def test_new_subgroups(self):
subgroup_size = 2
cur_subgroup, subgroups = dist.new_subgroups(subgroup_size)
world_size = dist.get_world_size()
self.assertEqual(cur_subgroup.size(), subgroup_size)
self.assertEqual(len(subgroups), world_size / subgroup_size)
self.assertFalse(dist._rank_not_in_group(cur_subgroup))
for subgroup in subgroups:
dist.destroy_process_group(subgroup)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@skip_if_no_gpu
def test_new_subgroups_group_size_exceeds_world_size(self):
with self.assertRaisesRegex(ValueError, "must not exceed"):
dist.new_subgroups(100)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@require_world_size(4)
@skip_if_lt_x_gpu(4)
def test_new_subgroups_world_size_not_divisible_by_group_size(self):
with self.assertRaisesRegex(
ValueError, "The world size must be divisible by 'group_size'"
):
dist.new_subgroups(3)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@require_world_size(4)
@skip_if_lt_x_gpu(4)
def test_new_subgroups_by_enumeration(self):
group, group_id, rank = self._init_global_test()
rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND)
device_id = rank_to_GPU[rank][0]
cur_subgroup, subgroups = dist.new_subgroups_by_enumeration(
ranks_per_subgroup_list=[[0, 2], [1, 3]]
)
if device_id >= 4:
self.assertIsNone(cur_subgroup)
else:
self.assertEqual(cur_subgroup.size(), 2)
self.assertEqual(len(subgroups), 2)
if device_id == 0 or device_id == 2:
self.assertEqual(cur_subgroup, subgroups[0])
else:
self.assertEqual(cur_subgroup, subgroups[1])
for subgroup in subgroups:
dist.destroy_process_group(subgroup)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@require_world_size(4)
@skip_if_lt_x_gpu(4)
def test_new_subgroups_by_enumeration_input_rank_exceeds_world_size(self):
group, group_id, rank = self._init_global_test()
rank_to_GPU = init_multigpu_helper(dist.get_world_size(), BACKEND)
device_id = rank_to_GPU[rank][0]
world_size = get_world_size(group_id)
with self.assertRaisesRegex(
RuntimeError,
"The new group's rank should be within the the world_size set by init_process_group",
):
dist.new_subgroups_by_enumeration(
ranks_per_subgroup_list=[[0, 1], [world_size, 2]]
)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@skip_if_no_gpu
def test_new_subgroups_by_enumeration_negative_input_rank(self):
group, group_id, rank = self._init_global_test()
with self.assertRaisesRegex(
RuntimeError,
"The new group's rank should be within the the world_size set by init_process_group",
):
dist.new_subgroups_by_enumeration(
ranks_per_subgroup_list=[[-1, -2], [-3, -4]]
)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)
@require_world_size(4)
@skip_if_lt_x_gpu(4)
def test_new_subgroups_overlap_not_allowed(self):
with self.assertRaisesRegex(
ValueError, "Rank 1 has appeared in both subgroup"
):
dist.new_subgroups_by_enumeration(
ranks_per_subgroup_list=[[0], [1, 2], [1, 3]]
)
@skip_but_pass_in_sandcastle_if(
BACKEND not in DistTestCases.backend_feature["subgroup"],
f"The {BACKEND} backend does not support creating subgroups on CUDA devices",
)