forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_c10d_nccl.py
5152 lines (4527 loc) · 201 KB
/
test_c10d_nccl.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
# Owner(s): ["oncall: distributed"]
import copy
import json
import os
import pickle
import random
import re
import signal
import sys
import tempfile
import threading
import time
import warnings
from contextlib import contextmanager
from datetime import datetime, timedelta
from enum import auto, Enum
from itertools import chain, product
from unittest import mock, SkipTest
import torch
import torch.distributed as c10d
import torch.distributed._functional_collectives as _functional_collectives
if not c10d.is_available() or not c10d.is_nccl_available():
print("c10d NCCL not available, skipping tests", file=sys.stderr)
sys.exit(0)
from typing import Dict, List
import test_c10d_common
from test_c10d_common import ConvNet, DoubleGpuNet, gpus_for_rank, ModuleForDdpCommHook
import torch.distributed as dist
import torch.distributed.algorithms.ddp_comm_hooks.default_hooks as default
import torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook as powerSGD
import torch.nn.functional as F
import torch.testing._internal.common_utils as common
from torch import nn
from torch._C._distributed_c10d import OpType, WorkResult
from torch.nn.parallel import DistributedDataParallel
from torch.testing._internal.common_cuda import TEST_MULTIGPU
from torch.testing._internal.common_distributed import (
get_timeout,
init_multigpu_helper,
MultiProcessTestCase,
requires_gloo,
requires_multicast_support,
requires_nccl,
requires_nccl_version,
skip_if_lt_x_gpu,
skip_if_rocm_multiprocess,
sm_is_or_higher_than,
TEST_SKIPS,
with_dist_debug_levels,
with_nccl_blocking_wait,
)
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
parametrize,
retry_on_connect_failures,
run_tests,
skip_but_pass_in_sandcastle,
skip_but_pass_in_sandcastle_if,
TEST_CUDA,
TEST_WITH_DEV_DBG_ASAN,
TEST_WITH_ROCM,
TestCase,
)
from torch.utils.cpp_extension import load_inline
if TEST_WITH_DEV_DBG_ASAN:
print(
"Skip ASAN as torch + multiprocessing spawn have known issues", file=sys.stderr
)
sys.exit(0)
# bfloat16 is only supported by CUDA 11+
BFLOAT16_AVAILABLE = torch.cuda.is_available() and (
(torch.version.cuda is not None and int(torch.version.cuda.split(".")[0]) >= 11)
or torch.version.hip is not None
)
class RendezvousEnvTest(TestCase):
@retry_on_connect_failures
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_CUDA, "No GPUs available, skipping test")
def test_common_errors(self):
vars = {
"WORLD_SIZE": "1",
"RANK": "0",
"MASTER_ADDR": "127.0.0.1",
"MASTER_PORT": str(common.find_free_port()),
}
class Env:
def __init__(self, vars):
self.env_patcher = mock.patch.dict(os.environ, vars, clear=True)
def __enter__(self):
self.env_patcher.start()
def __exit__(self, type, value, traceback):
self.env_patcher.stop()
def without(d, key):
d = d.copy()
d.pop(key)
return d
def withouts(d, keys):
d = d.copy()
for key in keys:
d.pop(key)
return d
with Env(without(vars, "WORLD_SIZE")):
self.assertEqual(None, os.environ.get("WORLD_SIZE"))
with self.assertRaisesRegex(ValueError, "WORLD_SIZE expected"):
gen = c10d.rendezvous("env://")
next(gen)
c10d.init_process_group(backend="nccl", world_size=1)
self.assertEqual(c10d.get_rank(), 0)
self.assertEqual(c10d.get_world_size(), 1)
c10d.destroy_process_group()
with Env(without(vars, "RANK")):
self.assertEqual(None, os.environ.get("RANK"))
with self.assertRaisesRegex(ValueError, "RANK expected"):
gen = c10d.rendezvous("env://")
next(gen)
c10d.init_process_group(backend="nccl", rank=0)
self.assertEqual(c10d.get_rank(), 0)
self.assertEqual(c10d.get_world_size(), 1)
c10d.destroy_process_group()
with Env(withouts(vars, ["RANK", "WORLD_SIZE"])):
self.assertEqual(None, os.environ.get("RANK"))
self.assertEqual(None, os.environ.get("WORLD_SIZE"))
c10d.init_process_group(backend="nccl", rank=0, world_size=1)
self.assertEqual(c10d.get_rank(), 0)
self.assertEqual(c10d.get_world_size(), 1)
c10d.destroy_process_group()
with Env(vars):
c10d.init_process_group(backend="nccl")
self.assertEqual(c10d.get_rank(), 0)
self.assertEqual(c10d.get_world_size(), 1)
c10d.destroy_process_group()
with Env(without(vars, "MASTER_ADDR")):
self.assertEqual(None, os.environ.get("MASTER_ADDR"))
with self.assertRaisesRegex(ValueError, "MASTER_ADDR expected"):
gen = c10d.rendezvous("env://")
next(gen)
with Env(without(vars, "MASTER_PORT")):
self.assertEqual(None, os.environ.get("MASTER_PORT"))
with self.assertRaisesRegex(ValueError, "MASTER_PORT expected"):
gen = c10d.rendezvous("env://")
next(gen)
with Env(without(vars, "WORLD_SIZE")):
self.assertEqual(None, os.environ.get("WORLD_SIZE"))
gen = c10d.rendezvous(f"env://?world_size={1}")
_, _, size = next(gen)
self.assertEqual(size, 1)
with Env(without(vars, "RANK")):
self.assertEqual(None, os.environ.get("RANK"))
gen = c10d.rendezvous(f"env://?rank={0}")
_, rank, _ = next(gen)
self.assertEqual(rank, 0)
with Env(withouts(vars, ["RANK", "WORLD_SIZE"])):
self.assertEqual(None, os.environ.get("RANK"))
self.assertEqual(None, os.environ.get("WORLD_SIZE"))
gen = c10d.rendezvous(f"env://?rank={0}&world_size={1}")
_, rank, size = next(gen)
self.assertEqual(rank, 0)
self.assertEqual(size, 1)
class TimeoutTest(test_c10d_common.AbstractTimeoutTest, TestCase):
@requires_nccl()
@retry_on_connect_failures
@skip_but_pass_in_sandcastle_if(not TEST_CUDA, "No GPUs available, skipping test")
def test_default_store_timeout_nccl(self):
self._test_default_store_timeout("nccl")
class ProcessGroupNCCLNoGPUTest(TestCase):
MAIN_PROCESS_RANK = 0
def setUp(self):
self.rank = self.MAIN_PROCESS_RANK
self.world_size = 1
self.file = tempfile.NamedTemporaryFile(delete=False)
def tearDown(self):
pass
@requires_nccl()
@skip_but_pass_in_sandcastle_if(TEST_CUDA, "GPUs are available, skipping test")
def test_init_no_gpus(self):
store = c10d.FileStore(self.file.name, self.world_size)
with self.assertRaisesRegex(
ValueError, "ProcessGroupNCCL is only supported with GPUs, no GPUs found!"
):
c10d.ProcessGroupNCCL(store, self.rank, self.world_size)
class ProcessGroupNCCLInitTest(MultiProcessTestCase):
device_type = "cuda"
def setUp(self):
super().setUp()
self._spawn_processes()
def tearDown(self):
super().tearDown()
try:
os.remove(self.file_name)
except OSError:
pass
@property
def world_size(self):
dm = torch.get_device_module(self.device_type)
return dm.device_count()
@property
def device(self):
return torch.device(self.device_type, self.rank % self.world_size)
# A helper with the must-needed init args for test infra.
# kwargs can be filled in by individual init tests.
def _init_process_group(self, **kwargs):
store = c10d.FileStore(self.file_name, self.world_size)
c10d.init_process_group(
rank=self.rank,
world_size=self.world_size,
store=store,
**kwargs,
)
@requires_nccl()
@skip_if_lt_x_gpu(1)
def test_init_wo_backend_str(self):
self._init_process_group(device_id=self.device)
x = torch.empty(1, device=self.device)
c10d.all_reduce(x)
class ProcessGroupNCCLGroupTest(MultiProcessTestCase):
def _create_process_group_nccl(self, store, opts, device_id=None):
# create nccl processgroup with opts
c10d.init_process_group(
"nccl",
world_size=self.world_size,
rank=self.rank,
store=store,
pg_options=opts,
device_id=device_id,
)
pg = c10d.distributed_c10d._get_default_group()
return pg
def opts(self, high_priority_stream=False):
opts = c10d.ProcessGroupNCCL.Options()
opts.is_high_priority_stream = high_priority_stream
return opts
def setUp(self):
super().setUp()
# Need to skip return code checking for these tests since the child
# processes don't exit cleanly in some cuda versions
self.skip_return_code_checks = [
self.test_nan_assert_float16.__wrapped__,
self.test_nan_assert_float32.__wrapped__,
self.test_nan_assert_float64.__wrapped__,
self.test_nan_assert_bfloat16.__wrapped__,
self.test_nan_assert_float8_e4m3fn.__wrapped__,
self.test_nan_assert_float8_e5m2.__wrapped__,
]
# TORCH_NCCL_BLOCKING_WAIT overrides TORCH_NCCL_ASYNC_ERROR_HANDLING hence tests
# that use TORCH_NCCL_BLOCKING_WAIT will test it as expected.
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "1"
# self.num_gpus = torch.cuda.device_count()
self._spawn_processes()
def tearDown(self):
super().tearDown()
try:
os.remove(self.file_name)
except OSError:
pass
@property
def world_size(self):
return 2
@property
def rank_to_GPU(self):
# return rank to GPU map
return init_multigpu_helper(self.world_size, "nccl")
@property
def destroy_pg_upon_exit(self) -> bool:
# This TestCase focuses on creation, destroy and abort of PG's. So it
# does not need auto-destroy upon exit.
return False
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 1 GPU")
@skip_if_lt_x_gpu(1)
def test_nccl_dist_backend_error(self):
store = c10d.FileStore(self.file_name, self.world_size)
self._create_process_group_nccl(store, self.opts())
# Both rank 0 and 1 will use the same CUDA device resulting in ncclInvalidUsage
with self.assertRaises(dist.DistBackendError) as cm:
dist.broadcast(torch.tensor([1, 2, 3]).cuda(), 0)
self.assertTrue(isinstance(cm.exception, dist.DistError))
self.assertIsInstance(cm.exception, RuntimeError)
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
def test_abort_pg(self):
# Disable ASYNC_ERROR_HANDLING for this test to ensure we can programmatically
# abort the process group.
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
store = c10d.FileStore(self.file_name, self.world_size)
self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
t = torch.rand(10, 10, device=device)
# First allreduce to initialize state.
dist.all_reduce(t)
def abortpg():
c10d.distributed_c10d._get_default_group()._get_backend(
torch.device(device)
).abort()
# Initialize DDP to ensure "destroy_process_group" will not call
# ProcessGroupNCCL destructor since DDP holds a reference to process group.
# Run a single iteration of DDP to initialize state.
model = DistributedDataParallel(
torch.nn.Linear(10, 10).to(device), device_ids=[device]
)
model(t).sum().backward()
# Now simulate collective getting stuck and abort gets us unstuck
if self.rank == 0:
dist.all_reduce(t)
# Schedule thread before we get stuck to abort pg.
thread = threading.Thread(target=abortpg)
thread.start()
# We would get stuck here due to d2h if we didn't abort.
t_cpu = t.cpu()
thread.join()
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
@parametrize("eager_init", [True, False])
def test_close_pg(self, eager_init: bool):
# Disable ASYNC_ERROR_HANDLING for this test to ensure we can programmatically
# abort the process group.
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device(f"cuda:{self.rank % torch.cuda.device_count()}")
c10d.init_process_group(
"nccl",
world_size=self.world_size,
rank=self.rank,
store=store,
device_id=device if eager_init else None,
)
t = torch.rand(10, 10, device=device)
# First allreduce to initialize state.
dist.all_reduce(t)
# Destroy pg and validate pg is no longer valid
dist.destroy_process_group()
with self.assertRaises(ValueError):
dist.all_reduce(t)
@requires_nccl()
@skip_if_rocm_multiprocess
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
def test_restart_pg(self):
# Note: restart test passes steadily only for blocking mode for now.
# TODO: expand this test to non-blocking mode
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device(f"cuda:{self.rank % torch.cuda.device_count()}")
# initialize pg for the first time
c10d.init_process_group(
"nccl",
world_size=self.world_size,
rank=self.rank,
store=store,
)
t0 = torch.rand(10, 10, device=device)
# First allreduce to lazy initialize default pg
dist.all_reduce(t0)
torch.cuda.synchronize()
# Destroy pg
dist.destroy_process_group()
# we need a new Store for the new PG, achieving it by adding prefix
new_store = c10d.PrefixStore("2nd", store)
# re-initialize pg
c10d.init_process_group(
"nccl",
world_size=self.world_size,
rank=self.rank,
store=new_store,
)
t1 = torch.rand(5, 5, device=device)
dist.all_reduce(t1)
torch.cuda.synchronize()
dist.destroy_process_group()
# validate default pg is no longer valid
with self.assertRaises(ValueError):
dist.all_reduce(t1)
CUDA_12_AND_ABOVE = torch.cuda.is_available() and (
torch.version.cuda is not None and int(torch.version.cuda.split(".")[0]) >= 12
)
@requires_nccl()
@skip_but_pass_in_sandcastle_if(
not (TEST_MULTIGPU and CUDA_12_AND_ABOVE),
"NCCL test requires 2+ GPUs and Device side assert could cause unexpected errors in lower versions of CUDA",
)
@parametrize(
"type",
[
torch.float16,
torch.float32,
torch.float64,
torch.bfloat16,
torch.float8_e4m3fn,
torch.float8_e5m2,
],
)
@skip_if_rocm_multiprocess
def test_nan_assert(self, type):
# Expecting a device-side error when NaN is detected
os.environ["TORCH_NCCL_NAN_CHECK"] = "1"
store = c10d.FileStore(self.file_name, self.world_size)
pg = self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
# Cover different buffer sizes
if type == torch.float64:
size = (1024,) # 1K elements
elif type == torch.float32:
size = (1024, 1024) # 1M elements
elif type == torch.float16:
size = (1024, 1024, 1024) # 1G elements
else:
size = (1,) # 1 element
# Note: currently we cannot fill values into a FP8 tensor, thus we
# create the NaN tensor in float32 type and cast it to FP8
if type == torch.float8_e4m3fn or type == torch.float8_e5m2:
init_type = torch.float32
else:
init_type = type
nan_tensor = torch.zeros(*size, dtype=init_type, device=device)
# randomly pick an nan element
index = tuple([random.randrange(size[i]) for i in range(len(size))])
nan_tensor[index] = float("nan")
if init_type != type:
# Now cast to the targeted dtype
nan_tensor = nan_tensor.to(type)
output = torch.empty(self.world_size, *size, dtype=type, device=device)
with self.assertRaises(RuntimeError):
# Note: using all-gather here bc FP8 types do not support reduce ops
# at the moment
pg._allgather_base(output, nan_tensor)
dist.destroy_process_group()
# reset env
os.environ["TORCH_NCCL_NAN_CHECK"] = "0"
@requires_nccl()
@skip_if_lt_x_gpu(2)
def test_nan_rank_filter(self):
# Putting NaN at recv buffer, program should not fail as NaN checker
# should not check on receive buffer
os.environ["TORCH_NCCL_NAN_CHECK"] = "1"
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device("cuda:%d" % self.rank)
c10d.init_process_group(
backend="nccl", store=store, rank=self.rank, world_size=self.world_size
)
t = torch.ones(3, 4, dtype=torch.bfloat16, device=device)
if self.rank != 0:
# Putting NaN at recv buffer
t[1, 1] = float("nan")
# Against broadcast
c10d.broadcast(t, 0)
# Against P2P
if self.rank == 0:
c10d.send(t, 1)
elif self.rank == 1:
c10d.recv(t, 0)
c10d.destroy_process_group()
# reset env
os.environ["TORCH_NCCL_NAN_CHECK"] = "0"
@requires_nccl()
@skip_if_lt_x_gpu(2)
def test_nan_check(self):
# Not expecting an error, NaN check should not make legit code fail
device = torch.device("cuda:%d" % self.rank)
if not sm_is_or_higher_than(device, 8, 0):
self.skipTest("bf16 requires sm >= 8.0")
os.environ["TORCH_NCCL_NAN_CHECK"] = "1"
store = c10d.FileStore(self.file_name, self.world_size)
c10d.init_process_group(
backend="nccl", store=store, rank=self.rank, world_size=self.world_size
)
x = torch.ones((10,), dtype=torch.bfloat16, device=device) * self.rank
t = torch.ones(3, 4, dtype=torch.bfloat16, device=device)
c10d.broadcast(x, src=0)
c10d.all_reduce(t)
c10d.barrier()
c10d.destroy_process_group()
# reset env
os.environ["TORCH_NCCL_NAN_CHECK"] = "0"
def _helper_test_extra_cuda_context_by_nvml(self):
"""
A helper for `test_extra_cuda_context`, if pynvml is avaiable.
pynvml provides python bindings for NVIDIA NVML functionalities.
Here we are interested in: nvmlDeviceGetComputeRunningProcesses
"""
import pynvml
pynvml.nvmlInit()
device = torch.device("cuda:%d" % self.rank)
x = torch.empty((1,), device=device)
work = c10d.all_reduce(x, async_op=True)
# Wait for non-0 ranks to garbage collect Work -- this is the latest
# point where extra CUDA context can be created
if self.rank == 0:
time.sleep(5)
del work
handle = pynvml.nvmlDeviceGetHandleByIndex(self.rank)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
nprocs = len(processes)
# A barrier for non-0 ranks
c10d.all_reduce(x)
torch.cuda.synchronize(device)
c10d.destroy_process_group()
self.assertLessEqual(
nprocs,
1,
f"Found {nprocs} processes creating contexts on {device}, expecting 1 at most",
)
def _helper_test_extra_cuda_context_by_memory(self):
"""
A helper for `test_extra_cuda_context`, if pynvml is NOT avaiable.
If extra context is created, it would manifest into device 0's memory usage.
"""
device = torch.device("cuda:%d" % self.rank)
x = torch.empty((1,), device=device)
# Rank 0 takes a snapshot before collective -- this snapshot should have
# included rank 0's own context.
if self.rank == 0:
free, total = torch.cuda.mem_get_info(device)
used_before = float(total - free)
work = c10d.all_reduce(x, async_op=True)
# Wait for non-0 ranks to garbage collect Work -- this is the latest
# point where extra CUDA context can be created
if self.rank == 0:
time.sleep(5)
free, total = torch.cuda.mem_get_info(device)
used_after = float(total - free)
del work
# A barrier for non-0 ranks
c10d.all_reduce(x)
torch.cuda.synchronize(device)
c10d.destroy_process_group()
if self.rank == 0:
# If non-0 rank creates a context on device 0, this assert would
# fail because one context takes about 1 GB -- much more than the
# tensor size created in this test.
self.assertTrue(
used_after < used_before * 1.5,
f"{device} used {used_after} bytes after collective, "
f"50% more than the status before ({used_before} bytes). "
f"Extra CUDA context may have been created.",
)
@requires_nccl()
@skip_if_lt_x_gpu(2)
def test_extra_cuda_context(self):
# Check if non-0 ranks would create extra CUDA context on device 0
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device("cuda:%d" % self.rank)
c10d.init_process_group(
backend="nccl",
store=store,
rank=self.rank,
world_size=self.world_size,
device_id=device,
)
try:
self._helper_test_extra_cuda_context_by_nvml()
except ModuleNotFoundError:
self._helper_test_extra_cuda_context_by_memory()
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
def test_destruct_before_terminate_pg(self):
# Disable ASYNC_ERROR_HANDLING for this test to ensure we can programmatically
# abort the process group.
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
store = c10d.FileStore(self.file_name, self.world_size)
pg = self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
t = torch.rand(10, 10, device=device)
# First allreduce to initialize state.
pg.allreduce(t)
# force destruction before terminating comms, destructor would terminate comms
del pg
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
def test_abort_in_destroy_pg(self):
# Disable ASYNC_ERROR_HANDLING for this test to ensure we can programmatically
# abort the process group.
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
store = c10d.FileStore(self.file_name, self.world_size)
pg = self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
t = torch.rand(10, 10, device=device)
# First allreduce to initialize state.
pg.allreduce(t)
# Destroy pg and validate pg is NOT in working condition since
# we have shutdown comms
dist.destroy_process_group()
with self.assertRaises(dist.DistBackendError):
pg.allreduce([t])
@requires_nccl()
@skip_but_pass_in_sandcastle_if(
torch.cuda.device_count() < 2, "NCCL test requires 2+ GPUs"
)
def test_close_multi_pg_unordered(self):
store = c10d.FileStore(self.file_name, self.world_size)
pg = self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
t = torch.rand(10, 10, device=device)
# First allreduce to initialize default PG's communicator.
pg.allreduce(t).wait()
new_pg1 = c10d.new_group([0, 1])
new_pg2 = c10d.new_group([0, 1])
if self.rank == 0 or self.rank == 1:
t1 = torch.rand(10, 10, device=device)
t2 = torch.rand(10, 10, device=device)
new_pg1.allreduce(t1).wait()
new_pg2.allreduce(t2).wait()
if self.rank == 0:
dist.destroy_process_group(new_pg2)
# force destruction of pg2 first
del new_pg2
dist.destroy_process_group(new_pg1)
del new_pg1
if self.rank == 1:
c10d.destroy_process_group(new_pg1)
# force destruction of pg1 first
del new_pg1
dist.destroy_process_group(new_pg2)
del new_pg2
dist.destroy_process_group()
@requires_nccl()
@skip_but_pass_in_sandcastle_if(
torch.cuda.device_count() < 2, "NCCL test requires 2+ GPUs"
)
def test_abort_in_destroy_multi_pgs(self):
store = c10d.FileStore(self.file_name, self.world_size)
pg = self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
t = torch.rand(10, 10, device=device)
# First allreduce to initialize default PG's communicator.
pg.allreduce(t).wait()
new_pg1 = c10d.new_group([0, 1])
new_pg2 = c10d.new_group([0, 1])
t1 = torch.rand(10, 10, device=device)
t2 = torch.rand(10, 10, device=device)
new_pg1.allreduce(t1).wait()
new_pg2.allreduce(t2).wait()
backend = pg._get_backend(torch.device(device))
# default PG's backend should have a split count of 0 because
# it's not eager initialized
self.assertEqual(backend.comm_split_count(), 0)
# shutdown all NCCL PGs in one shot
dist.destroy_process_group()
@requires_nccl()
@skip_but_pass_in_sandcastle_if(
torch.cuda.device_count() < 2, "NCCL test requires 2+ GPUs"
)
def test_abort_in_destroy_mixed_empty_pgs(self):
store = c10d.FileStore(self.file_name, self.world_size)
pg = self._create_process_group_nccl(store, self.opts())
device = self.rank_to_GPU[self.rank][0]
t = torch.rand(10, 10, device=device)
# First allreduce to initialize default PG's communicator.
pg.allreduce(t).wait()
# PG1 is an PG without comms initialized, since we don't call collective on it
new_pg1 = c10d.new_group([0, 1])
new_pg2 = c10d.new_group([0, 1])
t2 = torch.rand(10, 10, device=device)
new_pg2.allreduce(t2).wait()
backend = pg._get_backend(torch.device(device))
# default PG's backend should have a split count of 0
self.assertEqual(backend.comm_split_count(), 0)
# shutdown all NCCL PGs in one shot
dist.destroy_process_group()
@requires_nccl()
@skip_but_pass_in_sandcastle_if(
torch.cuda.device_count() < 2, "NCCL test requires 2+ GPUs"
)
def test_file_store_check(self):
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
os.environ["TORCH_NCCL_ENABLE_MONITORING"] = "0"
# FileStore check() would be executed
os.environ["TORCH_NCCL_DUMP_ON_TIMEOUT"] = "1"
os.environ["TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC"] = "0"
# self.file_name is created using "delete=False"
# e.g., self.file_name = tempfile.NamedTemporaryFile(delete=False).name
store = dist.FileStore(self.file_name, self.world_size)
dist.init_process_group(
backend="nccl", rank=self.rank, world_size=self.world_size, store=store
)
pg = dist.distributed_c10d._get_default_group()
self.assertEqual(pg.rank(), self.rank)
self.assertEqual(pg.size(), self.world_size)
# give enough time for check() to be executed multiple times
time.sleep(2)
dist.destroy_process_group()
def _check_nccl_timeout(self, expected_timeout):
pg = dist.distributed_c10d._get_default_group()
options = pg._get_backend(torch.device(f"cuda:{self.rank}")).options
self.assertEqual(options._timeout, expected_timeout)
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_CUDA, "No GPUs available, skipping test")
def test_init_process_group_nccl_timeout(self):
# nccl is handled 'specially' inside init_process_group and its options class is different from the options
# used by the other PG's. There are specific edge cases for nccl that need to be tested.
store = c10d.FileStore(self.file_name, self.world_size)
base_opts = dict(
backend="nccl", store=store, rank=self.rank, world_size=self.world_size
)
# test the default value coming from the `init_process_group` kwarg default
dist.init_process_group(**base_opts)
self._check_nccl_timeout(torch.distributed.constants.default_pg_nccl_timeout)
dist.destroy_process_group()
# test that `kwarg` timeout takes effect
new_timeout = timedelta(seconds=123)
dist.init_process_group(**base_opts, timeout=new_timeout)
self._check_nccl_timeout(new_timeout)
dist.destroy_process_group()
# test that timeout value provided via `pg_options` kwarg is ignored and issues warning,
# 'timeout' kwarg (or its kwdefault) taking precedence
opts = dist.ProcessGroupNCCL.Options()
opts._timeout = timedelta(seconds=123)
with warnings.catch_warnings(record=True) as w:
dist.init_process_group(**base_opts, pg_options=opts)
# TODO(whc) i verified that we are indeed emitting this warning, and i can't figure out why i can't catch it.
# self.assertEqual(len(w), 1)
# self.assertTrue("pg_options._timeout was specified" in str(w[-1].message))
self._check_nccl_timeout(torch.distributed.constants.default_pg_nccl_timeout)
dist.destroy_process_group()
# test that timeout value provided via `pg_options` kwarg is ignored and issues warning,
# 'timeout' kwarg taking precedence
opts = dist.ProcessGroupNCCL.Options()
opts._timeout = timedelta(seconds=123)
dist.init_process_group(
**base_opts, pg_options=opts, timeout=timedelta(seconds=1240)
)
self._check_nccl_timeout(timedelta(seconds=1240))
dist.destroy_process_group()
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
@parametrize("backend", [None, "nccl"])
def test_set_nccl_pg_timeout(self, backend):
store = c10d.FileStore(self.file_name, self.world_size)
opts = dict(
backend=backend,
store=store,
rank=self.rank,
world_size=self.world_size,
timeout=timedelta(seconds=123),
)
dist.init_process_group(**opts)
pg = dist.distributed_c10d._get_default_group()
pg.allreduce(torch.rand(10).cuda(self.rank))
self._check_nccl_timeout(timedelta(seconds=123))
pg._get_backend(torch.device(f"cuda:{self.rank}"))._set_default_timeout(
timedelta(seconds=23)
)
self._check_nccl_timeout(timedelta(seconds=23))
pg.allreduce(torch.rand(10).cuda(self.rank))
c10d.distributed_c10d._set_pg_timeout(timedelta(seconds=252), pg)
self._check_nccl_timeout(timedelta(seconds=252))
@requires_nccl()
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
@parametrize("backend", [None, "nccl"])
def test_extend_nccl_pg_timeout(self, backend):
torch.cuda.set_device(self.rank)
store = c10d.FileStore(self.file_name, self.world_size)
opts = dict(
backend=backend,
store=store,
rank=self.rank,
world_size=self.world_size,
timeout=timedelta(seconds=123),
)
dist.init_process_group(**opts)
pg = dist.distributed_c10d._get_default_group()
bankend = pg._get_backend(torch.device(f"cuda:{self.rank}"))
w = pg.allreduce(torch.rand(10).cuda(self.rank))
self.assertTrue(bankend._verify_work_timeout(w, timedelta(seconds=123)))
w.wait()
bankend._set_default_timeout(timedelta(seconds=3))
if self.rank == 0:
# Ideally we want to sleep for a very long time, but this is not
# feasible in unit test. So this is only a very tiny case.
time.sleep(5)
pg.allreduce(torch.rand(10).cuda(self.rank))
time.sleep(5)
pg.allreduce(torch.rand(5).cuda(self.rank))
w = pg.allreduce(torch.rand(10).cuda(self.rank))
self.assertTrue(bankend._verify_work_timeout(w, timedelta(seconds=3)))
w.wait()
else:
dist.distributed_c10d._add_ephemeral_timeout_for_all_pgs(
timedelta(seconds=10)
)
w1 = pg.allreduce(torch.rand(10).cuda(self.rank))
w2 = pg.allreduce(torch.rand(5).cuda(self.rank))
self.assertTrue(bankend._verify_work_timeout(w1, timedelta(seconds=13)))
self.assertTrue(bankend._verify_work_timeout(w2, timedelta(seconds=13)))
w1.wait()
dist.distributed_c10d._add_ephemeral_timeout_for_all_pgs(
timedelta(seconds=5)
)
# Since we are not block wait so use a sync here to leave enough time
# for watchdog to reset first timeout extension.
torch.cuda.synchronize(torch.device(f"cuda:{self.rank}"))
w = pg.allreduce(torch.rand(10).cuda(self.rank))
self.assertTrue(bankend._verify_work_timeout(w, timedelta(seconds=8)))
w.wait()
@requires_nccl_version((2, 18), "Need NCCL 2.18+ for ncclCommSplit")
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
@parametrize("eager_init", [True, False])
def test_new_group(self, eager_init: bool):
# Test the optimization of new groups that contain all world
# ranks use the "transparent" `ncclCommSplit` optimization.
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device(f"cuda:{self.rank % torch.cuda.device_count()}")
c10d.init_process_group(
"nccl",
world_size=self.world_size,
rank=self.rank,
store=store,
device_id=device if eager_init else None,
)
ng = c10d.new_group()
tensor = torch.tensor([self.rank], device=device)
dist.broadcast(tensor, 0)
dist.broadcast(tensor, 0, group=ng)
dist.destroy_process_group()
@requires_nccl_version((2, 18), "Need NCCL 2.18+ for ncclCommSplit")
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
@skip_but_pass_in_sandcastle_if(
torch.cuda.nccl.version()[-1] == "x", "NCCL test not for NCCLX"
)
def test_comm_split_subgroup(self):
# Test `ncclCommSplit` for smaller subgroups of the world when
# we've passed a specific device_id to init_process_group.
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device(f"cuda:{self.rank}")
pg = self._create_process_group_nccl(store, self.opts(), device_id=device)
backend = pg._get_backend(torch.device(device))
tensor = torch.full((1,), self.rank).cuda(device)
original_tensor = tensor.clone()
ng = c10d.new_group([0])
# comm split happens eagerly since device_id is passed to init_process_group.
self.assertEqual(backend.comm_split_count(), 1)
if self.rank == 0:
dist.broadcast(tensor, 0, group=ng)
# no additional comm split happens after a collective.
self.assertEqual(backend.comm_split_count(), 1)
self.assertEqual(tensor, original_tensor)
dist.destroy_process_group()
@requires_nccl_version((2, 18), "Need NCCL 2.18+ for ncclCommSplit")
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
def test_comm_eager_init_subgroup(self):
# Test `ncclCommSplit` for smaller subgroups of the world when
# we've passed a specific device_id to init_process_group.
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device(f"cuda:{self.rank}")
# default PG comm is not initialized yet
pg = self._create_process_group_nccl(store, self.opts())
backend = pg._get_backend(torch.device(device))
self.assertEqual(backend._is_initialized(), False)
# create a subgroup eagerly
new_group = c10d.new_group([0, 1], device_id=device)
tensor = torch.full((1,), self.rank).cuda(device)
dist.broadcast(tensor, 0, group=new_group)
# the default group should stay lazy
self.assertEqual(backend._is_initialized(), False)
torch.cuda.synchronize()
dist.destroy_process_group()
@requires_nccl_version((2, 18), "Need NCCL 2.18+ for ncclCommSplit")
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "NCCL test requires 2+ GPUs")
def test_comm_split_group(self):
# Test `ncclCommSplit` for smaller subgroups of the world when
# we've passed a specific device_id to init_process_group.
store = c10d.FileStore(self.file_name, self.world_size)
device = torch.device(f"cuda:{self.rank}")
pg = self._create_process_group_nccl(store, self.opts(), device_id=device)
backend = pg._get_backend(torch.device(device))
tensor = torch.full((1,), self.rank).cuda(device)
# Create subgroup between ranks 0, 1
subg_ranks = [0, 1]
ng1 = c10d.split_group(pg, [subg_ranks])
backend1 = ng1._get_backend(torch.device(device))
# check basic options are the same between parent and child
self.assertEqual(backend.options._timeout, backend1.options._timeout)
self.assertEqual(
backend.options.is_high_priority_stream,
backend1.options.is_high_priority_stream,
)
self.assertEqual(ng1.group_desc, "default_pg:split:0")
# comm split happens eagerly since device_id is passed to init_process_group.
self.assertEqual(backend.comm_split_count(), 1)
# dist.get_process_group_ranks returns the global ranks in the subgroup.
self.assertEqual(
dist.get_process_group_ranks(ng1),
subg_ranks if self.rank in subg_ranks else [],
)