forked from lanchongyizu/ngc-mxnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
horovod.patch
1718 lines (1648 loc) · 67.9 KB
/
horovod.patch
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
diff --git a/horovod/common/batched_memcpy.cu b/horovod/common/batched_memcpy.cu
new file mode 100644
index 0000000..3d1daa0
--- /dev/null
+++ b/horovod/common/batched_memcpy.cu
@@ -0,0 +1,185 @@
+// Copyright (C) 2018 NVIDIA CORPORATION. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// =============================================================================
+
+#define TO_NEXT_MULT_P2(x,p) (((x)+((p)-1)) & ~(p-1))
+
+__host__ __device__ ulonglong2 operator<<(ulonglong2 a, int l) {
+ ulonglong2 b;
+ if (l > 64) {
+ b = make_ulonglong2(0ull, a.x << (l-64));
+ } else {
+ b = make_ulonglong2(a.x << l, (a.y << l) | (a.x >> (8*sizeof(a.x)-l)));
+ }
+ return b;
+}
+
+__host__ __device__ ulonglong2 operator>>(ulonglong2 a, int l) {
+ ulonglong2 b;
+ if (l > 64) {
+ b = make_ulonglong2(a.y >> (l-64), 0ull);
+ } else {
+ b = make_ulonglong2((a.x >> l) | (a.y << (8*sizeof(a.y)-l)), a.y >> l);
+ }
+ return b;
+}
+
+__host__ __device__ ulonglong2 operator|(ulonglong2 a, ulonglong2 b) {
+ return make_ulonglong2(a.x | b.x, a.y | b.y);
+}
+
+template<int BDIM_X,
+ int MAXIOB,
+ int SH_BYTE_X_BL,
+ typename LDST_T>
+__device__ void memcpy_d(const size_t n,
+ const unsigned char *__restrict__ src,
+ unsigned char *__restrict__ dst,
+ unsigned char *__restrict__ __sh) {
+
+ const int tid = threadIdx.x;
+
+ const unsigned long long srcULL = reinterpret_cast<unsigned long long>(src);
+ const unsigned long long dstULL = reinterpret_cast<unsigned long long>(dst);
+
+ int srcOff = (MAXIOB - srcULL) & (MAXIOB-1);
+ int dstOff = (MAXIOB - dstULL) & (MAXIOB-1);
+
+ const int ELXTH = SH_BYTE_X_BL/(BDIM_X*MAXIOB);
+ LDST_T *__ptrSH = reinterpret_cast<LDST_T *>(__sh);
+
+ if (srcOff == dstOff) {
+
+ const LDST_T *__restrict__ __ptrLDG = reinterpret_cast<const LDST_T *>(src + srcOff);
+ LDST_T *__restrict__ __ptrSTG = reinterpret_cast< LDST_T *>(dst + dstOff);
+
+ int nread = (n-srcOff) / sizeof(*__ptrLDG);
+ int remBytes = (n-srcOff) % sizeof(*__ptrLDG);
+
+ LDST_T __loc[ELXTH];
+
+ #pragma unroll
+ for(int j = 0; j < ELXTH; j++) {
+ if (j*BDIM_X+tid < nread) {
+ __loc[j] = __ptrLDG[j*BDIM_X+tid];
+ }
+ }
+
+ for(int i = 0; i < nread; i += BDIM_X*ELXTH) {
+
+ #pragma unroll
+ for(int j = 0; j < ELXTH; j++) {
+ __ptrSH[j*BDIM_X+tid] = __loc[j];
+ }
+
+ #pragma unroll
+ for(int j = 0; j < ELXTH; j++) {
+ if (i + BDIM_X*ELXTH + j*BDIM_X + tid < nread) {
+ __loc[j] = __ptrLDG[i + BDIM_X*ELXTH + j*BDIM_X + tid];
+ }
+ }
+
+ #pragma unroll
+ for(int j = 0; j < ELXTH; j++) {
+ if (i + j*BDIM_X + tid < nread) {
+ __ptrSTG[i + j*BDIM_X + tid] = __ptrSH[j*BDIM_X+tid];
+ }
+ }
+ }
+ if (tid < srcOff+remBytes) {
+ const int off = (tid < srcOff) ? tid : n-remBytes+tid-srcOff;
+ dst[off] = src[off];
+ }
+ } else {
+ const LDST_T *__restrict__ __ptrLDG = reinterpret_cast<const LDST_T *>(src + srcOff);
+ LDST_T *__restrict__ __ptrSTG = reinterpret_cast< LDST_T *>(dst + dstOff);
+
+ int nread = ((n-srcOff) / sizeof(*__ptrLDG));
+ int remBytes = ((n-srcOff) % sizeof(*__ptrLDG));
+
+ int lowShft, uppShft;
+ if (srcOff > dstOff) {
+ uppShft = (srcOff-dstOff)*8;
+ lowShft = (8*sizeof(*__ptrLDG)) - uppShft;
+ __ptrSTG++;
+ } else {
+ lowShft = (dstOff-srcOff)*8;
+ uppShft = (8*sizeof(*__ptrLDG)) - lowShft;
+ }
+
+ for(int i = 0; i < nread-1; i += BDIM_X) {
+ if (i+tid < nread-1) {
+ const LDST_T low = __ptrLDG[i+tid];
+ const LDST_T upp = __ptrLDG[i+tid+1];
+
+ __ptrSTG[i+tid] = (low >> lowShft) | (upp << uppShft);
+ }
+ }
+
+ remBytes += sizeof(*__ptrLDG);
+ if (srcOff > dstOff) {
+ dstOff += sizeof(*__ptrLDG);
+ if (tid < dstOff+remBytes) {
+ const int off = (tid < dstOff) ? tid : n-remBytes + tid-dstOff;
+ dst[off] = src[off];
+ }
+ } else {
+ if (tid < dstOff+remBytes) {
+ const int off = (tid < dstOff) ? tid : n-remBytes + tid-dstOff;
+ dst[off] = src[off];
+ }
+ }
+ }
+}
+
+template<int BDIM_X,
+ int MAXIOB>
+__global__ void memcpy_k(const size_t *sizes,
+ const unsigned char *const __restrict__ *__restrict__ in,
+ unsigned char *__restrict__ *__restrict__ out) {
+
+ const int SH_BYTE_X_BL = 32768;
+ __shared__ unsigned char __sh[SH_BYTE_X_BL];
+
+ switch(MAXIOB) {
+ case 4:
+ memcpy_d<BDIM_X, MAXIOB, SH_BYTE_X_BL, unsigned int>(sizes[blockIdx.x],
+ in[blockIdx.x],
+ out[blockIdx.x],
+ __sh);
+ break;
+ case 8:
+ memcpy_d<BDIM_X, MAXIOB, SH_BYTE_X_BL, unsigned long long>(sizes[blockIdx.x],
+ in[blockIdx.x],
+ out[blockIdx.x],
+ __sh);
+ break;
+ case 16:
+ memcpy_d<BDIM_X, MAXIOB, SH_BYTE_X_BL, ulonglong2>(sizes[blockIdx.x],
+ in[blockIdx.x],
+ out[blockIdx.x],
+ __sh);
+ break;
+ }
+ return;
+}
+
+
+
+#define NTHREADS 1024
+void batched_d2d_memcpy(void** out_ptrs, void** in_ptrs, size_t* sizes, int num_copies, cudaStream_t stream)
+{
+ memcpy_k<NTHREADS, 16><<<num_copies, NTHREADS, 0, stream>>>(sizes, (unsigned char**) in_ptrs, (unsigned char**) out_ptrs);
+}
+
diff --git a/horovod/common/batched_memcpy.h b/horovod/common/batched_memcpy.h
new file mode 100644
index 0000000..867c8bf
--- /dev/null
+++ b/horovod/common/batched_memcpy.h
@@ -0,0 +1,22 @@
+// Copyright (C) 2018 NVIDIA CORPORATION. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// =============================================================================
+
+#ifndef BATCHED_MEMCPY_H
+#define BATCHED_MEMCPY_H
+
+// Performs a batched d2d memcopy
+void batched_d2d_memcpy(void** out_ptrs, void** in_ptrs, size_t* sizes, int num_copies, cudaStream_t stream = 0);
+
+#endif // BATCHED_MEMCPY_H
diff --git a/horovod/common/operations.cc b/horovod/common/operations.cc
index 3cf1a42..d164d2d 100644
--- a/horovod/common/operations.cc
+++ b/horovod/common/operations.cc
@@ -1,5 +1,6 @@
// Copyright 2016 The TensorFlow Authors. All Rights Reserved.
// Modifications copyright (C) 2018 Uber Technologies, Inc.
+// Modifications copyright (C) 2018 NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -26,6 +27,7 @@
#if HAVE_CUDA
#include <cuda_runtime.h>
+#include "batched_memcpy.h"
#endif
#if HAVE_NCCL
@@ -43,6 +45,8 @@
#include "operations.h"
#include "timeline.h"
+#define ALIGN_BYTES 128
+
/*
* Allreduce, Allgather and Broadcast Ops.
*
@@ -103,6 +107,33 @@ using MessageTable = std::unordered_map<
std::string,
std::tuple<std::vector<MPIRequest>, std::chrono::steady_clock::time_point>>;
+// Structure containing pinned host pointers for use with batched d2d copy
+// kernel
+#define PACK_PTRS_CAPACITY 500
+struct PackPtrs {
+ bool allocated = false;
+ void** pack_out = nullptr;
+ void** pack_in = nullptr;
+ size_t* pack_sizes = nullptr;
+ void** unpack_out = nullptr;
+ void** unpack_in = nullptr;
+ size_t* unpack_sizes = nullptr;
+
+ void free() {
+#if HAVE_CUDA
+ if (allocated) {
+ cudaFreeHost(pack_out);
+ cudaFreeHost(pack_in);
+ cudaFreeHost(pack_sizes);
+ cudaFreeHost(unpack_out);
+ cudaFreeHost(unpack_in);
+ cudaFreeHost(unpack_sizes);
+ allocated = false;
+ }
+#endif
+ }
+};
+
// The global state required for the MPI ops.
//
// MPI is a library that stores a lot of global per-program state and often
@@ -133,6 +164,8 @@ struct HorovodGlobalState {
// how many nodes are ready to allreduce every tensor (keyed by tensor
// name) and time point when tensor started allreduce op.
std::unique_ptr<MessageTable> message_table;
+ std::unique_ptr<MessageTable> local_message_table;
+ std::unique_ptr<MessageTable> fixed_message_table;
// Time point when coordinator last checked for stalled tensors.
std::chrono::steady_clock::time_point last_stall_check;
@@ -158,6 +191,8 @@ struct HorovodGlobalState {
std::shared_ptr<PersistentBuffer>>
tensor_fusion_buffers;
+ PackPtrs pack_ptrs;
+
// Whether MPI_Init has been completed on the background thread.
bool initialization_done = false;
@@ -190,6 +225,15 @@ struct HorovodGlobalState {
// Do hierarchical allreduce with MPI + NCCL.
bool hierarchical_allreduce = false;
+ // Use two stage control plane
+ bool two_stage_loop = false;
+
+ // Sets mode for allreduce (0: single global allreduce, 1: hierarchical on GPU)
+ int allreduce_mode = 0;
+
+ // Fixed number of tensors to allreduce in a step
+ int fixed_payload = 0;
+
// The CUDA stream used for data transfers and within-allreduce operations.
// A naive implementation would use the TensorFlow StreamExecutor CUDA
// stream. However, the allreduce and allgather require doing memory copies
@@ -209,6 +253,8 @@ struct HorovodGlobalState {
#endif
#if HAVE_NCCL
std::unordered_map<std::vector<int32_t>, ncclComm_t> nccl_comms;
+ std::unordered_map<std::vector<int32_t>, ncclComm_t> nccl_local_comms;
+ std::unordered_map<std::vector<int32_t>, ncclComm_t> nccl_cross_comms;
#endif
// Will be set to true after initialization when ddl is used
@@ -376,59 +422,65 @@ MPIResponse ConstructMPIResponse(std::unique_ptr<MessageTable>& message_table,
// the sum of the first dimension. Collect the sizes by rank.
std::vector<int64_t> tensor_sizes(requests.size());
if (message_type == MPIRequest::ALLGATHER) {
- TensorShape tensor_shape;
- for (auto dim : requests[0].tensor_shape()) {
- tensor_shape.AddDim(dim);
- }
-
- if (tensor_shape.dims() == 0) {
+ if (horovod_global.two_stage_loop) {
error = true;
- error_message_stream << "Rank zero tried to "
- << MPIRequest::RequestType_Name(message_type)
- << " a rank-zero tensor.";
+ error_message_stream << "Allgather not supported with HOROVOD_TWO_STAGE_LOOP=1. "
+ << " Disable this feature to run.";
} else {
- tensor_sizes[requests[0].request_rank()] = tensor_shape.dim_size(0);
- }
-
- for (unsigned int i = 1; i < requests.size(); i++) {
- if (error) {
- break;
+ TensorShape tensor_shape;
+ for (auto dim : requests[0].tensor_shape()) {
+ tensor_shape.AddDim(dim);
}
- TensorShape request_shape;
- for (auto dim : requests[i].tensor_shape()) {
- request_shape.AddDim(dim);
- }
- if (tensor_shape.dims() != request_shape.dims()) {
+ if (tensor_shape.dims() == 0) {
error = true;
- error_message_stream
- << "Mismatched " << MPIRequest::RequestType_Name(message_type)
- << " tensor shapes: One rank sent a tensor of rank "
- << tensor_shape.dims()
- << ", but another rank sent a tensor of rank "
- << request_shape.dims() << ".";
- break;
+ error_message_stream << "Rank zero tried to "
+ << MPIRequest::RequestType_Name(message_type)
+ << " a rank-zero tensor.";
+ } else {
+ tensor_sizes[requests[0].request_rank()] = tensor_shape.dim_size(0);
}
- bool dim_mismatch = false;
- for (int dim = 1; dim < tensor_shape.dims(); dim++) {
- if (tensor_shape.dim_size(dim) != request_shape.dim_size(dim)) {
+ for (unsigned int i = 1; i < requests.size(); i++) {
+ if (error) {
+ break;
+ }
+
+ TensorShape request_shape;
+ for (auto dim : requests[i].tensor_shape()) {
+ request_shape.AddDim(dim);
+ }
+ if (tensor_shape.dims() != request_shape.dims()) {
error = true;
error_message_stream
<< "Mismatched " << MPIRequest::RequestType_Name(message_type)
- << " tensor shapes: One rank sent a tensor with dimension " << dim
- << " equal to " << tensor_shape.dim_size(dim)
- << ", but another rank sent a tensor with dimension " << dim
- << " equal to " << request_shape.dim_size(dim) << ".";
- dim_mismatch = true;
+ << " tensor shapes: One rank sent a tensor of rank "
+ << tensor_shape.dims()
+ << ", but another rank sent a tensor of rank "
+ << request_shape.dims() << ".";
break;
}
- }
- if (dim_mismatch) {
- break;
- }
- tensor_sizes[requests[i].request_rank()] = request_shape.dim_size(0);
+ bool dim_mismatch = false;
+ for (int dim = 1; dim < tensor_shape.dims(); dim++) {
+ if (tensor_shape.dim_size(dim) != request_shape.dim_size(dim)) {
+ error = true;
+ error_message_stream
+ << "Mismatched " << MPIRequest::RequestType_Name(message_type)
+ << " tensor shapes: One rank sent a tensor with dimension " << dim
+ << " equal to " << tensor_shape.dim_size(dim)
+ << ", but another rank sent a tensor with dimension " << dim
+ << " equal to " << request_shape.dim_size(dim) << ".";
+ dim_mismatch = true;
+ break;
+ }
+ }
+ if (dim_mismatch) {
+ break;
+ }
+
+ tensor_sizes[requests[i].request_rank()] = request_shape.dim_size(0);
+ }
}
}
@@ -471,9 +523,24 @@ MPIResponse ConstructMPIResponse(std::unique_ptr<MessageTable>& message_table,
break;
}
}
- std::vector<int32_t> devices(requests.size());
+
+ std::vector<int32_t> devices;
+ if (horovod_global.two_stage_loop || horovod_global.fixed_payload != 0) {
+ devices.resize(1);
+ } else {
+ devices.resize(requests.size());
+ }
+
for (auto& request : requests) {
- devices[request.request_rank()] = request.device();
+ if (horovod_global.two_stage_loop || horovod_global.fixed_payload != 0) {
+ // Note: Device lists generated here aren't used for anything functional
+ // and are currently restrictive.
+ // Setting single list value to either CPU device or GPU device (0) when
+ // using alternative paths.
+ devices[0] = (request.device() == CPU_DEVICE_ID) ? CPU_DEVICE_ID : 0;
+ } else {
+ devices[request.request_rank()] = request.device();
+ }
}
MPIResponse response;
@@ -501,6 +568,52 @@ MPIResponse ConstructMPIResponse(std::unique_ptr<MessageTable>& message_table,
return response;
}
+// Populates provided MPIResponseList with responses from map. Fuses allreduce
+// responses by datatype when appropriate.
+void PopulateMPIResponseList(MPIResponseList& response_list,
+ std::map<MPIDataType, std::deque<MPIResponse>>& responses_by_type,
+ HorovodGlobalState& state) {
+
+ for (auto& res : responses_by_type) {
+ auto& responses = res.second;
+ while (!responses.empty()) {
+ auto response = responses.front();
+ assert(response.tensor_names().size() == 1);
+ responses.pop_front();
+
+ if (response.response_type() == MPIResponse::ResponseType::ALLREDUCE) {
+ // Attempt to add more responses to this fused response.
+ auto& entry = state.tensor_table[response.tensor_names()[0]];
+ int64_t tensor_size = entry.tensor->size();
+
+ while (!responses.empty()) {
+ auto new_response = responses.front();
+ assert(new_response.tensor_names().size() == 1);
+ auto& new_entry = state.tensor_table[new_response.tensor_names()[0]];
+ int64_t new_tensor_size = new_entry.tensor->size();
+
+ if (response.response_type() == new_response.response_type() &&
+ response.devices() == new_response.devices() &&
+ entry.tensor->dtype() == new_entry.tensor->dtype() &&
+ tensor_size + new_tensor_size <= state.tensor_fusion_threshold) {
+ tensor_size += new_tensor_size;
+ response.add_tensor_names(new_response.tensor_names()[0]);
+ responses.pop_front();
+ } else {
+ // Don't try to fuse additional tensors since they are usually
+ // computed in order of requests and skipping tensors may mean
+ // that the batch will have to wait longer while skipped tensors
+ // could be reduced at that time.
+ break;
+ }
+ }
+ }
+
+ response_list.add_responses(response);
+ }
+ }
+}
+
MPI_Datatype GetMPIDataType(const std::shared_ptr<Tensor> tensor) {
switch (tensor->dtype()) {
case HOROVOD_UINT8:
@@ -529,6 +642,33 @@ MPI_Datatype GetMPIDataType(const std::shared_ptr<Tensor> tensor) {
}
}
+size_t GetDataTypeSize(const std::shared_ptr<Tensor> tensor) {
+ switch (tensor->dtype()) {
+ case HOROVOD_UINT8:
+ return sizeof(unsigned char);
+ case HOROVOD_INT8:
+ return sizeof(char);
+ case HOROVOD_UINT16:
+ return sizeof(unsigned short int);
+ case HOROVOD_INT16:
+ return sizeof (short int);
+ case HOROVOD_INT32:
+ return sizeof(int);
+ case HOROVOD_INT64:
+ return sizeof(long long int);
+ case HOROVOD_FLOAT16:
+ return sizeof(short int);
+ case HOROVOD_FLOAT32:
+ return sizeof(float);
+ case HOROVOD_FLOAT64:
+ return sizeof(double);
+ case HOROVOD_BOOL:
+ return sizeof(bool);
+ default:
+ throw std::logic_error("Cannot get size of type " + MPIDataType_Name(tensor->dtype()));
+ }
+}
+
#if HAVE_NCCL
ncclDataType_t GetNCCLDataType(const std::shared_ptr<Tensor> tensor) {
switch (tensor->dtype()) {
@@ -725,7 +865,7 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
timeline.Start(e.tensor_name, response.response_type());
}
- if (entries.size() > 1) {
+ if (entries.size() > 0) {
auto first_entry = entries[0];
// Note: it is OK for different entries to come from different frameworks
// since buffer allocated here is guaranteed to survive at least till the
@@ -737,8 +877,14 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
// Lazily allocate persistent buffer for Tensor Fusion and keep it
// forever per device.
+ size_t buf_size = horovod_global.tensor_fusion_threshold;
+
+ // Add padding to allocation for allreduce_mode = 1 (hierarchical on GPU).
+ // Need a max of ALIGN_BYTES * local_size padding to guarantee enough space.
+ if (horovod_global.allreduce_mode == 1) buf_size += ALIGN_BYTES * horovod_global.local_size;
+
Status status = first_entry.context->AllocatePersistent(
- horovod_global.tensor_fusion_threshold, &buffer);
+ buf_size, &buffer);
if (!status.ok()) {
for (auto& e : entries) {
timeline.End(e.tensor_name, nullptr);
@@ -746,6 +892,18 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
}
return;
}
+#if HAVE_CUDA
+ if (!horovod_global.pack_ptrs.allocated) {
+ CUDA_CHECK(entries, "cudaSetDevice", cudaSetDevice(first_entry.device))
+ cudaMallocHost(&horovod_global.pack_ptrs.pack_out, PACK_PTRS_CAPACITY*sizeof(float*));
+ cudaMallocHost(&horovod_global.pack_ptrs.pack_in, PACK_PTRS_CAPACITY*sizeof(float*));
+ cudaMallocHost(&horovod_global.pack_ptrs.pack_sizes, PACK_PTRS_CAPACITY*sizeof(size_t));
+ cudaMallocHost(&horovod_global.pack_ptrs.unpack_out, PACK_PTRS_CAPACITY*sizeof(float*));
+ cudaMallocHost(&horovod_global.pack_ptrs.unpack_in, PACK_PTRS_CAPACITY*sizeof(float*));
+ cudaMallocHost(&horovod_global.pack_ptrs.unpack_sizes, PACK_PTRS_CAPACITY*sizeof(size_t));
+ horovod_global.pack_ptrs.allocated = true;
+ }
+#endif
ACTIVITY_END_ALL(entries, timeline)
}
@@ -868,7 +1026,8 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
// Determine GPU IDs of the devices participating in this communicator.
std::vector<int32_t> nccl_device_map;
- if (horovod_global.hierarchical_allreduce) {
+ if (horovod_global.hierarchical_allreduce &&
+ !(horovod_global.two_stage_loop || horovod_global.fixed_payload != 0)) {
for (int rank : horovod_global.local_comm_ranks) {
nccl_device_map.push_back(response.devices()[rank]);
}
@@ -879,7 +1038,9 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
#if HOROVOD_GPU_ALLREDUCE=='N'
// Ensure NCCL communicator is in the map before executing reduction.
ncclComm_t& nccl_comm = horovod_global.nccl_comms[nccl_device_map];
- if (nccl_comm == nullptr) {
+ ncclComm_t& nccl_local_comm = horovod_global.nccl_local_comms[nccl_device_map];
+ ncclComm_t& nccl_cross_comm = horovod_global.nccl_cross_comms[nccl_device_map];
+ if (horovod_global.allreduce_mode == 0 && nccl_comm == nullptr) {
ACTIVITY_START_ALL(entries, timeline, INIT_NCCL)
int nccl_rank, nccl_size;
@@ -914,7 +1075,52 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
MPI_CHECK(entries, "MPI_Barrier", MPI_Barrier(horovod_global.mpi_comm));
ACTIVITY_END_ALL(entries, timeline)
+
+ } else if (horovod_global.allreduce_mode == 1 && nccl_local_comm == nullptr &&
+ nccl_cross_comm == nullptr) {
+ ACTIVITY_START_ALL(entries, timeline, INIT_NCCL)
+ ncclUniqueId nccl_id;
+ if (horovod_global.local_rank == 0) {
+ NCCL_CHECK(entries, "ncclGetUniqueId", ncclGetUniqueId(&nccl_id))
+ }
+
+ MPI_CHECK(entries, "MPI_Bcast",
+ MPI_Bcast((void*)&nccl_id, sizeof(nccl_id), MPI_BYTE, 0,
+ horovod_global.local_comm));
+
+ ncclComm_t new_nccl_local_comm;
+ NCCL_CHECK(
+ entries, "ncclCommInitRank",
+ ncclCommInitRank(&new_nccl_local_comm, horovod_global.local_size, nccl_id, horovod_global.local_rank))
+
+ nccl_local_comm = new_nccl_local_comm;
+
+ MPI_CHECK(entries, "MPI_Barrier", MPI_Barrier(horovod_global.local_comm));
+
+
+ if (horovod_global.rank < horovod_global.local_size) {
+ NCCL_CHECK(entries, "ncclGetUniqueId", ncclGetUniqueId(&nccl_id))
+ }
+
+ MPI_CHECK(entries, "MPI_Bcast",
+ MPI_Bcast((void*)&nccl_id, sizeof(nccl_id), MPI_BYTE, 0,
+ horovod_global.cross_comm));
+
+ ncclComm_t new_nccl_cross_comm;
+ NCCL_CHECK(
+ entries, "ncclCommInitRank",
+ ncclCommInitRank(&new_nccl_cross_comm, horovod_global.cross_size, nccl_id, horovod_global.cross_rank))
+ nccl_cross_comm = new_nccl_cross_comm;
+
+ MPI_CHECK(entries, "MPI_Barrier", MPI_Barrier(horovod_global.cross_comm));
+
+ // Barrier helps NCCL to synchronize after initialization and avoid
+ // deadlock that we've been seeing without it.
+ MPI_CHECK(entries, "MPI_Barrier", MPI_Barrier(horovod_global.mpi_comm));
+
+ ACTIVITY_END_ALL(entries, timeline)
}
+
#elif HOROVOD_GPU_ALLREDUCE == 'D'
if (!horovod_global.ddl_initialized) {
// Initialize DDL
@@ -937,12 +1143,14 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
// If entries.size() > 1, we copy tensors into fusion buffer before
// allreduce, and distribute results of allreduce back into target
// tensors after allreduce.
+ // If there is a single entry and it will fit, also copy to fusion buffer.
const void* fused_input_data;
void* buffer_data;
int64_t num_elements = 0;
size_t buffer_len;
- if (entries.size() > 1) {
+
+ if (entries.size() > 1 || first_entry.output->size() <= horovod_global.tensor_fusion_threshold) {
// Access the fusion buffer.
auto& buffer = horovod_global.tensor_fusion_buffers[std::make_tuple(
first_entry.device, first_entry.context->framework())];
@@ -950,16 +1158,42 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
const_cast<void*>(buffer->AccessData(first_entry.context));
// Copy memory into the fusion buffer.
- int64_t offset = 0;
- for (auto& e : entries) {
- void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
- CUDA_CHECK(entries, "cudaMemcpyAsync",
- cudaMemcpyAsync(buffer_data_at_offset, e.tensor->data(),
- (size_t)e.tensor->size(),
- cudaMemcpyDeviceToDevice, stream))
- offset += e.tensor->size();
+ if (entries.size() <= PACK_PTRS_CAPACITY) {
+ int64_t offset = 0;
+ int idx = 0;
+
+ // Set input/output pointers and sizes
+ for (auto& e : entries) {
+ void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
+
+ horovod_global.pack_ptrs.pack_out[idx] = buffer_data_at_offset;
+ horovod_global.pack_ptrs.pack_in[idx] = (void*) e.tensor->data();
+ horovod_global.pack_ptrs.pack_sizes[idx] = e.tensor->size();
+
+ offset += e.tensor->size();
+ idx++;
+ }
+ buffer_len = (size_t)offset;
+
+ // Perform batched d2d memcpy
+ batched_d2d_memcpy(horovod_global.pack_ptrs.pack_out,
+ horovod_global.pack_ptrs.pack_in,
+ horovod_global.pack_ptrs.pack_sizes,
+ entries.size(),
+ stream);
+
+ } else {
+ int64_t offset = 0;
+ for (auto& e : entries) {
+ void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
+ CUDA_CHECK(entries, "cudaMemcpyAsync",
+ cudaMemcpyAsync(buffer_data_at_offset, e.tensor->data(),
+ (size_t)e.tensor->size(),
+ cudaMemcpyDeviceToDevice, stream))
+ offset += e.tensor->size();
+ }
+ buffer_len = (size_t)offset;
}
- buffer_len = (size_t)offset;
if (timeline.Initialized() || horovod_global.ddl_initialized) {
RECORD_EVENT(entries, event_queue, MEMCPY_IN_FUSION_BUFFER, stream)
}
@@ -971,6 +1205,7 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
for (auto& e : entries) {
num_elements += e.tensor->shape().num_elements();
}
+
} else {
fused_input_data = first_entry.tensor->data();
buffer_data = (void*)first_entry.output->data();
@@ -1050,29 +1285,86 @@ void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
RECORD_EVENT(entries, event_queue, NCCL_BCAST, stream)
}
} else {
- NCCL_CHECK(entries, "ncclAllReduce",
- ncclAllReduce(fused_input_data, buffer_data,
- (size_t)num_elements,
- GetNCCLDataType(first_entry.tensor), ncclSum,
- nccl_comm, stream))
+
+ size_t num_elements_per_rank = 0;
+ if (horovod_global.allreduce_mode == 1) {
+ num_elements_per_rank = (num_elements + horovod_global.local_size - 1) / horovod_global.local_size;
+ // align buffers to ALIGN_BYTES bytes
+ int align = ALIGN_BYTES / GetDataTypeSize(first_entry.tensor);
+ num_elements_per_rank = (num_elements_per_rank + align - 1) / align * align;
+ }
+
+ if (horovod_global.allreduce_mode == 0) {
+ NCCL_CHECK(entries, "ncclAllReduce",
+ ncclAllReduce(fused_input_data, buffer_data,
+ (size_t)num_elements,
+ GetNCCLDataType(first_entry.tensor), ncclSum,
+ nccl_comm, stream))
+
+ } else if (horovod_global.allreduce_mode == 1) {
+
+ auto buffer_at_offset = (uint8_t*)buffer_data + num_elements_per_rank * GetDataTypeSize(first_entry.tensor) *
+ horovod_global.local_rank;
+ ncclReduceScatter(fused_input_data, buffer_at_offset,
+ (size_t) num_elements_per_rank,
+ GetNCCLDataType(first_entry.tensor), ncclSum,
+ nccl_local_comm, stream);
+ ncclAllReduce(buffer_at_offset, buffer_at_offset,
+ (size_t)num_elements_per_rank,
+ GetNCCLDataType(first_entry.tensor), ncclSum,
+ nccl_cross_comm, stream);
+ ncclAllGather(buffer_at_offset, buffer_data,
+ (size_t)num_elements_per_rank,
+ GetNCCLDataType(first_entry.tensor),
+ nccl_local_comm, stream);
+ }
}
#endif
if (timeline.Initialized()) {
RECORD_EVENT(entries, event_queue, NCCL_ALLREDUCE, stream)
}
- if (entries.size() > 1) {
+ if (entries.size() > 1 || first_entry.output->size() <= horovod_global.tensor_fusion_threshold) {
// Copy memory out of the fusion buffer.
- int64_t offset = 0;
- for (auto& e : entries) {
- void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
- CUDA_CHECK(entries, "cudaMemcpyAsync",
- cudaMemcpyAsync((void*)e.output->data(),
- buffer_data_at_offset,
- (size_t)e.tensor->size(),
- cudaMemcpyDeviceToDevice, stream))
- offset += e.tensor->size();
+ if (entries.size() <= PACK_PTRS_CAPACITY) {
+ int64_t offset = 0;
+ int idx = 0;
+
+ // Set input/output pointers and sizes
+ for (auto& e : entries) {
+ void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
+
+ horovod_global.pack_ptrs.unpack_out[idx] = (void*)(e.output->data());
+ horovod_global.pack_ptrs.unpack_in[idx] = buffer_data_at_offset;
+ horovod_global.pack_ptrs.unpack_sizes[idx] = e.tensor->size();
+
+ offset += e.tensor->size();
+ idx++;
+ }
+ // Perform batched d2d memcpy
+ batched_d2d_memcpy(horovod_global.pack_ptrs.unpack_out,
+ horovod_global.pack_ptrs.unpack_in,
+ horovod_global.pack_ptrs.unpack_sizes,
+ entries.size(),
+ stream);
+
+ // Sync here is required to ensure pack/unpack pointer for batch D2D memcpy
+ // do not get overwritten by possible future iteration.
+ cudaStreamSynchronize(stream);
+
+ } else {
+ int64_t offset = 0;
+ for (auto& e : entries) {
+ void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
+ CUDA_CHECK(entries, "cudaMemcpyAsync",
+ cudaMemcpyAsync((void*)e.output->data(),
+ buffer_data_at_offset,
+ (size_t)e.tensor->size(),
+ cudaMemcpyDeviceToDevice, stream))
+ offset += e.tensor->size();
+ }
}
+
if (timeline.Initialized()) {
RECORD_EVENT(entries, event_queue, MEMCPY_OUT_FUSION_BUFFER, stream)
}
@@ -1300,6 +1592,8 @@ void CheckForStalledTensors(HorovodGlobalState& state) {
// otherwise we may end up dispatching many blocked threads and never make
// progress if we have a thread pool limit.
bool RunLoopOnce(HorovodGlobalState& state, bool is_coordinator);
+bool RunTwoStageLoopOnce(HorovodGlobalState& state, bool is_coordinator,
+ bool is_local_coordinator);
void BackgroundThreadLoop(HorovodGlobalState& state) {
// Initialize MPI. This must happen on the background thread, since not all
// MPI implementations support being called from multiple threads.
@@ -1345,6 +1639,7 @@ void BackgroundThreadLoop(HorovodGlobalState& state) {
local_comm_ranks[local_rank] = rank;
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, local_comm_ranks.data(), 1,
MPI_INT, local_comm);
+ bool is_local_coordinator = local_rank == 0;
// Set up cross-communicator in case of hierarchical allreduce.
MPI_Comm cross_comm;
@@ -1384,7 +1679,7 @@ void BackgroundThreadLoop(HorovodGlobalState& state) {
std::strtol(horovod_fusion_threshold, nullptr, 10);
}
- // Override the cycle time.
+ // Override the cycle times and low-latency threshold.
auto horovod_cycle_time = std::getenv("HOROVOD_CYCLE_TIME");
if (horovod_cycle_time != nullptr) {
state.cycle_time_ms = std::strtof(horovod_cycle_time, nullptr);
@@ -1400,17 +1695,60 @@ void BackgroundThreadLoop(HorovodGlobalState& state) {
state.hierarchical_allreduce = true;
}
+ // Set flag for two level communication strategy
+ auto horovod_two_stage_loop =
+ std::getenv("HOROVOD_TWO_STAGE_LOOP");
+ if (horovod_two_stage_loop != nullptr && std::atoi(horovod_two_stage_loop) != 0) {
+ state.two_stage_loop = true;
+ }
+
+ auto horovod_allreduce_mode =
+ std::getenv("HOROVOD_ALLREDUCE_MODE");
+ if (horovod_allreduce_mode != nullptr && std::atoi(horovod_allreduce_mode) != 0) {
+ state.allreduce_mode = std::atoi(horovod_allreduce_mode);
+ if (state.allreduce_mode != 1) {
+ if (state.rank == RANK_ZERO) {
+ std::cerr << "HOROVOD_ALLREDUCE_MODE = " << state.allreduce_mode << " not valid.";
+ std::cerr << "Reverting to default (HOROVOD_ALLREDUCE_MODE = 0)." << std::endl;
+ }
+ state.allreduce_mode = 0;
+ } else if (state.hierarchical_allreduce && state.allreduce_mode != 0) {
+ if (state.rank == RANK_ZERO) {
+ std::cerr << "HOROVOD_ALLREDUCE_MODE = " << state.allreduce_mode << " and ";
+ std::cerr << "HOROVOD_HIERARCHICAL_ALLREDUCE are incompatible options.";
+ std::cerr << "Reverting to default (HOROVOD_ALLREDUCE_MODE = 0)." << std::endl;
+ }
+ state.allreduce_mode = 0;
+ }
+ }
+
+ auto horovod_fixed_payload =
+ std::getenv("HOROVOD_FIXED_PAYLOAD");
+ if (horovod_fixed_payload != nullptr && std::atoi(horovod_fixed_payload) != 0) {
+ state.fixed_payload = std::atoi(horovod_fixed_payload);
+ }
+
// Initialize the tensor count table. No tensors are available yet.
if (is_coordinator) {
state.message_table = std::unique_ptr<MessageTable>(new MessageTable());
}
+ if (is_local_coordinator && state.two_stage_loop) {
+ state.local_message_table = std::unique_ptr<MessageTable>(new MessageTable());
+ }
+
+ if (state.fixed_payload != 0) {
+ state.fixed_message_table = std::unique_ptr<MessageTable>(new MessageTable());
+ }
// Signal that initialization is completed.
state.initialization_done = true;
// Iterate until shutdown.
- unsigned count = 0;
- while (RunLoopOnce(state, is_coordinator)) {};
+ if (!state.two_stage_loop) {
+ while (RunLoopOnce(state, is_coordinator)) {};
+ } else {
+ while (RunTwoStageLoopOnce(state, is_coordinator, is_local_coordinator)) {};
+ }
// TODO: init.cu:645 WARN Cuda failure 'driver shutting down'
//#if HAVE_NCCL
@@ -1441,6 +1779,9 @@ void BackgroundThreadLoop(HorovodGlobalState& state) {
cb(SHUT_DOWN_ERROR);
}
+ // Free batched memcpy pointers
+ state.pack_ptrs.free();
+
MPI_Comm_free(&state.mpi_comm);
MPI_Comm_free(&state.local_comm);
MPI_Comm_free(&state.cross_comm);
@@ -1454,6 +1795,42 @@ void BackgroundThreadLoop(HorovodGlobalState& state) {
#endif
}
+// In fixed payload case, all ranks can execute logic independently. This function
+// encapsulates that logic.
+void RunBypass(std::queue<MPIRequest>& message_queue, HorovodGlobalState& state) {
+ // Using set to get consistently ordered list
+ std::set<std::string> ready_to_reduce_fixed;
+
+ while (!message_queue.empty()) {
+ // Pop the first available message message
+ MPIRequest message = message_queue.front();
+ message_queue.pop();
+
+ IncrementTensorCount(state.fixed_message_table, message, 1);
+ ready_to_reduce_fixed.insert(message.tensor_name());
+ }
+
+ // Every rank forms own response
+ std::map<MPIDataType, std::deque<MPIResponse>> responses_by_type;
+
+ for (auto& tensor_name : ready_to_reduce_fixed) {
+ MPIResponse response =
+ ConstructMPIResponse(state.fixed_message_table, tensor_name);
+ auto& entry = state.tensor_table[response.tensor_names()[0]];
+ responses_by_type[entry.tensor->dtype()].push_back(std::move(response));
+ }
+
+ MPIResponseList response_list;
+ PopulateMPIResponseList(response_list, responses_by_type, state);
+
+ // Perform the collective operation. All nodes should end up performing
+ // the same operation.
+ for (auto& response : response_list.responses()) {
+ PerformOperation(state.tensor_table, response);
+ }
+}
+
+
// The coordinator currently follows a master-worker paradigm. Rank zero acts
// as the master (the "coordinator"), whereas all other ranks are simply
// workers. Each rank runs its own background thread which progresses in ticks.
@@ -1495,21 +1872,70 @@ bool RunLoopOnce(HorovodGlobalState& state, bool is_coordinator) {
if (sleep_duration > std::chrono::steady_clock::duration::zero()) {
std::this_thread::sleep_for(sleep_duration);
}
+
+ // Use barrier to sync Horovod worker thread timings
+ MPI_Barrier(state.mpi_comm);
state.last_cycle_start = std::chrono::steady_clock::now();
// Copy the data structures from global state under this lock.
// However, don't keep the lock for the rest of the loop, so that
// enqueued stream callbacks can continue.
+ int status[3];
std::queue<MPIRequest> message_queue;
{
std::lock_guard<std::mutex> guard(state.mutex);
- while (!state.message_queue.empty()) {
- MPIRequest message = state.message_queue.front();