/
operations.cc
1671 lines (1488 loc) · 62.8 KB
/
operations.cc
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
// Copyright 2016 The TensorFlow Authors. All Rights Reserved.
// Modifications copyright (C) 2018 Uber Technologies, Inc.
//
// 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.
// =============================================================================
#include <atomic>
#include <cassert>
#include <cstring>
#include <queue>
#include <sstream>
#include <thread>
#include <unordered_map>
#if HAVE_CUDA
#include <cuda_runtime.h>
#endif
#if HAVE_NCCL
#include <nccl.h>
#endif
#define OMPI_SKIP_MPICXX
#include "hashes.h"
#include "mpi.h"
#include "mpi_message.h"
#include "operations.h"
#include "timeline.h"
/*
* Allreduce, Allgather and Broadcast Ops.
*
* This module implements MPI ops for allgather, allreduce and broadcast, which
* do optimized gathers, reductions and broadcasts and can take advantage of
* hardware-optimized communication libraries through the MPI implementation.
*
* The primary logic of the allreduce, allgather and broadcast are in MPI and
* NCCL implementations. The background thread which facilitates MPI operations
* is run in BackgroundThreadLoop(). The provided ops are:
* – HorovodAllreduce:
* Perform an allreduce on a Tensor, returning the sum
* across all MPI processes in the global communicator.
* – HorovodAllgather:
* Perform an allgather on a Tensor, returning the concatenation of
* the tensor on the first dimension across all MPI processes in the
* global communicator.
* - HorovodBroadcast:
* Perform a broadcast on a Tensor, broadcasting Tensor
* value from root rank to all other ranks.
*
* Additionally, this library provides C APIs to initialize Horovod and query
* rank, local rank and world size. These are used in Python directly through
* ctypes.
*/
namespace horovod {
namespace common {
namespace {
// Table storing Tensors to be reduced, keyed by unique name.
// This table contains everything necessary to do the reduction.
typedef struct {
// Name of the tensor.
std::string tensor_name;
// Operation context.
std::shared_ptr<OpContext> context;
// Input tensor.
std::shared_ptr<Tensor> tensor;
// Pre-allocated output tensor.
std::shared_ptr<Tensor> output;
// Root rank for broadcast operation.
int root_rank;
// Event indicating that data is ready.
std::shared_ptr<ReadyEvent> ready_event;
// GPU to do reduction on, or CPU_DEVICE_ID in case of CPU.
int device;
// A callback to call with the status.
StatusCallback callback;
} TensorTableEntry;
typedef std::unordered_map<std::string, TensorTableEntry> TensorTable;
// Table for storing Tensor metadata on rank zero. This is used for error
// checking, stall checking and size calculations, as well as determining
// when a reduction is ready to be done (when all nodes are ready to do it).
typedef std::unordered_map<
std::string,
std::tuple<std::vector<MPIRequest>, std::chrono::steady_clock::time_point>>
MessageTable;
// The global state required for the MPI ops.
//
// MPI is a library that stores a lot of global per-program state and often
// requires running on a single thread. As a result, we have to have a single
// background thread responsible for all MPI operations, and communicate with
// that background thread through global state.
struct HorovodGlobalState {
// An atomic boolean which is set to true when background thread is started.
// This ensures that only one background thread is spawned.
std::atomic_flag initialize_flag = ATOMIC_FLAG_INIT;
// A mutex that needs to be used whenever MPI operations are done.
std::mutex mutex;
// Tensors waiting to be allreduced or allgathered.
TensorTable tensor_table;
// Queue of MPI requests waiting to be sent to the coordinator node.
std::queue<MPIRequest> message_queue;
// Background thread running MPI communication.
std::thread background_thread;
// Whether the background thread should shutdown.
bool shut_down = false;
// Only exists on the coordinator node (rank zero). Maintains a count of
// 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;
// Time point when coordinator last checked for stalled tensors.
std::chrono::steady_clock::time_point last_stall_check;
// Timeline writer.
Timeline timeline;
// Threshold for Tensor Fusion. All tensors that occupy memory beyond this
// threshold will be fused.
int64_t tensor_fusion_threshold = 64 * 1024 * 1024;
// Background thread cycle time in milliseconds. Fractional numbers are
// permitted.
double cycle_time = 5;
// Time point when last cycle started.
std::chrono::steady_clock::time_point last_cycle_start;
// Memory buffers for Tensor Fusion. They are keyed off device ID and
// framework, and all are allocated tensor_fusion_threshold bytes if
// initialized.
std::unordered_map<std::tuple<int, Framework>,
std::shared_ptr<PersistentBuffer>>
tensor_fusion_buffers;
// Whether MPI_Init has been completed on the background thread.
bool initialization_done = false;
// The MPI rank, local rank, size, local size and flag indicating whether MPI
// multi-threading is supported.
int rank = 0;
int local_rank = 0;
int size = 1;
int local_size = 1;
bool mpi_threads_supported = false;
// Private MPI communicator for Horovod to ensure no collisions with other
// threads using MPI.
MPI_Comm mpi_comm;
// 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
// and kernel executions (for accumulation of values on the GPU). However,
// the subsequent operations must wait for those operations to complete,
// otherwise MPI (which uses its own stream internally) will begin the data
// transfers before the CUDA calls are complete. In order to wait for those
// CUDA operations, if we were using the TensorFlow stream, we would have to
// synchronize that stream; however, other TensorFlow threads may be
// submitting more work to that stream, so synchronizing on it can cause the
// allreduce to be delayed, waiting for compute totally unrelated to it in
// other parts of the graph. Overlaying memory transfers and compute during
// backpropagation is crucial for good performance, so we cannot use the
// TensorFlow stream, and must use our own stream.
#if HAVE_CUDA
std::unordered_map<int, cudaStream_t> streams;
#endif
#if HAVE_NCCL
std::unordered_map<std::vector<int32_t>, ncclComm_t> nccl_comms;
#endif
// We reuse CUDA events as it appears that their creation carries non-zero cost.
// Event management code is only used in NCCL path.
#if HAVE_NCCL
std::unordered_map<int, std::queue<cudaEvent_t>> cuda_events;
std::mutex cuda_events_mutex;
#endif
~HorovodGlobalState() {
// Make sure that the destructor of the background thread is safe to
// call. If a thread is still joinable (not detached or complete) its
// destructor cannot be called.
if (background_thread.joinable()) {
shut_down = true;
background_thread.join();
}
}
};
// All the Horovod state that must be stored globally per-process.
static HorovodGlobalState horovod_global;
// For clarify in argument lists.
#define RANK_ZERO 0
// A tag used for all coordinator messaging.
#define TAG_NOTIFY 1
// Stall-check warning time
#define STALL_WARNING_TIME std::chrono::seconds(60)
static const Status NOT_INITIALIZED_ERROR = Status::PreconditionError(
"Horovod has not been initialized; use hvd.init().");
static const Status SHUT_DOWN_ERROR = Status::Aborted(
"Horovod has been shut down. This has been caused by an exception on one "
"of the rank or an attempt to allreduce, allgather or broadcast a tensor "
"after one of the ranks has finished execution.");
// Store the MPIRequest for a name, and return whether the total count of
// MPIRequests for that tensor is now equal to the MPI size (and thus we are
// ready to reduce the tensor).
bool IncrementTensorCount(std::unique_ptr<MessageTable>& message_table,
MPIRequest msg, int mpi_size) {
auto name = msg.tensor_name();
auto& timeline = horovod_global.timeline;
auto table_iter = message_table->find(name);
if (table_iter == message_table->end()) {
std::vector<MPIRequest> messages = {msg};
auto now = std::chrono::steady_clock::now();
message_table->emplace(name, std::make_tuple(std::move(messages), now));
table_iter = message_table->find(name);
timeline.NegotiateStart(name, msg.request_type());
} else {
std::vector<MPIRequest>& messages = std::get<0>(table_iter->second);
messages.push_back(msg);
}
timeline.NegotiateRankReady(name, msg.request_rank());
std::vector<MPIRequest>& messages = std::get<0>(table_iter->second);
int count = (int)messages.size();
bool ready_to_reduce = count == mpi_size;
if (ready_to_reduce) {
timeline.NegotiateEnd(name);
}
return ready_to_reduce;
}
// Once a tensor is ready to be reduced, the coordinator sends an MPIResponse
// instructing all ranks to start the reduction to all ranks. The MPIResponse
// also contains error messages in case the submitted MPIRequests were not
// valid (for example, contained mismatched shapes or types).
//
// Constructing the MPIResponse, thus, requires a whole lot of error checking.
MPIResponse ConstructMPIResponse(std::unique_ptr<MessageTable>& message_table,
std::string name) {
bool error = false;
auto it = message_table->find(name);
assert(it != message_table->end());
std::vector<MPIRequest>& requests = std::get<0>(it->second);
assert(requests.size() > 0);
std::ostringstream error_message_stream;
// Check that all data types of tensors being reduced, gathered or broadcasted
// are identical.
auto data_type = requests[0].tensor_type();
for (unsigned int i = 1; i < requests.size(); i++) {
auto request_type = requests[i].tensor_type();
if (data_type != request_type) {
error = true;
error_message_stream << "Mismatched data types: One rank had type "
<< MPIDataType_Name(data_type)
<< ", but another rank had type "
<< MPIDataType_Name(request_type) << ".";
break;
}
}
// Check that all requested operations are the same
auto message_type = requests[0].request_type();
for (unsigned int i = 1; i < requests.size(); i++) {
if (error) {
break;
}
auto request_type = requests[i].request_type();
if (message_type != request_type) {
error = true;
error_message_stream << "Mismatched MPI operations: One rank did an "
<< MPIRequest::RequestType_Name(message_type)
<< ", but another rank did an "
<< MPIRequest::RequestType_Name(request_type) << ".";
break;
}
}
// If we are doing an allreduce or broadcast, check that all tensor shapes are
// identical.
if (message_type == MPIRequest::ALLREDUCE ||
message_type == MPIRequest::BROADCAST) {
TensorShape tensor_shape;
for (auto it = requests[0].tensor_shape().begin();
it != requests[0].tensor_shape().end(); it++) {
tensor_shape.AddDim(*it);
}
for (unsigned int i = 1; i < requests.size(); i++) {
if (error) {
break;
}
TensorShape request_shape;
for (auto it = requests[i].tensor_shape().begin();
it != requests[i].tensor_shape().end(); it++) {
request_shape.AddDim(*it);
}
if (tensor_shape != request_shape) {
error = true;
error_message_stream
<< "Mismatched " << MPIRequest::RequestType_Name(message_type)
<< " tensor shapes: One rank sent a tensor of shape "
<< tensor_shape.DebugString()
<< ", but another rank sent a tensor of shape "
<< request_shape.DebugString() << ".";
break;
}
}
}
// If we are doing an allgather, make sure all but the first dimension are
// the same. The first dimension may be different and the output tensor is
// 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 it = requests[0].tensor_shape().begin();
it != requests[0].tensor_shape().end(); it++) {
tensor_shape.AddDim(*it);
}
if (tensor_shape.dims() == 0) {
error = true;
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);
}
for (unsigned int i = 1; i < requests.size(); i++) {
if (error) {
break;
}
TensorShape request_shape;
for (auto it = requests[i].tensor_shape().begin();
it != requests[i].tensor_shape().end(); it++) {
request_shape.AddDim(*it);
}
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 of rank "
<< tensor_shape.dims()
<< ", but another rank sent a tensor of rank "
<< request_shape.dims() << ".";
break;
}
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);
}
}
// If we are doing a broadcast, check that all root ranks are identical.
if (message_type == MPIRequest::BROADCAST) {
int first_root_rank = requests[0].root_rank();
for (unsigned int i = 1; i < requests.size(); i++) {
if (error) {
break;
}
int this_root_rank = requests[i].root_rank();
if (first_root_rank != this_root_rank) {
error = true;
error_message_stream
<< "Mismatched " << MPIRequest::RequestType_Name(message_type)
<< " root ranks: One rank specified root rank " << first_root_rank
<< ", but another rank specified root rank " << this_root_rank
<< ".";
break;
}
}
}
bool first_device_is_cpu = requests[0].device() == CPU_DEVICE_ID;
for (unsigned int i = 1; i < requests.size(); i++) {
if (error) {
break;
}
bool this_device_is_cpu = requests[i].device() == CPU_DEVICE_ID;
if (first_device_is_cpu != this_device_is_cpu) {
error = true;
error_message_stream
<< "Mismatched " << MPIRequest::RequestType_Name(message_type)
<< " CPU/GPU device selection: One rank specified device "
<< (first_device_is_cpu ? "CPU" : "GPU")
<< ", but another rank specified device "
<< (this_device_is_cpu ? "CPU" : "GPU") << ".";
break;
}
}
std::vector<int32_t> devices(requests.size());
for (auto it = requests.begin(); it != requests.end(); it++) {
devices[it->request_rank()] = it->device();
}
MPIResponse response;
response.add_tensor_names(name);
if (error) {
std::string error_message = error_message_stream.str();
response.set_response_type(MPIResponse::ERROR);
response.set_error_message(error_message);
} else if (message_type == MPIRequest::ALLGATHER) {
response.set_response_type(MPIResponse::ALLGATHER);
for (auto dim : tensor_sizes) {
response.add_tensor_sizes(dim);
}
} else if (message_type == MPIRequest::ALLREDUCE) {
response.set_response_type(MPIResponse::ALLREDUCE);
} else if (message_type == MPIRequest::BROADCAST) {
response.set_response_type(MPIResponse::BROADCAST);
}
response.set_devices(devices);
// Clear all queued up requests for this name. They are now taken care of
// by the constructed MPI response.
message_table->erase(it);
return response;
}
MPI_Datatype GetMPIDataType(const std::shared_ptr<Tensor> tensor) {
switch (tensor->dtype()) {
case HOROVOD_UINT8:
return MPI_UINT8_T;
case HOROVOD_INT8:
return MPI_INT8_T;
case HOROVOD_UINT16:
return MPI_UINT16_T;
case HOROVOD_INT16:
return MPI_INT16_T;
case HOROVOD_INT32:
return MPI_INT32_T;
case HOROVOD_INT64:
return MPI_INT64_T;
case HOROVOD_FLOAT32:
return MPI_FLOAT;
case HOROVOD_FLOAT64:
return MPI_DOUBLE;
case HOROVOD_BOOL:
return MPI_C_BOOL;
default:
throw std::logic_error("Type " + MPIDataType_Name(tensor->dtype()) +
" is not supported in MPI mode.");
}
}
#if HAVE_NCCL
ncclDataType_t GetNCCLDataType(const std::shared_ptr<Tensor> tensor) {
switch (tensor->dtype()) {
case HOROVOD_INT32:
return ncclInt32;
case HOROVOD_INT64:
return ncclInt64;
case HOROVOD_FLOAT32:
return ncclFloat32;
case HOROVOD_FLOAT64:
return ncclFloat64;
default:
throw std::logic_error("Type " + MPIDataType_Name(tensor->dtype()) +
" is not supported in NCCL mode.");
}
}
#endif
#define MPI_CHECK(entries, op_name, op) \
{ \
auto mpi_result = (op); \
if (mpi_result != MPI_SUCCESS) { \
for (auto it = entries.begin(); it != entries.end(); it++) { \
timeline.End(it->tensor_name, nullptr); \
it->callback(Status::UnknownError( \
std::string(op_name) + " failed, see MPI output for details.")); \
} \
return; \
} \
}
#define CUDA_CHECK(entries, op_name, op) \
{ \
auto cuda_result = (op); \
if (cuda_result != cudaSuccess) { \
for (auto it = entries.begin(); it != entries.end(); it++) { \
timeline.End(it->tensor_name, nullptr); \
it->callback(Status::UnknownError(std::string(op_name) + " failed: " + \
cudaGetErrorString(cuda_result))); \
} \
return; \
} \
}
#define NCCL_CHECK(entries, op_name, op) \
{ \
auto nccl_result = (op); \
if (nccl_result != ncclSuccess) { \
for (auto it = entries.begin(); it != entries.end(); it++) { \
timeline.End(it->tensor_name, nullptr); \
it->callback(Status::UnknownError(std::string(op_name) + " failed: " + \
ncclGetErrorString(nccl_result))); \
} \
return; \
} \
}
// This event management code is only used in NCCL.
#ifdef HAVE_NCCL
cudaError_t GetCudaEvent(cudaEvent_t* event) {
int device;
auto status = cudaGetDevice(&device);
if (status != cudaSuccess) {
return status;
}
auto& mutex = horovod_global.cuda_events_mutex;
{
std::lock_guard<std::mutex> guard(mutex);
auto& queue = horovod_global.cuda_events[device];
if (!queue.empty()) {
*event = queue.front();
queue.pop();
return cudaSuccess;
}
}
return cudaEventCreateWithFlags(event, cudaEventBlockingSync |
cudaEventDisableTiming);
}
cudaError_t ReleaseCudaEvent(cudaEvent_t event) {
int device;
auto status = cudaGetDevice(&device);
if (status != cudaSuccess) {
return status;
}
auto& mutex = horovod_global.cuda_events_mutex;
{
std::lock_guard<std::mutex> guard(mutex);
auto& queue = horovod_global.cuda_events[device];
queue.push(event);
}
return cudaSuccess;
}
#define RECORD_EVENT(entries, event, stream) \
CUDA_CHECK(entries, "GetCudaEvent", GetCudaEvent(&event)) \
CUDA_CHECK(entries, "cudaEventRecord", cudaEventRecord(event, stream))
#define RELEASE_EVENT(entries, event) \
CUDA_CHECK(entries, "ReleaseCudaEvent", ReleaseCudaEvent(event))
#endif
#define ACTIVITY_START_ALL(entries, timeline, activity) \
{ \
for (auto it = entries.begin(); it != entries.end(); it++) { \
timeline.ActivityStart(it->tensor_name, activity); \
} \
}
#define ACTIVITY_END_ALL(entries, timeline) \
{ \
for (auto it = entries.begin(); it != entries.end(); it++) { \
timeline.ActivityEnd(it->tensor_name); \
} \
}
// Process an MPIResponse by doing a reduction, a gather, a broadcast, or
// raising an error.
void PerformOperation(TensorTable& tensor_table, MPIResponse response) {
std::vector<TensorTableEntry> entries;
{
// Lock on the tensor table.
std::lock_guard<std::mutex> guard(horovod_global.mutex);
for (auto it = response.tensor_names().begin();
it != response.tensor_names().end(); it++) {
// We should never fail at finding this key in the tensor table.
auto name = *it;
auto iter = tensor_table.find(name);
assert(iter != tensor_table.end());
assert(response.response_type() == MPIResponse::ALLREDUCE ||
response.response_type() == MPIResponse::ALLGATHER ||
response.response_type() == MPIResponse::BROADCAST ||
response.response_type() == MPIResponse::ERROR);
entries.push_back(iter->second);
// Clear the tensor table of this tensor and its callbacks; the rest of
// this function takes care of it.
tensor_table.erase(iter);
}
}
auto& timeline = horovod_global.timeline;
for (auto it = entries.begin(); it != entries.end(); it++) {
timeline.Start(it->tensor_name, response.response_type());
}
if (entries.size() > 1) {
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
// end of this operation.
auto& buffer = horovod_global.tensor_fusion_buffers[std::make_tuple(
first_entry.device, first_entry.context->framework())];
if (buffer == nullptr) {
ACTIVITY_START_ALL(entries, timeline, "INIT_FUSION_BUFFER")
// Lazily allocate persistent buffer for Tensor Fusion and keep it
// forever per device.
Status status = first_entry.context->AllocatePersistent(
horovod_global.tensor_fusion_threshold, &buffer);
if (!status.ok()) {
for (auto it = entries.begin(); it != entries.end(); it++) {
timeline.End(it->tensor_name, nullptr);
it->callback(status);
}
return;
}
ACTIVITY_END_ALL(entries, timeline)
}
}
// On GPU data readiness is signalled by ready_event.
std::vector<TensorTableEntry> waiting_tensors;
for (auto it = entries.begin(); it != entries.end(); it++) {
if (it->ready_event != nullptr) {
timeline.ActivityStart(it->tensor_name, "WAIT_FOR_DATA");
waiting_tensors.push_back(*it);
}
}
while (!waiting_tensors.empty()) {
for (auto it = waiting_tensors.begin(); it != waiting_tensors.end();) {
if (it->ready_event->Ready()) {
timeline.ActivityEnd(it->tensor_name);
timeline.ActivityStart(it->tensor_name, "WAIT_FOR_OTHER_TENSOR_DATA");
it = waiting_tensors.erase(it);
} else {
it++;
}
}
std::this_thread::sleep_for(std::chrono::nanoseconds(100));
}
for (auto it = entries.begin(); it != entries.end(); it++) {
if (it->ready_event != nullptr) {
timeline.ActivityEnd(it->tensor_name);
}
}
Status status;
if (response.response_type() == MPIResponse::ALLGATHER) {
assert(entries.size() == 1);
auto e = entries[0];
// Copy tensor sizes from the MPI response into a vector of int64_t
// and compute total size. This is size of first dimension.
std::vector<int64_t> tensor_sizes;
int64_t total_dimension_size = 0;
for (auto it = response.tensor_sizes().begin();
it != response.tensor_sizes().end(); it++) {
tensor_sizes.push_back(*it);
total_dimension_size += *it;
}
// Every tensor participating in Allgather operation may have different
// first dimension size, but the rest of dimensions are same for all
// tensors. Here we get shape of tensor sliced by first dimension.
TensorShape single_slice_shape;
for (int i = 1; i < e.tensor->shape().dims(); i++) {
single_slice_shape.AddDim(e.tensor->shape().dim_size(i));
}
// Allgather output will have shape of:
// (sum of first dimension of every tensor) x (tensor slice shape).
TensorShape output_shape;
output_shape.AddDim((int64_t)total_dimension_size);
output_shape.AppendShape(single_slice_shape);
ACTIVITY_START_ALL(entries, timeline, "ALLOCATE_OUTPUT")
status = e.context->AllocateOutput(output_shape, &e.output);
if (!status.ok()) {
timeline.End(e.tensor_name, nullptr);
e.callback(status);
return;
}
ACTIVITY_END_ALL(entries, timeline)
// Tensors may have different first dimension, so we need to use
// MPI_Allgatherv API that supports gathering arrays of different length.
ACTIVITY_START_ALL(entries, timeline, "MPI_ALLGATHER")
int* recvcounts = new int[tensor_sizes.size()];
int* displcmnts = new int[tensor_sizes.size()];
for (unsigned int i = 0; i < tensor_sizes.size(); i++) {
recvcounts[i] =
(int)(single_slice_shape.num_elements() * tensor_sizes[i]);
if (i == 0) {
displcmnts[i] = 0;
} else {
displcmnts[i] = recvcounts[i - 1] + displcmnts[i - 1];
}
}
auto result = MPI_Allgatherv(
e.tensor->data(), (int)e.tensor->shape().num_elements(),
GetMPIDataType(e.tensor), (void*)e.output->data(), recvcounts,
displcmnts, GetMPIDataType(e.tensor), horovod_global.mpi_comm);
delete[] recvcounts;
delete[] displcmnts;
MPI_CHECK(entries, "MPI_Allgatherv", result)
ACTIVITY_END_ALL(entries, timeline)
timeline.End(e.tensor_name, e.output);
e.callback(Status::OK());
} else if (response.response_type() == MPIResponse::ALLREDUCE) {
auto first_entry = entries[0];
#if HAVE_CUDA
bool on_gpu = first_entry.device != CPU_DEVICE_ID;
if (on_gpu) {
CUDA_CHECK(entries, "cudaSetDevice", cudaSetDevice(first_entry.device))
// Ensure stream is in the map before executing reduction.
cudaStream_t& stream = horovod_global.streams[first_entry.device];
if (stream == nullptr) {
int greatest_priority;
CUDA_CHECK(entries, "cudaDeviceGetStreamPriorityRange",
cudaDeviceGetStreamPriorityRange(NULL, &greatest_priority))
CUDA_CHECK(entries, "cudaStreamCreateWithPriority",
cudaStreamCreateWithPriority(&stream, cudaStreamNonBlocking,
greatest_priority))
}
}
#endif
#if HOROVOD_GPU_ALLREDUCE == 'N' // 'N' stands for NCCL
if (on_gpu) {
auto stream = horovod_global.streams[first_entry.device];
// Ensure NCCL communicator is in the map before executing reduction.
ncclComm_t& nccl_comm = horovod_global.nccl_comms[response.devices()];
if (nccl_comm == nullptr) {
ACTIVITY_START_ALL(entries, timeline, "INIT_NCCL")
ncclUniqueId nccl_id;
if (horovod_global.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.mpi_comm));
ncclComm_t new_nccl_comm;
NCCL_CHECK(entries, "ncclCommInitRank",
ncclCommInitRank(&new_nccl_comm, horovod_global.size,
nccl_id, horovod_global.rank))
nccl_comm = new_nccl_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)
}
ACTIVITY_START_ALL(entries, timeline, "SCHEDULE")
cudaEvent_t queue_end_event = nullptr;
if (timeline.Initialized()) {
RECORD_EVENT(entries, queue_end_event, stream);
}
cudaEvent_t after_memcpy_in_event = nullptr;
cudaEvent_t after_reduce_event = nullptr;
cudaEvent_t after_memcpy_out_event = nullptr;
if (entries.size() > 1) {
// Access the fusion buffer.
auto& buffer = horovod_global.tensor_fusion_buffers[std::make_tuple(
first_entry.device, first_entry.context->framework())];
auto buffer_data = buffer->AccessData(first_entry.context);
// Copy memory into the fusion buffer.
int64_t offset = 0;
for (auto it = entries.begin(); it != entries.end(); it++) {
void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
CUDA_CHECK(entries, "cudaMemcpyAsync",
cudaMemcpyAsync(buffer_data_at_offset, it->tensor->data(),
(size_t)it->tensor->size(),
cudaMemcpyDeviceToDevice, stream))
offset += it->tensor->size();
}
if (timeline.Initialized()) {
RECORD_EVENT(entries, after_memcpy_in_event, stream)
}
// Perform the reduction on the fusion buffer.
int64_t num_elements = 0;
for (auto it = entries.begin(); it != entries.end(); it++) {
num_elements += it->tensor->shape().num_elements();
}
NCCL_CHECK(entries, "ncclAllReduce",
ncclAllReduce(buffer_data, (void*)buffer_data,
(size_t)num_elements,
GetNCCLDataType(first_entry.tensor), ncclSum,
nccl_comm, stream))
if (timeline.Initialized()) {
RECORD_EVENT(entries, after_reduce_event, stream)
}
// Copy memory out of the fusion buffer.
offset = 0;
for (auto it = entries.begin(); it != entries.end(); it++) {
void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
CUDA_CHECK(entries, "cudaMemcpyAsync",
cudaMemcpyAsync((void*)it->output->data(),
buffer_data_at_offset,
(size_t)it->tensor->size(),
cudaMemcpyDeviceToDevice, stream))
offset += it->tensor->size();
}
if (timeline.Initialized()) {
RECORD_EVENT(entries, after_memcpy_out_event, stream)
}
} else {
auto e = first_entry;
NCCL_CHECK(entries, "ncclAllReduce",
ncclAllReduce(e.tensor->data(), (void*)e.output->data(),
(size_t)e.tensor->shape().num_elements(),
GetNCCLDataType(first_entry.tensor), ncclSum,
nccl_comm, stream))
if (timeline.Initialized()) {
RECORD_EVENT(entries, after_reduce_event, stream)
}
}
ACTIVITY_END_ALL(entries, timeline)
ACTIVITY_START_ALL(entries, timeline, "QUEUE")
// Use completion marker via event because it's faster than
// blocking cudaStreamSynchronize() in this thread.
cudaEvent_t done_event;
RECORD_EVENT(entries, done_event, stream)
// TODO: use thread pool or single thread for callbacks
std::thread finalizer_thread([entries, first_entry, done_event,
queue_end_event, after_memcpy_in_event,
after_reduce_event, after_memcpy_out_event,
response, &timeline] {
CUDA_CHECK(entries, "cudaSetDevice", cudaSetDevice(first_entry.device))
if (queue_end_event != nullptr) {
CUDA_CHECK(entries, "cudaEventSynchronize",
cudaEventSynchronize(queue_end_event))
// All the work scheduled on NCCL stream before this allreduce
// is done at this point, end queueing activity.
ACTIVITY_END_ALL(entries, timeline)
RELEASE_EVENT(entries, queue_end_event);
}
if (after_memcpy_in_event != nullptr) {
ACTIVITY_START_ALL(entries, timeline, "MEMCPY_IN_FUSION_BUFFER")
CUDA_CHECK(entries, "cudaEventSynchronize",
cudaEventSynchronize(after_memcpy_in_event))
// The memcpy into the fusion buffer is done after this point has been
// reached.
ACTIVITY_END_ALL(entries, timeline)
RELEASE_EVENT(entries, after_memcpy_in_event);
}
if (after_reduce_event != nullptr) {
ACTIVITY_START_ALL(entries, timeline, "NCCL_ALLREDUCE")
CUDA_CHECK(entries, "cudaEventSynchronize",
cudaEventSynchronize(after_reduce_event))
// The allreduce is done after this point has been reached.
ACTIVITY_END_ALL(entries, timeline)
RELEASE_EVENT(entries, after_reduce_event);
}
if (after_memcpy_out_event != nullptr) {
ACTIVITY_START_ALL(entries, timeline, "MEMCPY_OUT_FUSION_BUFFER")
CUDA_CHECK(entries, "cudaEventSynchronize",
cudaEventSynchronize(after_memcpy_out_event))
// The memcpy out of the fusion buffer is done after this point has
// been reached.
ACTIVITY_END_ALL(entries, timeline)
RELEASE_EVENT(entries, after_memcpy_out_event);
}
CUDA_CHECK(entries, "cudaEventSynchronize",
cudaEventSynchronize(done_event))
for (auto it = entries.begin(); it != entries.end(); it++) {
timeline.End(it->tensor_name, it->output);
it->callback(Status::OK());
}
RELEASE_EVENT(entries, done_event);
});
finalizer_thread.detach();
return;
}
#endif
if (entries.size() > 1) {
// Access the fusion buffer.
auto& buffer = horovod_global.tensor_fusion_buffers[std::make_tuple(
first_entry.device, first_entry.context->framework())];
auto buffer_data = buffer->AccessData(first_entry.context);
// Copy memory into the fusion buffer.
ACTIVITY_START_ALL(entries, timeline, "MEMCPY_IN_FUSION_BUFFER")
int64_t offset = 0;
for (auto it = entries.begin(); it != entries.end(); it++) {
void* buffer_data_at_offset = (uint8_t*)buffer_data + offset;
#if HAVE_CUDA
if (on_gpu) {
CUDA_CHECK(entries, "cudaMemcpyAsync",
cudaMemcpyAsync(
buffer_data_at_offset, it->tensor->data(),
(size_t)it->tensor->size(), cudaMemcpyDeviceToDevice,
horovod_global.streams[first_entry.device]))
} else {
#endif
std::memcpy(buffer_data_at_offset, it->tensor->data(),
(size_t)it->tensor->size());
#if HAVE_CUDA
}
#endif
offset += it->tensor->size();
}
#if HAVE_CUDA
if (on_gpu) {
CUDA_CHECK(
entries, "cudaStreamSynchronize",
cudaStreamSynchronize(horovod_global.streams[first_entry.device]))
}
#endif
ACTIVITY_END_ALL(entries, timeline)
ACTIVITY_START_ALL(entries, timeline, "MPI_ALLREDUCE")
int64_t num_elements = 0;
for (auto it = entries.begin(); it != entries.end(); it++) {
num_elements += it->tensor->shape().num_elements();
}
MPI_CHECK(entries, "MPI_Allreduce",
MPI_Allreduce(MPI_IN_PLACE, (void*)buffer_data,
(int)num_elements,
GetMPIDataType(first_entry.tensor), MPI_SUM,
horovod_global.mpi_comm))