forked from horovod/horovod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operations.cc
2594 lines (2286 loc) · 99.1 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) 2019 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>
#include <unordered_set>
#if HAVE_CUDA
#include <cuda_runtime.h>
#endif
#if HAVE_NCCL
#include <nccl.h>
#endif
#if HAVE_DDL
#include <ddl.hpp>
#endif
#define OMPI_SKIP_MPICXX
#include "fusion_buffer_manager.h"
#include "half.h"
#include "hashes.h"
#include "mpi.h"
#include "message.h"
#include "operations.h"
#include "parameter_manager.h"
#include "timeline.h"
#include "logging.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.
struct TensorTableEntry {
// 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 = 0;
// 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 = CPU_DEVICE_ID;
// A callback to call with the status.
StatusCallback callback;
};
using TensorTable = std::unordered_map<std::string, TensorTableEntry>;
// 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).
using MessageTable = std::unordered_map<
std::string,
std::tuple<std::vector<Request>, std::chrono::steady_clock::time_point>>;
// 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 requests waiting to be sent to the coordinator node.
std::queue<Request> message_queue;
// Background thread running MPI communication.
std::thread background_thread;
// Whether the background thread should shutdown.
std::atomic_bool shut_down{false};
// Whether Horovod should finalize MPI (only if it has initialized it).
bool should_finalize = 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;
// Flag indicating whether to perform stall tensor check.
bool perform_stall_check = true;
// Timeline writer.
Timeline timeline;
// Flag indicating whether to mark cycles in the timeline.
bool mark_cycles_in_timeline = false;
ParameterManager param_manager;
// Encapsulates the fusion buffers, handles resizing and auto-tuning of buffer
// size.
FusionBufferManager fusion_buffer;
// Time point when last cycle started.
std::chrono::steady_clock::time_point last_cycle_start;
// Whether MPI_Init has been completed on the background thread.
std::atomic_bool initialization_done{false};
// The MPI rank, local rank, size, local size, flag indicating whether MPI
// multi-threading is supported, ranks from which the MPI communicator will
// be made and the communicator itself.
int rank = 0;
int local_rank = 0;
int cross_rank = 0;
int size = 1;
int local_size = 1;
int cross_size = 1;
bool mpi_threads_supported = false;
bool is_homogeneous = false;
std::vector<int> ranks;
// COMM_WORLD ranks of processes running on this node.
std::vector<int> local_comm_ranks;
// Numbers of ranks running per node
std::vector<int> local_sizes;
// MPI custom data type for float16.
MPI_Datatype mpi_float16_t;
MPI_Op mpi_float16_sum;
// Private MPI communicator for Horovod to ensure no collisions with other
// threads using MPI.
MPI_Comm mpi_comm;
// Node-local communicator.
MPI_Comm local_comm;
// Cross-node communicator for hierarchical allreduce.
MPI_Comm cross_comm;
// MPI Window used for shared memory allgather
MPI_Win window;
// Pointer to shared buffer for allgather
void* shared_buffer = nullptr;
// Current shared buffer size
int64_t shared_buffer_size = 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
// 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
// Will be set to true after initialization when ddl is used
bool ddl_initialized = false;
int32_t ddl_local_device_id = 0;
// We reuse CUDA events as it appears that their creation carries non-zero cost.
#if HAVE_CUDA
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.
HorovodGlobalState horovod_global;
// For clarify in argument lists.
#define RANK_ZERO 0
// Stall-check warning time
#define STALL_WARNING_TIME std::chrono::seconds(60)
const Status NOT_INITIALIZED_ERROR = Status::PreconditionError(
"Horovod has not been initialized; use hvd.init().");
const Status SHUT_DOWN_ERROR = Status::UnknownError(
"Horovod has been shut down. This was caused by an exception on one of the "
"ranks or an attempt to allreduce, allgather or broadcast a tensor after "
"one of the ranks finished execution. If the shutdown was caused by an "
"exception, you should see the exception in the log before the first "
"shutdown message.");
const Status DUPLICATE_NAME_ERROR = Status::InvalidArgument(
"Requested to allreduce, allgather, or broadcast a tensor with the same "
"name as another tensor that is currently being processed. If you want "
"to request another tensor, use a different tensor name.");
#define OP_ERROR(entries, error_message) \
{ \
for (auto& e : (entries)) { \
timeline.End(e.tensor_name, nullptr); \
e.callback(Status::UnknownError(error_message)); \
} \
return; \
}
// Store the Request for a name, and return whether the total count of
// Requests 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,
const Request& 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<Request> messages = {msg};
messages.reserve(static_cast<unsigned long>(mpi_size));
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<Request>& messages = std::get<0>(table_iter->second);
messages.push_back(msg);
}
timeline.NegotiateRankReady(name, msg.request_rank());
std::vector<Request>& 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 a Response
// instructing all ranks to start the reduction to all ranks. The Response
// also contains error messages in case the submitted Requests were not
// valid (for example, contained mismatched shapes or types).
//
// Constructing the Response, thus, requires a whole lot of error checking.
Response ConstructResponse(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<Request>& 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 "
<< DataType_Name(data_type)
<< ", but another rank had type "
<< DataType_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 "
<< Request::RequestType_Name(message_type)
<< ", but another rank did an "
<< Request::RequestType_Name(request_type) << ".";
break;
}
}
// If we are doing an allreduce or broadcast, check that all tensor shapes are
// identical.
if (message_type == Request::ALLREDUCE ||
message_type == Request::BROADCAST) {
TensorShape tensor_shape;
for (auto dim : requests[0].tensor_shape()) {
tensor_shape.AddDim(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 != request_shape) {
error = true;
error_message_stream
<< "Mismatched " << Request::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 == Request::ALLGATHER) {
TensorShape tensor_shape;
for (auto dim : requests[0].tensor_shape()) {
tensor_shape.AddDim(dim);
}
if (tensor_shape.dims() == 0) {
error = true;
error_message_stream << "Rank zero tried to "
<< Request::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 dim : requests[i].tensor_shape()) {
request_shape.AddDim(dim);
}
if (tensor_shape.dims() != request_shape.dims()) {
error = true;
error_message_stream
<< "Mismatched " << Request::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 " << Request::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 == Request::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 " << Request::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 " << Request::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& request : requests) {
devices[request.request_rank()] = request.device();
}
Response response;
response.add_tensor_name(name);
if (error) {
std::string error_message = error_message_stream.str();
response.set_response_type(Response::ERROR);
response.set_error_message(error_message);
} else if (message_type == Request::ALLGATHER) {
response.set_response_type(Response::ALLGATHER);
for (auto dim : tensor_sizes) {
response.add_tensor_size(dim);
}
} else if (message_type == Request::ALLREDUCE) {
response.set_response_type(Response::ALLREDUCE);
} else if (message_type == Request::BROADCAST) {
response.set_response_type(Response::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_FLOAT16:
return horovod_global.mpi_float16_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 " + DataType_Name(tensor->dtype()) +
" is not supported in MPI mode.");
}
}
// Return the total byte size of the final allgathered output tensor
int64_t TotalByteSizeOfAllgatherOutput(const std::vector<int64_t> &tensor_sizes,
const TensorTableEntry entry) {
int64_t total_dimension_size = 0;
for (auto sz : tensor_sizes) {
total_dimension_size += sz;
}
// 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. Allgather output will have shape of: (sum of first
// dimension of every tensor) x (tensor slice shape).
int64_t total_count_of_output_entries = total_dimension_size;
for (int i = 1; i < entry.tensor->shape().dims(); ++i) {
total_count_of_output_entries *= entry.tensor->shape().dim_size(i);
}
int element_size;
MPI_Type_size(GetMPIDataType(entry.tensor), &element_size);
int64_t total_byte_size_of_output =
total_count_of_output_entries * element_size;
return total_byte_size_of_output;
}
#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_FLOAT16:
return ncclFloat16;
case HOROVOD_FLOAT32:
return ncclFloat32;
case HOROVOD_FLOAT64:
return ncclFloat64;
default:
throw std::logic_error("Type " + DataType_Name(tensor->dtype()) +
" is not supported in NCCL mode.");
}
}
#endif
#if HAVE_DDL
DDL_Type GetDDLDataType(const std::shared_ptr<Tensor> tensor) {
switch (tensor->dtype()) {
case HOROVOD_FLOAT32:
return DDL_TYPE_FLOAT;
default:
throw std::logic_error("Type " + DataType_Name(tensor->dtype()) +
" is not supported in DDL mode.");
}
}
#endif
#define MPI_CHECK(entries, op_name, op) \
{ \
auto mpi_result = (op); \
if (mpi_result != MPI_SUCCESS) { \
for (auto& e : (entries)) { \
timeline.End(e.tensor_name, nullptr); \
e.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& e : (entries)) { \
timeline.End(e.tensor_name, nullptr); \
e.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& e : (entries)) { \
timeline.End(e.tensor_name, nullptr); \
e.callback(Status::UnknownError(std::string(op_name) + " failed: " + \
ncclGetErrorString(nccl_result))); \
} \
return; \
} \
}
#define DDL_CHECK(entries, op_name, op) \
{ \
auto ddl_result = (op); \
if (ddl_result != DDL_SUCCESS) { \
for (auto& e : (entries)) { \
timeline.End(e.tensor_name, nullptr); \
e.callback(Status::UnknownError(std::string(op_name) + " failed.")); \
} \
return; \
} \
}
// This event management code is only used with CUDA
#if HAVE_CUDA
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_queue, name, stream) \
{ \
cudaEvent_t event; \
CUDA_CHECK(entries, "GetCudaEvent", GetCudaEvent(&event)) \
CUDA_CHECK(entries, "cudaEventRecord", cudaEventRecord(event, stream)) \
(event_queue).emplace(name, event); \
}
#define WAIT_FOR_EVENTS(entries, timeline, event_queue) \
{ \
while (!(event_queue).empty()) { \
std::string name; \
cudaEvent_t event; \
std::tie(name, event) = (event_queue).front(); \
(event_queue).pop(); \
if (name != "") { \
ACTIVITY_START_ALL(entries, timeline, name) \
} \
CUDA_CHECK(entries, "cudaEventSynchronize", cudaEventSynchronize(event)) \
if (name != "") { \
ACTIVITY_END_ALL(entries, timeline) \
} \
CUDA_CHECK(entries, "ReleaseCudaEvent", ReleaseCudaEvent(event)) \
} \
}
#endif
#define ACTIVITY_START_ALL(entries, timeline, activity) \
{ \
for (auto& e : (entries)) { \
(timeline).ActivityStart(e.tensor_name, activity); \
} \
}
#define ACTIVITY_END_ALL(entries, timeline) \
{ \
for (auto& e : (entries)) { \
(timeline).ActivityEnd(e.tensor_name); \
} \
}
int64_t TensorFusionThresholdBytes() {
int64_t proposed_fusion_threshold =
horovod_global.param_manager.TensorFusionThresholdBytes();
// If the cluster is homogeneous and hierarchical allreduce is enabled,
// adjust buffer size to make sure it is divisible by local_size to improve
// performance.
if (horovod_global.is_homogeneous &&
horovod_global.param_manager.HierarchicalAllreduce()) {
// Assume the worst-case data type float64, since if it is divisible with
// float64, it will be divisible for other types too.
// Ensuring that fusion buffer can hold a number of elements divisible by
// FUSION_BUFFER_ATOMIC_UNIT for performance
int mpi_double_size;
MPI_Type_size(MPI_DOUBLE, &mpi_double_size);
int64_t div =
horovod_global.local_size * mpi_double_size * FUSION_BUFFER_ATOMIC_UNIT;
return ((proposed_fusion_threshold + div - 1) / div) * div;
}
return proposed_fusion_threshold;
}
// Process a Response by doing a reduction, a gather, a broadcast, or
// raising an error.
void PerformOperation(TensorTable& tensor_table, Response response) {
std::vector<TensorTableEntry> entries;
// Reserve to save re-allocation costs, as we know the size before.
entries.reserve(response.tensor_names().size());
{
// Lock on the tensor table.
std::lock_guard<std::mutex> guard(horovod_global.mutex);
for (auto& name : response.tensor_names()) {
// We should never fail at finding this key in the tensor table.
auto iter = tensor_table.find(name);
assert(iter != tensor_table.end());
assert(response.response_type() == Response::ALLREDUCE ||
response.response_type() == Response::ALLGATHER ||
response.response_type() == Response::BROADCAST ||
response.response_type() == Response::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& e : entries) {
timeline.Start(e.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.
Status status = horovod_global.fusion_buffer.InitializeBuffer(
TensorFusionThresholdBytes(), first_entry.device, first_entry.context,
[&]() { ACTIVITY_START_ALL(entries, timeline, INIT_FUSION_BUFFER) },
[&]() { ACTIVITY_END_ALL(entries, timeline) });
if (!status.ok()) {
for (auto& e : entries) {
timeline.End(e.tensor_name, nullptr);
e.callback(status);
}
return;
}
}
// On GPU data readiness is signalled by ready_event.
std::vector<TensorTableEntry> waiting_tensors;
for (auto& e : entries) {
if (e.ready_event != nullptr) {
timeline.ActivityStart(e.tensor_name, WAIT_FOR_DATA);
waiting_tensors.push_back(e);
}
}
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& e : entries) {
if (e.ready_event != nullptr) {
timeline.ActivityEnd(e.tensor_name);
}
}
Status status;
if (response.response_type() == Response::ALLGATHER) {
// Sizes of subcomponents of each entry from all ranks
auto** entry_component_sizes = new int64_t*[entries.size()];
// Offset of each subcomponent of every entry in the final buffer after
// allgatherv
auto** entry_component_offsets = new int64_t*[entries.size()];
auto* recvcounts = new int[horovod_global.size]();
auto* displcmnts = new int[horovod_global.size]();
for (size_t ec = 0; ec < entries.size(); ++ec) {
entry_component_sizes[ec] = new int64_t[horovod_global.size]();
entry_component_offsets[ec] = new int64_t[horovod_global.size]();
}
auto& first_entry = entries[0];
ACTIVITY_START_ALL(entries, timeline, ALLOCATE_OUTPUT)
for (size_t ec = 0; ec < entries.size(); ++ec) {
auto& e = entries[ec];
// 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));
}
// Copy tensor sizes from the Response into a vector of int64_t
// and compute total size. This is size of first dimension.
int64_t total_entry_dimension_size = 0;
for (int rc = 0; rc < horovod_global.size; ++rc) {
auto component_size =
response.tensor_sizes()[ec * horovod_global.size + rc];
total_entry_dimension_size += component_size;
recvcounts[rc] += component_size * single_slice_shape.num_elements();
entry_component_sizes[ec][rc] =
component_size * single_slice_shape.num_elements();
}
// 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_entry_dimension_size);
output_shape.AppendShape(single_slice_shape);
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)
for (int rc = 0; rc < horovod_global.size; ++rc) {
if (rc == 0) {
displcmnts[rc] = 0;
} else {
displcmnts[rc] = displcmnts[rc - 1] + recvcounts[rc - 1];
}
}
unsigned int rank_displacement = 0;
for (int rc = 0; rc < horovod_global.size; ++rc) {
for (size_t ec = 0; ec < entries.size(); ++ec) {
if (ec == 0) {
entry_component_offsets[ec][rc] = rank_displacement;
} else {
entry_component_offsets[ec][rc] =
entry_component_offsets[ec - 1][rc] +
entry_component_sizes[ec - 1][rc];
}
}
rank_displacement += recvcounts[rc];
}
int element_size;
MPI_Type_size(GetMPIDataType(first_entry.tensor), &element_size);
int64_t total_size = displcmnts[horovod_global.size - 1] +
recvcounts[horovod_global.size - 1];
int64_t total_size_in_bytes = total_size * element_size;
#if HOROVOD_GPU_ALLGATHER != 'M' // 'M' stands for MPI
if (horovod_global.param_manager.HierarchicalAllgather()) {
// If shared buffer is not initialized or is not large enough, reallocate
if (horovod_global.shared_buffer == nullptr ||
horovod_global.shared_buffer_size < total_size_in_bytes) {
if (horovod_global.shared_buffer != nullptr) {
MPI_Win_fence(0, horovod_global.window);
MPI_Win_free(&horovod_global.window);
horovod_global.shared_buffer = nullptr;
}
int64_t window_size =
horovod_global.local_rank == 0 ? total_size_in_bytes : 0;
// Allocate shared memory, give each rank their respective pointer
ACTIVITY_START_ALL(entries, timeline, ALLOCATE_SHARED_BUFFER)
MPI_Win_allocate_shared(
window_size, element_size, MPI_INFO_NULL, horovod_global.local_comm,
&horovod_global.shared_buffer, &horovod_global.window);
if (horovod_global.local_rank != 0) {
int disp_unit;
MPI_Aint winsize;
MPI_Win_shared_query(horovod_global.window, 0, &winsize, &disp_unit,
&horovod_global.shared_buffer);
}
horovod_global.shared_buffer_size = total_size_in_bytes;
ACTIVITY_END_ALL(entries, timeline)
}
// Compute cross-node allgather displacements and recvcounts for
// homogeneous/parallelized case
auto* cross_recvcounts = new int[horovod_global.cross_size]();
auto* cross_displcmnts = new int[horovod_global.cross_size]();
if (horovod_global.is_homogeneous) {
for (int i = 0; i < horovod_global.cross_size; ++i) {
cross_recvcounts[i] = recvcounts[horovod_global.local_size * i +
horovod_global.local_rank];
cross_displcmnts[i] = displcmnts[horovod_global.local_size * i +
horovod_global.local_rank];
}
} else if (horovod_global.local_rank == 0) {
// In this case local rank 0 will allgather with all local data
int offset = 0;
for (int i = 0; i < horovod_global.cross_size; ++i) {
for (int j = offset; j < offset + horovod_global.local_sizes[i];
++j) {
cross_recvcounts[i] += recvcounts[j];
}
cross_displcmnts[i] = displcmnts[offset];
offset += horovod_global.local_sizes[i];
}
}
ACTIVITY_START_ALL(entries, timeline, MEMCPY_IN_SHARED_BUFFER)
for (size_t ec = 0; ec < entries.size(); ++ec) {
auto& e = entries[ec];
void* shared_buffer_at_offset =
(uint8_t*)horovod_global.shared_buffer +
entry_component_offsets[ec][horovod_global.rank] * element_size;
// CPU copy to shared buffer
memcpy(shared_buffer_at_offset, e.tensor->data(),
(size_t)(entry_component_sizes[ec][horovod_global.rank] *
element_size));
}
MPI_CHECK(entries, "MPI_Barrier", MPI_Barrier(horovod_global.mpi_comm));
ACTIVITY_END_ALL(entries, timeline)
// Perform the cross-node allgather. If the cluster is homogeneous all
// local ranks participate, otherwise local rank 0 handles all data
ACTIVITY_START_ALL(entries, timeline, MPI_CROSS_ALLGATHER)