-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathTransferBench.hpp
More file actions
7322 lines (6512 loc) · 282 KB
/
TransferBench.hpp
File metadata and controls
7322 lines (6512 loc) · 282 KB
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 (c) Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/// @cond
#pragma once
#include <algorithm>
#include <arpa/inet.h>
#include <atomic>
#include <barrier>
#include <cstring>
#include <fcntl.h>
#include <filesystem>
#include <fstream>
#include <functional>
#include <future>
#include <map>
#include <mutex>
#include <netinet/in.h>
#include <numa.h> // If not found, try installing libnuma-dev (e.g apt-get install libnuma-dev)
#include <numaif.h>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <thread>
#include <unistd.h>
#include <vector>
#ifdef NIC_EXEC_ENABLED
#include <infiniband/verbs.h>
#if IBV_DIRECT
#define IBV_FN(name, rettype, arglist) constexpr rettype(*pfn_##name)arglist = name;
#else
#include <dlfcn.h>
#define IBV_FN(name, rettype, arglist) rettype(*pfn_##name)arglist = nullptr;
#endif
#endif
#ifdef MPI_COMM_ENABLED
#include <mpi.h>
#endif
#if defined(__NVCC__)
#include <cuda.h>
#include <cuda_runtime.h>
#ifdef NVML_ENABLED
#include <nvml.h>
#endif
#else
#include "hip/hip_ext.h"
#include "hip/hip_runtime.h"
#include "hsa/hsa.h"
#include "hsa/hsa_ext_amd.h"
#ifdef AMD_SMI_ENABLED
#include "amd_smi/amdsmi.h"
#endif
#endif
/// @endcond
namespace TransferBench
{
using std::map;
using std::pair;
using std::set;
using std::vector;
constexpr char VERSION[] = "1.67";
/**
* Enumeration of supported Executor types
*
* @note The Executor is the device used to perform a Transfer
*/
enum ExeType
{
EXE_CPU = 0, ///< CPU executor (subExecutor = CPU thread)
EXE_GPU_GFX = 1, ///< GPU kernel-based executor (subExecutor = threadblock/CU)
EXE_GPU_DMA = 2, ///< GPU SDMA executor (subExecutor = not supported)
EXE_NIC = 3, ///< NIC RDMA executor (subExecutor = queue pair)
EXE_NIC_NEAREST = 4 ///< NIC RDMA nearest executor (subExecutor = queue pair)
};
char const ExeTypeStr[6] = "CGDIN";
inline bool IsCpuExeType(ExeType e){ return e == EXE_CPU; }
inline bool IsGpuExeType(ExeType e){ return e == EXE_GPU_GFX || e == EXE_GPU_DMA; }
inline bool IsNicExeType(ExeType e){ return e == EXE_NIC || e == EXE_NIC_NEAREST; }
/**
* A ExeDevice defines a specific Executor
*/
struct ExeDevice
{
ExeType exeType; ///< Executor type
int32_t exeIndex; ///< Executor index
int32_t exeRank = 0; ///< Executor rank
int32_t exeSlot = 0; ///< Executor slot
bool operator<(ExeDevice const& other) const {
return ((exeRank != other.exeRank) ? (exeRank < other.exeRank) :
(exeType != other.exeType) ? (exeType < other.exeType) :
(exeIndex != other.exeIndex) ? (exeIndex < other.exeIndex) :
(exeSlot < other.exeSlot));
}
};
/**
* Enumeration of supported memory types
*
* @note These are possible types of memory to be used as sources/destinations
*/
enum MemType
{
MEM_CPU = 0, ///< Default pinned CPU memory (via hipHostMalloc)
MEM_CPU_CLOSEST = 1, ///< Default pinned CPU memory (indexed by closest GPU)
MEM_CPU_COHERENT = 2, MEM_CPU_FINE = 2, ///< Coherent pinned CPU memory (via hipHostMallocCoherent flag)
MEM_CPU_NONCOHERENT = 3, ///< Noncoherent pinned CPU memory (via hipHostMallocNonCoherent flag)
MEM_CPU_UNCACHED = 4, ///< Uncached pinned CPU memory (via hipHostMallocUncached flag)
MEM_CPU_UNPINNED = 5, ///< Unpinned CPU memory
MEM_GPU = 6, ///< Default GPU memory (via hipMalloc)
MEM_GPU_FINE = 7, ///< Fine-grained GPU memory (via hipDeviceMallocFinegrained flag)
MEM_GPU_UNCACHED = 8, ///< Uncached GPU memory (via hipDeviceMallocUncached flag)
MEM_MANAGED = 9, ///< Managed memory
MEM_NULL = 10, ///< NULL memory - used for empty
};
char const MemTypeStr[12] = "CPBDKHGFUMN";
inline bool IsCpuMemType(MemType m) { return (MEM_CPU <= m && m <= MEM_CPU_UNPINNED);}
inline bool IsGpuMemType(MemType m) { return (MEM_GPU <= m && m <= MEM_MANAGED);}
/**
* A MemDevice indicates a memory type on a specific device
*/
struct MemDevice
{
MemType memType; ///< Memory type
int32_t memIndex; ///< Device index
int32_t memRank = 0; ///< Rank index
bool operator<(MemDevice const& other) const {
return ((memType != other.memType) ? (memType < other.memType) :
(memIndex != other.memIndex) ? (memIndex < other.memIndex) :
(memRank < other.memRank));
}
bool operator==(MemDevice const& other) const {
return (memType == other.memType &&
memIndex == other.memIndex &&
memRank == other.memRank);
}
};
/**
* A Transfer adds together data from zero or more sources then writes the sum to zero or more desintations
*/
struct Transfer
{
size_t numBytes = 0; ///< Number of bytes to Transfer
vector<MemDevice> srcs = {}; ///< List of source memory devices
vector<MemDevice> dsts = {}; ///< List of destination memory devices
ExeDevice exeDevice = {}; ///< Executor to use
int32_t exeSubIndex = -1; ///< Executor subindex
int32_t exeSubSlot = 0; ///< Executor subslot
int numSubExecs = 0; ///< Number of subExecutors to use for this Transfer
};
/**
* General options
*/
struct GeneralOptions
{
int numIterations = 10; ///< Number of timed iterations to perform. If negative, run for -numIterations seconds instead
int numSubIterations = 1; ///< Number of sub-iterations per iteration
int numWarmups = 3; ///< Number of un-timed warmup iterations to perform
int recordPerIteration = 0; ///< Record per-iteration timing information
int useInteractive = 0; ///< Pause for user-input before starting transfer loop
};
/**
* Data options
*/
struct DataOptions
{
int alwaysValidate = 0; ///< Validate after each iteration instead of once at end
int blockBytes = 256; ///< Each subexecutor works on a multiple of this many bytes
int byteOffset = 0; ///< Byte-offset for memory allocations
vector<float> fillPattern = {}; ///< Pattern of floats used to fill source data
vector<int> fillCompress = {}; ///< Customized data patterns (overrides fillPattern if non-empty)
int validateDirect = 0; ///< Validate GPU results directly instead of copying to host
int validateSource = 0; ///< Validate src GPU memory immediately after preparation
};
/**
* GFX Executor options
*/
struct GfxOptions
{
int blockOrder = 0; ///< Determines how threadblocks are ordered (0=sequential, 1=interleaved, 2=random)
int blockSize = 256; ///< Size of each threadblock (must be multiple of 64)
vector<uint32_t> cuMask = {}; ///< Bit-vector representing the CU mask
vector<vector<int>> prefXccTable = {}; ///< 2D table with preferred XCD to use for a specific [src][dst] GPU device
int seType = 0; ///< SubExecutor granularity type (0=threadblock, 1=warp)
int temporalMode = 0; ///< Non-temporal load/store mode 0=none, 1=load, 2=store, 3=both
int unrollFactor = 4; ///< GFX-kernel unroll factor
int useHipEvents = 1; ///< Use HIP events for timing GFX Executor
int useMultiStream = 0; ///< Use multiple streams for GFX
int useSingleTeam = 0; ///< Team all subExecutors across the data array
int waveOrder = 0; ///< GFX-kernel wavefront ordering
int wordSize = 4; ///< GFX-kernel packed data size (4=dwordx4, 2=dwordx2, 1=dwordx1)
};
/**
* DMA Executor options
*/
struct DmaOptions
{
int useHipEvents = 1; ///< Use HIP events for timing DMA Executor
int useHsaCopy = 0; ///< Use HSA copy instead of HIP copy to perform DMA
};
/**
* NIC Executor options
*/
struct NicOptions
{
size_t chunkBytes = 1<<30; ///< How much bytes to transfer at a time
int cqPollBatch = 4; ///< Maximum CQ entries polled per call
int ibGidIndex = -1; ///< GID Index for RoCE NICs (-1 is auto)
uint8_t ibPort = 1; ///< NIC port number to be used
int ipAddressFamily = 4; ///< 4=IPv4, 6=IPv6 (used for auto GID detection)
int maxRecvWorkReq = 16; ///< Maximum number of recv work requests per queue pair
int maxSendWorkReq = 1024; ///< Maximum number of send work requests per queue pair
int queueSize = 100; ///< Completion queue size
int roceVersion = 2; ///< RoCE version (used for auto GID detection)
int useRelaxedOrder = 1; ///< Use relaxed ordering
int useNuma = 0; ///< Switch to closest numa thread for execution
};
/**
* Configuration options for performing Transfers
*/
struct ConfigOptions
{
GeneralOptions general; ///< General options
DataOptions data; ///< Data options
GfxOptions gfx; ///< GFX executor options
DmaOptions dma; ///< DMA executor options
NicOptions nic; ///< NIC executor options
};
/**
* Enumeration of possible error types
*/
enum ErrType
{
ERR_NONE = 0, ///< No errors
ERR_WARN = 1, ///< Warning - results may not be accurate
ERR_FATAL = 2, ///< Fatal error - results are invalid
};
/**
* Enumeration of GID priority
*
* @note These are the GID types ordered in priority from lowest (0) to highest
*/
enum GidPriority
{
UNKNOWN = -1, ///< Default
ROCEV1_LINK_LOCAL = 0, ///< RoCEv1 Link-local
ROCEV2_LINK_LOCAL = 1, ///< RoCEv2 Link-local fe80::/10
ROCEV1_IPV6 = 2, ///< RoCEv1 IPv6
ROCEV2_IPV6 = 3, ///< RoCEv2 IPv6
ROCEV1_IPV4 = 4, ///< RoCEv1 IPv4-mapped IPv6
ROCEV2_IPV4 = 5, ///< RoCEv2 IPv4-mapped IPv6 ::ffff:192.168.x.x
};
const char* GidPriorityStr[] = {
"RoCEv1 Link-local",
"RoCEv2 Link-local",
"RoCEv1 IPv6",
"RoCEv2 IPv6",
"RoCEv1 IPv4-mapped IPv6",
"RoCEv2 IPv4-mapped IPv6"
};
/**
* Enumeration of possible communication mode types
*/
enum CommType
{
COMM_NONE = 0, ///< Single node only
COMM_MPI = 1, ///< MPI-based communication
COMM_SOCKET = 2 ///< Socket-based communication
};
/**
* ErrResult consists of error type and error message
*/
struct ErrResult
{
ErrType errType; ///< Error type
std::string errMsg; ///< Error details
ErrResult() = default;
#if defined(__NVCC__)
ErrResult(cudaError_t err);
ErrResult(CUresult err);
#else
ErrResult(hipError_t err);
ErrResult(hsa_status_t err);
#endif
ErrResult(ErrType err);
ErrResult(ErrType errType, const char* format, ...);
};
/**
* Results for a single Executor
*/
struct ExeResult
{
size_t numBytes; ///< Total bytes transferred by this Executor
double avgDurationMsec; ///< Averaged duration for all the Transfers for this Executor
double avgBandwidthGbPerSec; ///< Average bandwidth for this Executor
double sumBandwidthGbPerSec; ///< Naive sum of individual Transfer average bandwidths
vector<int> transferIdx; ///< Indicies of Transfers this Executor executed
};
/**
* Results for a single Transfer
*/
struct TransferResult
{
size_t numBytes; ///< Number of bytes transferred by this Transfer
double avgDurationMsec; ///< Duration for this Transfer, averaged over all timed iterations
double avgBandwidthGbPerSec; ///< Bandwidth for this Transfer based on averaged duration
// Only filled in if recordPerIteration = 1
vector<double> perIterMsec; ///< Duration for each individual iteration
vector<set<pair<int,int>>> perIterCUs; ///< GFX-Executor only. XCC:CU used per iteration
ExeDevice exeDevice; ///< Tracks which executor performed this Transfer (e.g. for EXE_NIC_NEAREST)
ExeDevice exeDstDevice; ///< Tracks actual destination executor (only valid for EXE_NIC/EXE_NIC_NEAREST)
};
/**
* TestResults contain timing results for a set of Transfers as a group as well as per Executor and per Transfer
* timing information
*/
struct TestResults
{
int numTimedIterations; ///< Number of iterations executed
size_t totalBytesTransferred; ///< Total bytes transferred per iteration
double avgTotalDurationMsec; ///< Wall-time (msec) to finish all Transfers (averaged across all timed iterations)
double avgTotalBandwidthGbPerSec; ///< Bandwidth based on all Transfers and average wall time
double overheadMsec; ///< Difference between total wall time and slowest executor
map<ExeDevice, ExeResult> exeResults; ///< Per Executor results
vector<TransferResult> tfrResults; ///< Per Transfer results
vector<ErrResult> errResults; ///< List of any errors/warnings that occurred
};
/**
* Run a set of Transfers
*
* @param[in] config Configuration options
* @param[in] transfers Set of Transfers to execute
* @param[out] results Timing results
* @returns true if and only if Transfers were run successfully without any fatal errors
*/
bool RunTransfers(ConfigOptions const& config,
vector<Transfer> const& transfers,
TestResults& results);
/**
* Enumeration of implementation attributes
*/
enum IntAttribute
{
ATR_GFX_MAX_BLOCKSIZE, ///< Maximum blocksize for GFX executor
ATR_GFX_MAX_UNROLL, ///< Maximum unroll factor for GFX executor
};
enum StrAttribute
{
ATR_SRC_PREP_DESCRIPTION ///< Description of how source memory is prepared
};
/**
* Query attributes (integer)
*
* @note This allows querying of implementation information such as limits
*
* @param[in] attribute Attribute to query
* @returns Value of the attribute
*/
int GetIntAttribute(IntAttribute attribute);
/**
* Query attributes (string)
*
* @note This allows query of implementation details such as limits
*
* @param[in] attrtibute Attribute to query
* @returns Value of the attribute
*/
std::string GetStrAttribute(StrAttribute attribute);
/**
* Returns information about number of available Executors given an executor type
*
* @param[in] exeType Executor type to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns Number of detected Executors of exeType
*/
int GetNumExecutors(ExeType exeType, int targetRank = -1);
/**
* Returns information about number of available Executors given a memory type
*
* @param[in] memType Memory type to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns Number of detected Executors for memType
*/
int GetNumExecutors(MemType memType, int targetRank = -1);
/**
* Returns the number of possible Executor subindices
*
* @note For CPU, this is 0
* @note For GFX, this refers to the number of XCDs
* @note For DMA, this refers to the number of DMA engines
*
* @param[in] exeDevice The specific Executor to query
* @returns Number of detected executor subindices
*/
int GetNumExecutorSubIndices(ExeDevice exeDevice);
/**
* Returns number of subExecutors for a given ExeDevice
*
* @param[in] exeDevice The specific Executor to query
* @returns Number of detected subExecutors for the given ExePair
*/
int GetNumSubExecutors(ExeDevice exeDevice);
/**
* Returns the index of the NUMA node closest to the given GPU
*
* @param[in] gpuIndex Index of the GPU to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns NUMA node index closest to GPU gpuIndex, or -1 if unable to detect
*/
int GetClosestCpuNumaToGpu(int gpuIndex, int targetRank = -1);
/**
* Returns the index of the NUMA node closest to the given NIC
*
* @param[in] nicIndex Index of the NIC to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns NUMA node index closest to the NIC nicIndex, or -1 if unable to detect
*/
int GetClosestCpuNumaToNic(int nicIndex, int targetRank = -1);
/**
* Returns the index of a NIC closest to the given GPU
*
* @param[in] gpuIndex Index of the GPU to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @note This function is applicable when the IBV/RDMA executor is available
* @returns IB Verbs capable NIC index closest to GPU gpuIndex, or -1 if unable to detect
*/
int GetClosestNicToGpu(int gpuIndex, int targetRank = -1);
/**
* Returns the indices of the NICs closest to the given CPU
*
* @param[out] nicIndices Vector that will contain NIC indices closest to given CPU
* @param[in] cpuIndex Index of the CPU to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @note This function is applicable when the IBV/RDMA executor is available
* @returns IB Verbs capable NIC indices closest to CPU cpuIndex, or empty if unable to detect
*/
void GetClosestNicsToCpu(std::vector<int>& nicIndices, int cpuIndex, int targetRank = -1);
/**
* Returns the indices of the NICs closest to the given GPU
*
* @param[out] nicIndices Vector that will contain NIC indices closest to given GPU
* @param[in] gpuIndex Index of the GPU to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @note This function is applicable when the IBV/RDMA executor is available
* @returns IB Verbs capable NIC indices closest to GPU gpuIndex, or empty if unable to detect
*/
void GetClosestNicsToGpu(std::vector<int>& nicIndices, int gpuIndex, int targetRank = -1);
/**
* Returns the index of a GPU closest to the given NIC
*
* @param[in] nicIndex Index of the NIC to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @note This function is applicable when the IBV/RDMA executor is available
* @returns GPU index closest to IB Verbs capable NIC index nicIndex, or -1 if unable to detect
*/
int GetClosestGpuToNic(int nicIndex, int targetRank);
/**
* Returns the indices of the GPUs closest to the given NIC
*
* @param[out] gpuIndices Vector that will contain GPU indices closest to given NIC
* @param[in] nicIndex Index of the NIC to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @note This function is applicable when the IBV/RDMA executor is available
* @returns GPU indices closest to NIC nicIndex, or empty if unable to detect
*/
void GetClosestGpusToNic(std::vector<int>& gpuIndices, int nicIndex, int targetRank = -1);
/**
* @returns 0-indexed rank for this process
*/
int GetRank();
/**
* @returns The total numbers of ranks participating
*/
int GetNumRanks();
/**
* @returns Gets the current communication mode
*/
int GetCommMode();
/**
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns Gets the hostname for the target rank
**/
std::string GetHostname(int targetRank = -1);
/**
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns Gets the unique pod identifier for the target rank based on its physical and virtual pod
**/
int64_t GetPodIdx(int targetRank = -1);
/**
* @param[in] targetRank Remote rank to query
* @param[in] sourceRank Base rank to query (-1 for local rank)
* @returns Whether source and target ranks belong to the same pod
**/
bool IsSamePod(int targetRank, int sourceRank = -1);
/**
* @param[in] exeDevice The specific Executor to query
* @returns Name of the executor
*/
std::string GetExecutorName(ExeDevice exeDevice);
/**
*
* @param[in] nicIndex The NIC index to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns Returns 1 if and only if NIC exists and has an active port
*/
int NicIsActive(int nicIndex, int targetRank = -1);
/**
* Helper function to parse a line containing Transfers into a vector of Transfers
*
* @param[in] str String containing description of Transfers
* @param[out] transfers List of Transfers described by 'str'
* @returns Information about any error that may have occured
*/
ErrResult ParseTransfers(std::string str,
std::vector<Transfer>& transfers);
}
//==========================================================================================
// End of TransferBench API
//==========================================================================================
// Redefinitions for CUDA compatibility
//==========================================================================================
#if defined(__NVCC__)
// ROCm specific
#define wall_clock64 clock64
#define gcnArchName name
// Datatypes
#define hipDeviceProp_t cudaDeviceProp
#define hipError_t cudaError_t
#define hipEvent_t cudaEvent_t
#define hipStream_t cudaStream_t
#define hipMemAllocationProp CUmemAllocationProp
#define hipMemGenericAllocationHandle_t CUmemGenericAllocationHandle
#define hipMemAccessDesc CUmemAccessDesc
#define hipMemFabricHandle_t CUmemFabricHandle
// Enumerations
#define hipDeviceAttributeClockRate cudaDevAttrClockRate
#define hipDeviceAttributeMultiprocessorCount cudaDevAttrMultiProcessorCount
#define hipDeviceAttributeWarpSize cudaDevAttrWarpSize
#define hipErrorPeerAccessAlreadyEnabled cudaErrorPeerAccessAlreadyEnabled
#define hipFuncCachePreferShared cudaFuncCachePreferShared
#define hipMemcpyDefault cudaMemcpyDefault
#define hipMemcpyDeviceToHost cudaMemcpyDeviceToHost
#define hipMemcpyHostToDevice cudaMemcpyHostToDevice
#define hipSuccess cudaSuccess
#define hipMemLocationTypeDevice CU_MEM_LOCATION_TYPE_DEVICE
#define hipMemAllocationTypePinned CU_MEM_ALLOCATION_TYPE_PINNED
#define hipMemHandleTypeFabric CU_MEM_HANDLE_TYPE_FABRIC
#define hipMemAllocationGranularityRecommended CU_MEM_ALLOC_GRANULARITY_RECOMMENDED
#define hipMemAccessFlagsProtReadWrite CU_MEM_ACCESS_FLAGS_PROT_READWRITE
// Functions
#define hipDeviceCanAccessPeer cudaDeviceCanAccessPeer
#define hipDeviceEnablePeerAccess cudaDeviceEnablePeerAccess
#define hipDeviceGetAttribute cudaDeviceGetAttribute
#define hipDeviceGetPCIBusId cudaDeviceGetPCIBusId
#define hipDeviceSetCacheConfig cudaDeviceSetCacheConfig
#define hipDeviceSynchronize cudaDeviceSynchronize
#define hipEventCreate cudaEventCreate
#define hipEventDestroy cudaEventDestroy
#define hipEventElapsedTime cudaEventElapsedTime
#define hipEventRecord cudaEventRecord
#define hipFree cudaFree
#define hipGetDeviceCount cudaGetDeviceCount
#define hipGetDeviceProperties cudaGetDeviceProperties
#define hipGetErrorString cudaGetErrorString
#define hipHostFree cudaFreeHost
#define hipHostMalloc cudaMallocHost
#define hipMalloc cudaMalloc
#define hipMallocManaged cudaMallocManaged
#define hipMemcpy cudaMemcpy
#define hipMemcpyAsync cudaMemcpyAsync
#define hipMemset cudaMemset
#define hipMemsetAsync cudaMemsetAsync
#define hipSetDevice cudaSetDevice
#define hipStreamCreate cudaStreamCreate
#define hipStreamDestroy cudaStreamDestroy
#define hipStreamSynchronize cudaStreamSynchronize
#define hipMemGetAllocationGranularity cuMemGetAllocationGranularity
#define hipMemCreate cuMemCreate
#define hipMemAddressReserve cuMemAddressReserve
#define hipMemMap cuMemMap
#define hipMemSetAccess cuMemSetAccess
#define hipMemUnmap cuMemUnmap
#define hipMemRelease cuMemRelease
#define hipMemAddressFree cuMemAddressFree
#define hipMemExportToShareableHandle cuMemExportToShareableHandle
#define hipMemImportFromShareableHandle cuMemImportFromShareableHandle
using gpu_device_ptr = CUdeviceptr;
// Define float2 addition operator for NVIDIA platform
__device__ inline float2& operator +=(float2& a, const float2& b)
{
a.x += b.x;
a.y += b.y;
return a;
}
// Define float4 addition operator for NVIDIA platform
__device__ inline float4& operator +=(float4& a, const float4& b)
{
a.x += b.x;
a.y += b.y;
a.z += b.z;
a.w += b.w;
return a;
}
#else
using gpu_device_ptr = void*;
#endif
// Helper macro functions
//==========================================================================================
// Macro for collecting CU/SM GFX kernel is running on
#if defined(__GFX9__)
#define GetHwId(hwId) asm volatile ("s_getreg_b32 %0, hwreg(HW_REG_HW_ID)" : "=s" (hwId))
#elif defined(__GFX10__) || defined(__GFX11__) || defined(__GFX12__)
#define GetHwId(hwId) asm volatile ("s_getreg_b32 %0, hwreg(HW_REG_HW_ID1)" : "=s" (hwId))
#elif defined(__NVCC__)
#define GetHwId(hwId) asm("mov.u32 %0, %smid;" : "=r"(hwId))
#else
#define GetHwId(hwId) hwId = 0
#endif
// Macro for collecting XCC GFX kernel is running on
#if defined(__gfx942__) || defined(__gfx950__)
#define GetXccId(val) asm volatile ("s_getreg_b32 %0, hwreg(HW_REG_XCC_ID)" : "=s" (val))
#else
#define GetXccId(val) val = 0
#endif
// Error check macro (NOTE: This will return even for ERR_WARN)
#define ERR_CHECK(cmd) \
do { \
ErrResult err = (cmd); \
if (err.errType != ERR_NONE) { \
err.errMsg += std::string(" [") + __FILE__ + ":" + \
std::to_string(__LINE__) + " in " + __func__ + "]"; \
return err; \
} \
} while (0)
// Appends warn/fatal errors to a list, return false if fatal
#define ERR_APPEND(cmd, list) \
do { \
ErrResult err = (cmd); \
if (err.errType != ERR_NONE) { \
err.errMsg += std::string(" [") + __FILE__ + ":" + \
std::to_string(__LINE__) + " in " + __func__ + "]"; \
list.push_back(err); \
} \
if (err.errType == ERR_FATAL) \
return false; \
} while (0)
namespace {
IBV_FN(ibv_alloc_pd, ibv_pd*, (ibv_context*));
IBV_FN(ibv_close_device, int, (ibv_context*));
IBV_FN(ibv_create_cq, ibv_cq*, (ibv_context*, int, void*, ibv_comp_channel*, int));
IBV_FN(ibv_create_qp, ibv_qp*, (ibv_pd*, ibv_qp_init_attr*));
IBV_FN(ibv_dealloc_pd, int, (ibv_pd*));
IBV_FN(ibv_dereg_mr, int, (ibv_mr*));
IBV_FN(ibv_destroy_cq, int, (ibv_cq*));
IBV_FN(ibv_destroy_qp, int, (ibv_qp*));
IBV_FN(ibv_free_device_list, void, (ibv_device**));
IBV_FN(ibv_get_device_list, ibv_device**, (int*));
IBV_FN(ibv_get_device_name, const char*, (ibv_device*));
IBV_FN(ibv_modify_qp, int, (ibv_qp*, ibv_qp_attr*, int));
IBV_FN(ibv_open_device, ibv_context*, (ibv_device*));
IBV_FN(ibv_poll_cq, int, (ibv_cq*, int, ibv_wc*));
IBV_FN(ibv_post_send, int, (ibv_qp*, ibv_send_wr*, ibv_send_wr**));
IBV_FN(ibv_query_device, int, (ibv_context*, ibv_device_attr*));
IBV_FN(ibv_query_gid, int, (ibv_context*, uint8_t, int, ibv_gid*));
IBV_FN(ibv_query_port, int, (ibv_context*, uint8_t, ibv_port_attr*));
#ifdef HAVE_DMABUF_SUPPORT
IBV_FN(ibv_reg_dmabuf_mr, ibv_mr*, (ibv_pd*, uint64_t, size_t, uint64_t, int, int));
#endif
IBV_FN(ibv_reg_mr, ibv_mr*, (ibv_pd*, void*, size_t, int));
}
// Helper macros for calling RDMA functions and reporting errors
#ifdef VERBS_DEBUG
#define IBV_CALL(__func__, ...) \
do { \
int error = pfn_##__func__(__VA_ARGS__); \
if (error != 0) { \
return {ERR_FATAL, "Encountered IbVerbs error (%d) at line (%d) " \
"and function (%s)", (error), __LINE__, #__func__}; \
} \
} while (0)
#define IBV_PTR_CALL(__ptr__, __func__, ...) \
do { \
__ptr__ = pfn_##__func__(__VA_ARGS__); \
if (__ptr__ == nullptr) { \
return {ERR_FATAL, "Encountered IbVerbs nullptr error at line (%d) " \
"and function (%s)", __LINE__, #__func__}; \
} \
} while (0)
#else
#define IBV_CALL(__func__, ...) \
do { \
int error = pfn_##__func__(__VA_ARGS__); \
if (error != 0) { \
return {ERR_FATAL, "Encountered IbVerbs error (%d=%s) in func (%s)" \
, error, strerror(errno), #__func__}; \
} \
} while (0)
#define IBV_PTR_CALL(__ptr__, __func__, ...) \
do { \
__ptr__ = pfn_##__func__(__VA_ARGS__); \
if (__ptr__ == nullptr) { \
return {ERR_FATAL, "Encountered IbVerbs nullptr error (%s) in func (%s) " \
, strerror(errno), #__func__}; \
} \
} while (0)
#endif
namespace TransferBench
{
/// @cond
// Helper functions ('hidden' in anonymous namespace)
//========================================================================================
namespace {
// Constants
//========================================================================================
int constexpr MAX_BLOCKSIZE = 1024; // Max threadblock size
int constexpr MAX_UNROLL = 8; // Max unroll factor
int constexpr MAX_SRCS = 8; // Max srcs per Transfer
int constexpr MAX_DSTS = 8; // Max dsts per Transfer
int constexpr MEMSET_CHAR = 75; // Value to memset (char)
float constexpr MEMSET_VAL = 13323083.0f; // Value to memset (double)
int GetWarpSize(std::vector<ErrResult>* errors = nullptr) {
int warpSize = 0;
hipError_t err = hipDeviceGetAttribute(&warpSize, hipDeviceAttributeWarpSize, 0);
if (err == hipSuccess) {
return warpSize;
}
// Query failed, report error and fall back to compile-time default
if (errors) {
errors->push_back({ERR_WARN,
"Failed to query device warp size (hipDeviceGetAttribute error: %d). "
"Falling back to compile-time default", err});
}
#if defined(__NVCC__)
return 32;
#else
return 64;
#endif
}
// Calculate grid Y dimension based on SE_TYPE
int CalculateGridY(int seType, int blockSize, int numSubExecs) {
// Warp-level: each subexecutor is a warp, pack warps into threadblocks
if (seType == 1) {
int warpsPerBlock = blockSize / GetWarpSize();
return (numSubExecs + warpsPerBlock - 1) / warpsPerBlock;
}
// Default: Threadblock-level, each subexecutor is a threadblock
return numSubExecs;
}
// System singleton
//========================================================================================
/**
* System singleton class used for multi-node capability / topology dectection
*
* This supports three possible communication modes - Socket-based, MPI-based, disabled
*
* - Will first attempt to use sockets if TB_RANK env var is detected
* - Will then try MPI-based, if compiled with MPI support
* - Drop back to single node functionality
* - Configuration for socket-based communicator is read via environment variables
* - TB_RANK: Rank of this process (0-based)
* - TB_NUM_RANKS: Total number of processes
* - TB_MASTER_ADDR: IP address of rank 0
* - TB_MASTER_PORT: Port for communication (default: 29500)
*/
class System
{
public:
static System& Get() {
static System instance;
return instance;
}
/**
* @returns 0-indexed rank for this process
*/
int GetRank() const { return rank; }
/**
* @returns The total numbers of ranks participating
*/
int GetNumRanks() const { return numRanks; }
/**
* @returns The communication mode
*/
int GetCommMode() const { return commMode; }
bool& IsVerbose() { return verbose; }
/**
* Helper logging function that logs only on output ranks
* - In MPI mode - Rank 0 only
* - In socket mode - All ranks unless TB_SINGLE_LOG=1
*/
void Log(const char* format, ...) const;
/**
* Helper function that logs Transfers being executed to a config file
*/
void LogTransfers(std::vector<Transfer> const& transfers);
// Communication functions
/**
* Barrier that all ranks must arrive at before proceeding
*/
void Barrier();
/**
* Send data to a single destination rank
* Requires a matching call to RecvData on destination rank
* NOTE: For socket-based communicator, this must involve rank 0
*
* @param[in] dstRank Rank to send to
* @param[in] numBytes Number of bytes to send
* @param[in] sendData Data to send
*/
void SendData(int dstRank, size_t const numBytes, const void* sendData) const;
/**
* Recevive data from a single source rank
* Requires a matching call to SendData on source rank
* NOTE: For socket-based communicator, this must involve rank 0
*
* @param[in] srcRank Rank to receive from
* @param[in] numBytes Number of bytes to receive
* @param[in] recvData Buffer to receive data into
*/
void RecvData(int srcRank, size_t const numBytes, void* recvData) const;
/**
* Modifies provided input to true if any rank provides a true input
*
* @param[in] flag Flag to compare across ranks
* @returns True if and only if any rank provided a flag with value of true
*/
bool Any(bool const flag) const;
/**
* Broadcast data from root to all ranks
* All ranks must participate in this call
*
* @param[in] root Rank that sends data
* @param[in] numBytes Number of bytes to transfer
* @param[in/out] data Buffer to send from root / to receive into on other ranks
*/
void Broadcast(int root, size_t const numBytes, void* data) const;
/**
* Collect errors across ranks
* @param[in,out] errResults List of errors per rank
*/
void AllGatherErrors(vector<ErrResult>& errResults) const;
// Topology functions
/**
* Returns information about number of available Executors
*
* @param[in] exeType Executor type to query
* @param[in] targetRank Rank to query. (-1 for local rank)
* @returns Number of detected Executors of exeType
*/
int GetNumExecutors(ExeType exeType, int targetRank = -1) const;
/**
* Returns the number of possible Executor subindices
*
* @note For CPU, this is 0
* @note For GFX, this refers to the number of XCDs
* @note For DMA, this refers to the number of DMA engines
*
* @param[in] exeDevice The specific Executor to query
* @returns Number of detected executor subindices
*/
int GetNumExecutorSubIndices(ExeDevice exeDevice) const;
/**
* Returns number of subExecutors for a given ExeDevice
*
* @param[in] exeDevice The specific Executor to query
* @returns Number of detected subExecutors for the given ExePair
*/
int GetNumSubExecutors(ExeDevice exeDevice) const;
/**
* Returns the index of the NUMA node closest to the given GPU
*
* @param[in] gpuIndex Index of the GPU to query
* @param[in] targetRank Rank to query (-1 for local rank)
* @returns NUMA node index closest to GPU gpuIndex, or -1 if unable to detect