TransferBench.hpp 241 KB
Newer Older
1
/*
gilbertlee-amd's avatar
gilbertlee-amd committed
2
Copyright (c) Advanced Micro Devices, Inc. All rights reserved.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

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.
*/

srawat's avatar
srawat committed
23
/// @cond
24
#pragma once
gilbertlee-amd's avatar
gilbertlee-amd committed
25
#include <algorithm>
26
27
28
#include <arpa/inet.h>
#include <atomic>
#include <barrier>
29
#include <cstring>
30
31
32
33
#include <fcntl.h>
#include <filesystem>
#include <fstream>
#include <functional>
34
35
#include <future>
#include <map>
36
37
#include <mutex>
#include <netinet/in.h>
38
39
#include <numa.h> // If not found, try installing libnuma-dev (e.g apt-get install libnuma-dev)
#include <numaif.h>
gilbertlee-amd's avatar
gilbertlee-amd committed
40
#include <random>
41
#include <regex>
42
43
44
#include <set>
#include <sstream>
#include <stdarg.h>
45
46
47
48
49
50
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
51
#include <thread>
52
#include <unistd.h>
53
54
#include <vector>

gilbertlee-amd's avatar
gilbertlee-amd committed
55
56
#ifdef NIC_EXEC_ENABLED
#include <infiniband/verbs.h>
57
58
59
60
#endif

#ifdef MPI_COMM_ENABLED
#include <mpi.h>
gilbertlee-amd's avatar
gilbertlee-amd committed
61
62
#endif

63
64
#if defined(__NVCC__)
#include <cuda_runtime.h>
65
#include <nvml.h>
66
67
68
69
70
71
#else
#include <hip/hip_ext.h>
#include <hip/hip_runtime.h>
#include <hsa/hsa.h>
#include <hsa/hsa_ext_amd.h>
#endif
srawat's avatar
srawat committed
72
/// @endcond
73
74
75
76
77
78
79
80

namespace TransferBench
{
  using std::map;
  using std::pair;
  using std::set;
  using std::vector;

81
  constexpr char VERSION[] = "1.66";
82
83
84
85
86
87
88
89
90
91
92

  /**
   * 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)
gilbertlee-amd's avatar
gilbertlee-amd committed
93
94
    EXE_NIC          = 3,                       ///<  NIC RDMA executor         (subExecutor = queue pair)
    EXE_NIC_NEAREST  = 4                        ///<  NIC RDMA nearest executor (subExecutor = queue pair)
95
  };
gilbertlee-amd's avatar
gilbertlee-amd committed
96
  char const ExeTypeStr[6] = "CGDIN";
97
98
  inline bool IsCpuExeType(ExeType e){ return e == EXE_CPU; }
  inline bool IsGpuExeType(ExeType e){ return e == EXE_GPU_GFX || e == EXE_GPU_DMA; }
gilbertlee-amd's avatar
gilbertlee-amd committed
99
  inline bool IsNicExeType(ExeType e){ return e == EXE_NIC || e == EXE_NIC_NEAREST; }
100
101
102
103
104
105
106
107

  /**
   * A ExeDevice defines a specific Executor
   */
  struct ExeDevice
  {
    ExeType exeType;                            ///< Executor type
    int32_t exeIndex;                           ///< Executor index
108
109
    int32_t exeRank = 0;                        ///< Executor rank
    int32_t exeSlot = 0;                        ///< Executor slot
110

111
    bool operator<(ExeDevice const& other) const {
112
113
114
115
      return ((exeRank  != other.exeRank)  ? (exeRank  < other.exeRank)  :
              (exeType  != other.exeType)  ? (exeType  < other.exeType)  :
              (exeIndex != other.exeIndex) ? (exeIndex < other.exeIndex) :
                                             (exeSlot  < other.exeSlot));
116
    }
117
118
119
120
121
122
123
124
125
  };

  /**
   * Enumeration of supported memory types
   *
   * @note These are possible types of memory to be used as sources/destinations
   */
  enum MemType
  {
126
127
128
129
130
131
132
133
134
135
136
    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
137
  };
138
139
140
  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);}
141
142
143
144
145
146
147
148

  /**
   * A MemDevice indicates a memory type on a specific device
   */
  struct MemDevice
  {
    MemType memType;                            ///< Memory type
    int32_t memIndex;                           ///< Device index
149
    int32_t memRank = 0;                        ///< Rank index
150
151

    bool operator<(MemDevice const& other) const {
152
153
154
155
156
157
158
159
      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);
160
    }
161
162
163
164
165
166
167
  };

  /**
   * A Transfer adds together data from zero or more sources then writes the sum to zero or more desintations
   */
  struct Transfer
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
168
    size_t            numBytes    = 0;          ///< Number of bytes to Transfer
169
170
171
172
    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
173
    int32_t           exeSubSlot  = 0;          ///< Executor subslot
174
175
176
177
178
179
180
181
    int               numSubExecs = 0;          ///< Number of subExecutors to use for this Transfer
  };

  /**
   * General options
   */
  struct GeneralOptions
  {
srawat's avatar
srawat committed
182
183
    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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    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
gilbertlee-amd's avatar
gilbertlee-amd committed
198
    vector<int>   fillCompress     = {};        ///< Customized data patterns (overrides fillPattern if non-empty)
199
200
201
202
203
204
205
206
207
    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
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
208
    int                 blockOrder     = 0;     ///< Determines how threadblocks are ordered (0=sequential, 1=interleaved, 2=random)
209
210
211
    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
212
    int                 seType         = 0;     ///< SubExecutor granularity type (0=threadblock, 1=warp)
gilbertlee-amd's avatar
gilbertlee-amd committed
213
    int                 temporalMode   = 0;     ///< Non-temporal load/store mode 0=none, 1=load, 2=store, 3=both
214
215
216
    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
217
    int                 useSingleTeam  = 0;     ///< Team all subExecutors across the data array
218
    int                 waveOrder      = 0;     ///< GFX-kernel wavefront ordering
gilbertlee-amd's avatar
gilbertlee-amd committed
219
    int                 wordSize       = 4;     ///< GFX-kernel packed data size (4=dwordx4, 2=dwordx2, 1=dwordx1)
220
221
  };

gilbertlee-amd's avatar
gilbertlee-amd committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  /**
   * 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
  {
236
    size_t      chunkBytes      = 1<<30;        ///< How much bytes to transfer at a time
gilbertlee-amd's avatar
gilbertlee-amd committed
237
238
239
240
    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
241
    int         maxSendWorkReq  = 1024;         ///< Maximum number of send work requests per queue pair
gilbertlee-amd's avatar
gilbertlee-amd committed
242
243
244
245
246
247
248
    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
  };


249
250
251
252
253
254
255
256
257
258
  /**
   * 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
gilbertlee-amd's avatar
gilbertlee-amd committed
259
    NicOptions     nic;                         ///< NIC executor options
260
261
262
263
264
265
266
267
268
269
270
271
  };

  /**
   * 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
  };

gilbertlee-amd's avatar
gilbertlee-amd committed
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
  /**
   * 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"
  };

297
298
299
300
301
302
303
304
305
306
  /**
   * 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
  };

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
  /**
   * 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);
#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
gilbertlee-amd's avatar
gilbertlee-amd committed
350
351
352

    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)
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
  };

  /**
   * 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);

  /**
419
   * Returns information about number of available Executors given an executor type
420
   *
421
422
   * @param[in] exeType         Executor type to query
   * @param[in] targetRank      Rank to query (-1 for local rank)
423
424
   * @returns Number of detected Executors of exeType
   */
425
426
427
428
429
430
431
432
433
434
  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);
435
436
437
438
439
440
441
442

  /**
   * 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
   *
443
   * @param[in] exeDevice       The specific Executor to query
444
445
446
447
448
449
450
   * @returns Number of detected executor subindices
   */
  int GetNumExecutorSubIndices(ExeDevice exeDevice);

  /**
   * Returns number of subExecutors for a given ExeDevice
   *
451
   * @param[in] exeDevice       The specific Executor to query
452
453
454
455
456
457
458
   * @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
   *
459
460
   * @param[in] gpuIndex        Index of the GPU to query
   * @param[in] targetRank      Rank to query (-1 for local rank)
461
462
   * @returns NUMA node index closest to GPU gpuIndex, or -1 if unable to detect
   */
463
  int GetClosestCpuNumaToGpu(int gpuIndex, int targetRank = -1);
464

gilbertlee-amd's avatar
gilbertlee-amd committed
465
466
467
  /**
   * Returns the index of the NUMA node closest to the given NIC
   *
468
469
   * @param[in] nicIndex        Index of the NIC to query
   * @param[in] targetRank      Rank to query (-1 for local rank)
gilbertlee-amd's avatar
gilbertlee-amd committed
470
471
   * @returns NUMA node index closest to the NIC nicIndex, or -1 if unable to detect
   */
472
  int GetClosestCpuNumaToNic(int nicIndex, int targetRank = -1);
gilbertlee-amd's avatar
gilbertlee-amd committed
473
474

  /**
475
   * Returns the index of a NIC closest to the given GPU
gilbertlee-amd's avatar
gilbertlee-amd committed
476
   *
477
478
   * @param[in] gpuIndex        Index of the GPU to query
   * @param[in] targetRank      Rank to query (-1 for local rank)
gilbertlee-amd's avatar
gilbertlee-amd committed
479
480
481
   * @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
   */
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
  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 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 physical pod identifier for the target rank
   **/
  std::string GetPpodId(int targetRank = -1);

  /**
   * @param[in] targetRank  Rank to query (-1 for local rank)
   * @returns Gets the virtual pod identifier for the target rank
   **/
  int GetVpodId(int targetRank = -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);
gilbertlee-amd's avatar
gilbertlee-amd committed
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
  /**
   * 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

  // Enumerations
  #define hipDeviceAttributeClockRate                        cudaDevAttrClockRate
  #define hipDeviceAttributeMultiprocessorCount              cudaDevAttrMultiProcessorCount
584
  #define hipDeviceAttributeWarpSize                         cudaDevAttrWarpSize
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
  #define hipErrorPeerAccessAlreadyEnabled                   cudaErrorPeerAccessAlreadyEnabled
  #define hipFuncCachePreferShared                           cudaFuncCachePreferShared
  #define hipMemcpyDefault                                   cudaMemcpyDefault
  #define hipMemcpyDeviceToHost                              cudaMemcpyDeviceToHost
  #define hipMemcpyHostToDevice                              cudaMemcpyHostToDevice
  #define hipSuccess                                         cudaSuccess

  // 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

gilbertlee-amd's avatar
gilbertlee-amd committed
620
621
622
623
624
625
626
627
  // 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;
  }

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
  // 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;
  }
#endif

// Helper macro functions
//==========================================================================================

// Macro for collecting CU/SM GFX kernel is running on
gilbertlee-amd's avatar
gilbertlee-amd committed
643
#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__)
644
645
646
647
648
649
650
651
#define GetHwId(hwId) hwId = 0
#elif defined(__NVCC__)
#define GetHwId(hwId) asm("mov.u32 %0, %smid;" : "=r"(hwId))
#else
#define GetHwId(hwId) asm volatile ("s_getreg_b32 %0, hwreg(HW_REG_HW_ID)" : "=s" (hwId));
#endif

// Macro for collecting XCC GFX kernel is running on
gilbertlee-amd's avatar
gilbertlee-amd committed
652
#if defined(__gfx942__) || defined(__gfx950__)
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
#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)  \
      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)  \
      list.push_back(err);        \
    if (err.errType == ERR_FATAL) \
      return false;               \
  } while (0)

gilbertlee-amd's avatar
gilbertlee-amd committed
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
// Helper macros for calling RDMA functions and reporting errors
#ifdef VERBS_DEBUG
#define IBV_CALL(__func__, ...)                                         \
  do {                                                                  \
    int error = __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__ = __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 = __func__(__VA_ARGS__);                                  \
    if (error != 0) {                                                   \
      return {ERR_FATAL, "Encountered IbVerbs error (%d) in func (%s) " \
              , error, #__func__};                                      \
    }                                                                   \
  } while (0)

#define IBV_PTR_CALL(__ptr__, __func__, ...)                               \
  do {                                                                     \
    __ptr__ = __func__(__VA_ARGS__);                                       \
    if (__ptr__ == nullptr) {                                              \
      return {ERR_FATAL, "Encountered IbVerbs nullptr error in func (%s) " \
              , #__func__};                                                \
    }                                                                      \
  } while (0)
#endif

715
716
namespace TransferBench
{
srawat's avatar
srawat committed
717
718

/// @cond
719
720
721
722
723
724
// Helper functions ('hidden' in anonymous namespace)
//========================================================================================
namespace {

// Constants
//========================================================================================
gilbertlee-amd's avatar
gilbertlee-amd committed
725

gilbertlee-amd's avatar
gilbertlee-amd committed
726
  int   constexpr MAX_BLOCKSIZE  = 1024;               // Max threadblock size
gilbertlee-amd's avatar
gilbertlee-amd committed
727
728
729
730
731
  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)
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
  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;
  }

765
// System singleton
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
1001
1002
1003
1004
1005
1006
1007
/**
   * 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; }

    // 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
     */
    int GetClosestCpuNumaToGpu(int gpuIndex, int targetRank = -1) const;

    /**
     * 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) const;

    /**
     * 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) const;

    std::string GetHostname(int targetRank) const;
    std::string GetPpodId(int targetRank) const;
    int GetVpodId(int targetRank) const;
    std::string GetExecutorName(ExeDevice exeDevice) const;
    int NicIsActive(int nicIndex, int targetRank) const;

#if !defined(__NVCC__)
    ErrResult GetHsaAgent(ExeDevice const& exeDevice, hsa_agent_t& agent) const;
    ErrResult GetHsaAgent(MemDevice const& memDevice, hsa_agent_t& agent) const;
#endif

    template <typename T>
    void BroadcastVector(int root, vector<T>& data) const;
    void BroadcastString(int root, std::string& string) const;
    void BroadcastExeResult(int root, ExeResult& exeResult) const;
    void BroadcastTfrResult(int root, TransferResult& tfrResult) const;


  private:
    System();
    ~System();
    System(System const&)            = delete;
    System(System&&)                 = delete;
    System& operator=(System const&) = delete;
    System& operator=(System&&)      = delete;

    int rank;
    int numRanks;
    bool verbose = false;

#if !defined(__NVCC__)
    std::vector<hsa_agent_t> cpuAgents;
    std::vector<hsa_agent_t> gpuAgents;
#endif

    int commMode;                             ///< Communication mode

#ifdef MPI_COMM_ENABLED
    bool mpiInit = false;                     ///< Whether or not MPI_Init was called
    MPI_Comm comm;                            ///< MPI communicator
#endif

    // Socket related
    std::string      masterAddr;              ///< Rank 0 master address
    int              masterPort;              ///< Rank 0 master port
    std::vector<int> sockets;                 ///< Master list of sockets
    int              listenSocket;            ///< Master listener socket

    // Topology related
    struct RankTopology
    {
      char hostname[33];
      char ppodId[256];
      int  vpodId;

      std::map<ExeType,            int>         numExecutors;
      std::map<pair<ExeType, int>, int>         numExecutorSubIndices;
      std::map<pair<ExeType, int>, int>         numSubExecutors;
      std::map<int,                int>         closestCpuNumaToGpu;
      std::map<int,                int>         closestCpuNumaToNic;
      std::map<int,                int>         nicIsActive;
      std::map<int,                vector<int>> closestNicsToGpu;
      std::map<pair<ExeType, int>, std::string> executorName;
    };

    std::vector<RankTopology> rankInfo;       ///< Topology of each rank

    void SetupSocketCommunicator();
    void SetupMpiCommunicator();
    void GetRankTopology(RankTopology& topo);
    void CollectTopology();
    std::string GetCpuName() const;

    template <typename KeyType, typename ValType>
    void SendMap(int peerRank, std::map<KeyType, std::vector<ValType>> const& mapToSend) const;
    template <typename KeyType, typename ValType>
    void SendMap(int peerRank, std::map<KeyType, ValType> const& mapToSend) const;
    template <typename KeyType>
    void SendMap(int peerRank, std::map<KeyType, std::string> const& mapToSend) const;

    template <typename KeyType, typename ValType>
    void RecvMap(int peerRank, std::map<KeyType, std::vector<ValType>>& mapToRecv) const;
    template <typename KeyType, typename ValType>
    void RecvMap(int peerRank, std::map<KeyType, ValType>& mapToRecv) const;
    template <typename KeyType>
    void RecvMap(int peerRank, std::map<KeyType, std::string>& mapToRecv) const;

    void SendRankTopo(int peerRank, RankTopology const& topo) const;
    void RecvRankTopo(int peerRank, RankTopology& topo) const;
  };
1008

1009
1010
// Parsing-related functions
//========================================================================================
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
  static ErrResult CharToMemType(char const c, MemType& memType)
  {
    char const* val = strchr(MemTypeStr, toupper(c));
    if (val) {
      memType = (MemType)(val - MemTypeStr);
      return ERR_NONE;
    }
    return {ERR_FATAL, "Unexpected memory type (%c)", c};
  }

  static ErrResult CharToExeType(char const c, ExeType& exeType)
  {
    char const* val = strchr(ExeTypeStr, toupper(c));
    if (val) {
      exeType = (ExeType)(val - ExeTypeStr);
      return ERR_NONE;
    }
    return {ERR_FATAL, "Unexpected executor type (%c)", c};
  }

1031
  struct WildcardMemDevice
1032
1033
  {
    MemType memType;
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
    vector<int> memRanks;
    vector<int> memIndices;
  };

  struct WildcardExeDevice
  {
    ExeType exeType;
    std::vector<int> exeRanks;
    std::vector<int> exeIndices;
    std::vector<int> exeSlots;
    std::vector<int> exeSubIndices;
    std::vector<int> exeSubSlots;
  };

  struct WildcardTransfer
  {
    std::vector<WildcardMemDevice> mem[2]; // 0 = SRCs, 1 = DSTs
    WildcardExeDevice exe;
  };

  static char const* ParseRange(char const* start, int fullCount, std::vector<int>& range)
  {
    range.clear();

    char const* ptr = start;
    if (!ptr) return 0;

    // Full wildcard
    if (*ptr == '*') {
      if (fullCount >= 0) {
        for (int i = 0; i < fullCount; i++)
        range.push_back(i);
      } else {
        range.push_back(fullCount);
      }
      return ++ptr;
    }

    // Ranged wildcard
    if (*ptr == '[') {
      std::string rangeStr(++ptr);
      size_t endPos = rangeStr.find(']');
      if (endPos == std::string::npos) return 0;
      rangeStr.erase(endPos);
      ptr += endPos+1;

      std::set<int> values;
      char* token = strtok(rangeStr.data(), ",");
      while (token) {
        int start, end;
        if (sscanf(token, "%d..%d", &start, &end) == 2) {
          if (start < 0 || end < 0 || end <= start) return 0;
          for (int i = start; i <= end; i++)
            values.insert(i);
        } else if (sscanf(token, "%d", &start) == 1) {
          values.insert(start);
        } else {
          return 0;
        }
        token = strtok(NULL, ",");
      }
      if (values.empty()) return 0;
      for (auto v : values) range.push_back(v);
      return ptr;
    }

    // Single number
    char* endPtr;
    int val = strtol(ptr, &endPtr, 10);
    if (endPtr == ptr) return 0;
    else range.push_back(val);
    return endPtr;
  }

  static char const* ParseAlphaRange(char const* start, std::vector<int>& range)
  {
    range.clear();

    char const* ptr = start;
    if (!ptr) return 0;
1114

1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
    // Full wildcard
    if (*ptr == '*') {
      range.push_back(-1);
      return ++ptr;
    }

    // Ranged wildcard
    if (*ptr == '[') {
      std::string rangeStr(++ptr);
      size_t endPos = rangeStr.find(']');
      if (endPos == std::string::npos) return 0;
      rangeStr.erase(endPos);
      ptr += endPos+1;

      std::set<int> values;
      char* token = strtok(rangeStr.data(), ",");
      while (token) {
        char start, end;
        if (sscanf(token, "%c..%c", &start, &end) == 2 && isalpha(toupper(start)) && isalpha(toupper(end))) {
          int realStart = toupper(start) - 'A';
          int realEnd   = toupper(end)   - 'A';
          if (realStart < 0 || realEnd < 0) return 0;
          for (int i = realStart; i <= realEnd; i++)
            values.insert(i);
        } else if (sscanf(token, "%c", &start) == 1 && isalpha(toupper(start))) {
          int realStart = toupper(start) - 'A';
          values.insert(realStart);
        } else {
          return 0;
        }
        token = strtok(NULL, ",");
      }
      for (auto v : values) range.push_back(v);
      return ptr;
    }

    // Single character
    if (isalpha(toupper(*ptr))) {
      range.push_back(toupper(*ptr)-'A');
      ++ptr;
    }
    return ptr;
  }

  static ErrResult ParseMemType(std::string const& token,
                                std::vector<WildcardMemDevice>& memDevices)
  {
1162
1163
    memDevices.clear();

1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
    char const* ptr = token.c_str();
    while (*ptr) {
      WildcardMemDevice w;

      // Parse memory rank if it exists
      if (*ptr == 'R' || *ptr == 'r') {
        ptr++; // Skip 'R'
        ptr = ParseRange(ptr, GetNumRanks(), w.memRanks);
        if (!ptr) return {ERR_FATAL, "Unable to parse rank index in memory token %s", token.c_str()};
      } else {
        // Otherwise will be replaced by "local" wildcard
        w.memRanks.clear();
      }

      // Parse memory type
1179
1180
1181
1182
      ErrResult err = CharToMemType(*ptr, w.memType);
      if (err.errType != ERR_NONE) {
        return {err.errType, "Error parsing token [%s]: %s\n", token.c_str(), err.errMsg.c_str()};
      }
1183
      ptr++; // Skip memory type
1184

1185
1186
1187
1188
1189
      // Parse memory index
      if (w.memType != MEM_NULL) {
        ptr = ParseRange(ptr, -1, w.memIndices);
        if (!ptr) return {ERR_FATAL, "Unable to parse device index in memory token %s", token.c_str()};
        memDevices.push_back(w);
1190
1191
      } else {
        break;
1192
      }
1193
    }
1194
    return ERR_NONE;
1195
1196
1197
  }

  static ErrResult ParseExeType(std::string const& token,
1198
                                WildcardExeDevice& exeDevice)
1199
  {
1200
    char const* ptr = token.c_str();
1201

1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
    // Check for rank prefix
    if (*ptr == 'R' || *ptr == 'r') {
      ptr++; // Skip 'R'
      ptr = ParseRange(ptr, GetNumRanks(), exeDevice.exeRanks);
      if (!ptr) return {ERR_FATAL, "Unable to parse rank index in executor token %s", token.c_str()};
    } else {
      exeDevice.exeRanks.clear();
    }

    // Parse executor type
    ERR_CHECK(CharToExeType(*ptr, exeDevice.exeType));
    ptr++; // Skip executor type char

    // Parse executor index
    // This is optional for EXE_NIC_NEAREST as long as nothing further is specified
    char const* endPtr = ParseRange(ptr, -1, exeDevice.exeIndices);
    if (!endPtr) {
      if (exeDevice.exeType == EXE_NIC_NEAREST && *endPtr == 0) {
        if (exeDevice.exeRanks.size() != 0) {
          return {ERR_FATAL, "Wildcard NIC executor may not be specified with rank in executor token %s", token.c_str()};
        }
        exeDevice.exeIndices.clear();
        return ERR_NONE;
      } else {
        return {ERR_FATAL, "Unable to parse device index in executor token %s", token.c_str()};
      }
    } else {
      ptr = endPtr;
    }

    // Parse (optional) executor slot
    ptr = ParseAlphaRange(ptr, exeDevice.exeSlots);
    if (!ptr) return {ERR_FATAL, "Unable to parse executor slot in executor token %s", token.c_str()};

    // Check for subindex after device
    if (*ptr == '.') {
      ptr++; // Skip '.'
      ptr = ParseRange(ptr, -2, exeDevice.exeSubIndices);
      if (!ptr) return {ERR_FATAL, "Unable to parse subindex in executor token %s", token.c_str()};
    }

    // Ensure that EXE_NIC has non-empty subindex
    if (exeDevice.exeType == EXE_NIC && exeDevice.exeSubIndices.size() == 0) {
      return {ERR_FATAL, "NIC executor requires specification of a subindex in executor token %s", token.c_str()};
1246
    }
1247
1248
1249
1250
1251
1252

    // Parse (optional) executor subslot
    ptr = ParseAlphaRange(ptr, exeDevice.exeSubSlots);
    if (!ptr) return {ERR_FATAL, "Unable to parse subslot in executor token %s", token.c_str()};

    return ERR_NONE;
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
  }

// Memory-related functions
//========================================================================================
  // Enable peer access between two GPUs
  static ErrResult EnablePeerAccess(int const deviceId, int const peerDeviceId)
  {
    int canAccess;
    ERR_CHECK(hipDeviceCanAccessPeer(&canAccess, deviceId, peerDeviceId));
    if (!canAccess)
gilbertlee-amd's avatar
gilbertlee-amd committed
1263
1264
      return {ERR_FATAL, "Peer access is unavailable between GPU devices %d to %d."
                         "For AMD hardware, check IOMMU configuration", peerDeviceId, deviceId};
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305

    ERR_CHECK(hipSetDevice(deviceId));
    hipError_t error = hipDeviceEnablePeerAccess(peerDeviceId, 0);
    if (error != hipSuccess && error != hipErrorPeerAccessAlreadyEnabled) {
      return {ERR_FATAL,
              "Unable to enable peer to peer access from %d to %d (%s)",
              deviceId, peerDeviceId, hipGetErrorString(error)};
    }
    return ERR_NONE;
  }

  // Check that CPU memory array of numBytes has been allocated on targetId NUMA node
  static ErrResult CheckPages(char* array, size_t numBytes, int targetId)
  {
    size_t const pageSize = getpagesize();
    size_t const numPages = (numBytes + pageSize - 1) / pageSize;

    std::vector<void *> pages(numPages);
    std::vector<int> status(numPages);

    pages[0] = array;
    for (int i = 1; i < numPages; i++) {
      pages[i] = (char*)pages[i-1] + pageSize;
    }

    long const retCode = move_pages(0, numPages, pages.data(), NULL, status.data(), 0);
    if (retCode)
      return {ERR_FATAL,
              "Unable to collect page table information for allocated memory. "
              "Ensure NUMA library is installed properly"};

    size_t mistakeCount = 0;
    for (size_t i = 0; i < numPages; i++) {
      if (status[i] < 0)
        return {ERR_FATAL,
                "Unexpected page status (%d) for page %llu", status[i], i};
      if (status[i] != targetId) mistakeCount++;
    }
    if (mistakeCount > 0) {
      return {ERR_FATAL,
              "%lu out of %lu pages for memory allocation were not on NUMA node %d."
gilbertlee-amd's avatar
gilbertlee-amd committed
1306
              " This could be due to hardware memory issues, or the use of numa-rebalancing daemons such as numad",
1307
1308
1309
1310
1311
1312
              mistakeCount, numPages, targetId};
    }
    return ERR_NONE;
  }

  // Allocate memory
1313
  static ErrResult AllocateMemory(MemDevice memDevice, size_t numBytes, void** memPtr, bool isShareable = false)
1314
1315
1316
1317
1318
1319
1320
1321
1322
  {
    if (numBytes == 0) {
      return {ERR_FATAL, "Unable to allocate 0 bytes"};
    }
    *memPtr = nullptr;

    MemType const& memType = memDevice.memType;

    if (IsCpuMemType(memType)) {
gilbertlee-amd's avatar
gilbertlee-amd committed
1323
1324
1325
1326
1327
1328
1329
1330
      // Determine which NUMA device to use
      int numaIdx = memDevice.memIndex;
      if (memType == MEM_CPU_CLOSEST) {
        numaIdx = GetClosestCpuNumaToGpu(memDevice.memIndex);
      }

      // Set NUMA policy prior to call to hipHostMalloc
      numa_set_preferred(numaIdx);
1331
1332

      // Allocate host-pinned memory (should respect NUMA mem policy)
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
      int flags = 0;
#if !defined(__NVCC__)
      flags |= hipHostMallocNumaUser;
#endif
      if (memType == MEM_CPU || memType == MEM_CPU_CLOSEST) {
        ERR_CHECK(hipHostMalloc((void **)memPtr, numBytes, flags));
      } else if (memType == MEM_CPU_COHERENT) {
#if defined (__NVCC__)
        return {ERR_FATAL, "Coherent pinned-CPU memory not supported on NVIDIA platform"};
#else
        ERR_CHECK(hipHostMalloc((void **)memPtr, numBytes, flags | hipHostMallocCoherent));
#endif
      } else if (memType == MEM_CPU_NONCOHERENT) {
1346
#if defined (__NVCC__)
1347
        return {ERR_FATAL, "Non-coherent pinned-CPU memory not supported on NVIDIA platform"};
1348
#else
1349
        ERR_CHECK(hipHostMalloc((void **)memPtr, numBytes, flags | hipHostMallocNonCoherent));
1350
#endif
1351
      } else if (memType == MEM_CPU_UNCACHED) {
1352
#if defined (__NVCC__)
1353
        return {ERR_FATAL, "Coherent CPU memory not supported on NVIDIA platform"};
1354
#else
1355
1356
1357
1358
1359
#if HIP_VERSION_MAJOR >= 7
        ERR_CHECK(hipHostMalloc((void **)memPtr, numBytes, flags | hipHostMallocUncached));
#else
        return {ERR_FATAL, "Uncached pinned-CPU memory requires ROCm 7.0"};
#endif
1360
1361
#endif
      } else if (memType == MEM_CPU_UNPINNED) {
gilbertlee-amd's avatar
gilbertlee-amd committed
1362
        *memPtr = numa_alloc_onnode(numBytes, numaIdx);
1363
1364
1365
1366
      }

      // Check that the allocated pages are actually on the correct NUMA node
      memset(*memPtr, 0, numBytes);
gilbertlee-amd's avatar
gilbertlee-amd committed
1367
      ERR_CHECK(CheckPages((char*)*memPtr, numBytes, numaIdx));
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380

      // Reset to default numa mem policy
      numa_set_preferred(-1);
    } else if (IsGpuMemType(memType)) {
      // Switch to the appropriate GPU
      ERR_CHECK(hipSetDevice(memDevice.memIndex));

      if (memType == MEM_GPU) {
        // Allocate GPU memory on appropriate device
        ERR_CHECK(hipMalloc((void**)memPtr, numBytes));
      } else if (memType == MEM_GPU_FINE) {
#if defined (__NVCC__)
        return {ERR_FATAL, "Fine-grained GPU memory not supported on NVIDIA platform"};
1381
1382
1383
1384
1385
1386
1387
#else
        int flag = hipDeviceMallocFinegrained;
        ERR_CHECK(hipExtMallocWithFlags((void**)memPtr, numBytes, flag));
#endif
      } else if (memType == MEM_GPU_UNCACHED) {
#if defined (__NVCC__)
        return {ERR_FATAL, "Uncached GPU memory not supported on NVIDIA platform"};
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
#else
        int flag = hipDeviceMallocUncached;
        ERR_CHECK(hipExtMallocWithFlags((void**)memPtr, numBytes, flag));
#endif
      } else if (memType == MEM_MANAGED) {
        ERR_CHECK(hipMallocManaged((void**)memPtr, numBytes));
      }

      // Clear the memory
      ERR_CHECK(hipMemset(*memPtr, 0, numBytes));
      ERR_CHECK(hipDeviceSynchronize());
    } else {
      return {ERR_FATAL, "Unsupported memory type (%d)", memType};
    }
    return ERR_NONE;
  }

  // Deallocate memory
  static ErrResult DeallocateMemory(MemType memType, void *memPtr, size_t const bytes)
  {
    // Avoid deallocating nullptr
    if (memPtr == nullptr)
      return {ERR_FATAL, "Attempted to free null pointer for %lu bytes", bytes};

    switch (memType) {
1413
    case MEM_CPU: case MEM_CPU_CLOSEST: case MEM_CPU_COHERENT: case MEM_CPU_NONCOHERENT: case MEM_CPU_UNCACHED:
1414
1415
1416
1417
1418
1419
1420
1421
1422
    {
      ERR_CHECK(hipHostFree(memPtr));
      break;
    }
    case MEM_CPU_UNPINNED:
    {
      numa_free(memPtr, bytes);
      break;
    }
1423
    case MEM_GPU : case MEM_GPU_FINE: case MEM_GPU_UNCACHED: case MEM_MANAGED:
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
    {
      ERR_CHECK(hipFree(memPtr));
      break;
    }
    default:
      return {ERR_FATAL, "Attempting to deallocate unrecognized memory type (%d)", memType};
    }
    return ERR_NONE;
  }

// Setup validation-related functions
//========================================================================================
1436
1437
1438
1439
  // This function resolves executors that may be indexed by "nearest"
  static ErrResult GetActualExecutor(ExeDevice     const& origExeDevice,
                                     ExeDevice&           actualExeDevice,
                                     int                  rankOverride = -1)
gilbertlee-amd's avatar
gilbertlee-amd committed
1440
1441
1442
1443
  {
    // By default, nothing needs to change
    actualExeDevice = origExeDevice;

1444
1445
1446
1447
1448
    // Check that executor rank is valid
    int exeRank = (rankOverride == -1 ? origExeDevice.exeRank : rankOverride);
    if (exeRank < 0 || exeRank >= GetNumRanks())
      return {ERR_FATAL, "Rank index must be between 0 and %d (instead of %d)", GetNumRanks() - 1, exeRank};

gilbertlee-amd's avatar
gilbertlee-amd committed
1449
1450
1451
    // When using NIC_NEAREST, remap to the closest NIC to the GPU
    if (origExeDevice.exeType == EXE_NIC_NEAREST) {
      actualExeDevice.exeType  = EXE_NIC;
1452
1453
1454
1455
1456
1457
      actualExeDevice.exeRank  = exeRank;
      std::vector<int> nicIndices;
      GetClosestNicsToGpu(nicIndices, origExeDevice.exeIndex, exeRank);
      if (origExeDevice.exeSlot < 0 || origExeDevice.exeSlot >= nicIndices.size()) {
        return {ERR_FATAL, "Rank %d GPU %d closest NIC slot %d is invalid (%lu slots detected)",
          exeRank, origExeDevice.exeIndex, origExeDevice.exeSlot, nicIndices.size()};
gilbertlee-amd's avatar
gilbertlee-amd committed
1458
      }
1459
1460
      actualExeDevice.exeIndex = nicIndices[actualExeDevice.exeSlot];
      actualExeDevice.exeSlot = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
1461
1462
1463
1464
    }
    return ERR_NONE;
  }

1465
1466
1467
1468
1469
1470
  // Validate that MemDevice exists
  static ErrResult CheckMemDevice(MemDevice const& memDevice)
  {
    if (memDevice.memType == MEM_NULL)
      return ERR_NONE;

1471
1472
1473
1474
1475
    if (memDevice.memRank < 0 || memDevice.memRank >= GetNumRanks()) {
      return {ERR_FATAL,
              "Rank index must be between 0 and %d (instead of %d)", GetNumRanks() - 1, memDevice.memRank};
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
1476
    if (IsCpuMemType(memDevice.memType) && memDevice.memType != MEM_CPU_CLOSEST) {
1477
      int numCpus = GetNumExecutors(EXE_CPU, memDevice.memRank);
1478
1479
      if (memDevice.memIndex < 0 || memDevice.memIndex >= numCpus)
        return {ERR_FATAL,
1480
                "CPU index must be between 0 and %d (instead of %d) on rank %d", numCpus - 1, memDevice.memIndex, memDevice.memRank};
1481
1482
1483
      return ERR_NONE;
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
1484
    if (IsGpuMemType(memDevice.memType) || memDevice.memType == MEM_CPU_CLOSEST) {
1485
      int numGpus = GetNumExecutors(EXE_GPU_GFX, memDevice.memRank);
1486
1487
      if (memDevice.memIndex < 0 || memDevice.memIndex >= numGpus)
        return {ERR_FATAL,
1488
                "GPU index must be between 0 and %d (instead of %d) on rank %d", numGpus - 1, memDevice.memIndex, memDevice.memRank};
gilbertlee-amd's avatar
gilbertlee-amd committed
1489
      if (memDevice.memType == MEM_CPU_CLOSEST) {
1490
1491
        if (GetClosestCpuNumaToGpu(memDevice.memIndex, memDevice.memRank) == -1) {
          return {ERR_FATAL, "Unable to determine closest NUMA node for GPU %d on rank %d", memDevice.memIndex, memDevice.memRank};
gilbertlee-amd's avatar
gilbertlee-amd committed
1492
1493
        }
      }
1494
1495
1496
1497
1498
      return ERR_NONE;
    }
    return {ERR_FATAL, "Unsupported memory type (%d)", memDevice.memType};
  }

1499
1500
  static void CheckMultiNodeConfigConsistency(ConfigOptions const& cfg,
                                              std::vector<ErrResult>& errors)
1501
  {
1502
1503
1504
    if (GetCommMode() == COMM_NONE) return;
    if (System::Get().IsVerbose()) {
      printf("[INFO] Rank %d checking config consistency\n", GetRank());
gilbertlee-amd's avatar
gilbertlee-amd committed
1505
    }
1506

1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
    // To check consistency, compare against rank 0
    int root = 0;

    #define ADD_ERROR(STR) errors.push_back({ERR_FATAL, STR " must be consistent across all ranks"})

    // Compare general options
    {
      GeneralOptions general = cfg.general;
      System::Get().Broadcast(root, sizeof(general), &general);
      if (general.numIterations      != cfg.general.numIterations)      ADD_ERROR("cfg.general.numIterations");
      if (general.numSubIterations   != cfg.general.numSubIterations)   ADD_ERROR("cfg.general.numSubIterations");
      if (general.numWarmups         != cfg.general.numWarmups)         ADD_ERROR("cfg.general.numWarmups");
      if (general.recordPerIteration != cfg.general.recordPerIteration) ADD_ERROR("cfg.general.recordPerIteration");
      if (general.useInteractive     != cfg.general.useInteractive)     ADD_ERROR("cfg.general.useInteractive");
    }

    // Compare data options
    {
      DataOptions data = cfg.data;
      System::Get().Broadcast(root, sizeof(data), &data);

      // data.alwaysValidate is permitted to be different across ranks

      if (data.blockBytes != cfg.data.blockBytes) ADD_ERROR("cfg.data.blockBytes");
      if (data.byteOffset != cfg.data.byteOffset) ADD_ERROR("cfg.data.byteOffset");

      size_t fillPatternSize = cfg.data.fillPattern.size();
      System::Get().Broadcast(root, sizeof(fillPatternSize), &fillPatternSize);
      if (fillPatternSize != cfg.data.fillPattern.size()) {
        ADD_ERROR("cfg.data.fillPattern");
      } else if (fillPatternSize > 0) {
        auto fillPatternTemp = cfg.data.fillPattern;
        System::Get().BroadcastVector(0, fillPatternTemp);
        for (size_t i = 0; i < fillPatternSize; i++) {
          if (fillPatternTemp[i] != cfg.data.fillPattern[i]) {
            ADD_ERROR("cfg.data.fillPattern");
            break;
          }
        }
      }

      size_t fillCompressSize = cfg.data.fillCompress.size();
      System::Get().Broadcast(root, sizeof(fillCompressSize), &fillCompressSize);
      if (fillCompressSize != cfg.data.fillCompress.size()) {
        ADD_ERROR("cfg.data.fillCompress");
      } else if (fillCompressSize > 0) {
        auto fillCompressTemp = cfg.data.fillCompress;
        System::Get().BroadcastVector(0, fillCompressTemp);
        for (size_t i = 0; i < fillCompressSize; i++) {
          if (fillCompressTemp[i] != cfg.data.fillCompress[i]) {
            ADD_ERROR("cfg.data.fillCompress");
            break;
          }
        }
      }

      // data.validateDirect is permitted to be different across ranks
      // data.validateSource is permitted to be different across ranks
    }

    // Compare GFX Executor options
    {
      GfxOptions gfx = cfg.gfx;
      System::Get().Broadcast(root, sizeof(gfx), &gfx);
      if (gfx.blockOrder     != cfg.gfx.blockOrder)     ADD_ERROR("cfg.gfx.blockOrder");
      if (gfx.blockSize      != cfg.gfx.blockSize)      ADD_ERROR("cfg.gfx.blockSize");
      // gfx.cuMask       is permitted to be different across ranks
      // gfx.perfXccTable is permitted to be different across ranks
      if (gfx.seType         != cfg.gfx.seType)         ADD_ERROR("cfg.gfx.seType");
      if (gfx.temporalMode   != cfg.gfx.temporalMode)   ADD_ERROR("cfg.gfx.temporalMode");
      if (gfx.unrollFactor   != cfg.gfx.unrollFactor)   ADD_ERROR("cfg.gfx.unrollFactor)");
      if (gfx.useHipEvents   != cfg.gfx.useHipEvents)   ADD_ERROR("cfg.gfx.useHipEvents");
      if (gfx.useMultiStream != cfg.gfx.useMultiStream) ADD_ERROR("cfg.gfx.useMultiStream");
      if (gfx.useSingleTeam  != cfg.gfx.useSingleTeam)  ADD_ERROR("cfg.gfx.useSingleTeam");
      if (gfx.waveOrder      != cfg.gfx.waveOrder)      ADD_ERROR("cfg.gfx.waveOrder");
      if (gfx.wordSize       != cfg.gfx.wordSize)       ADD_ERROR("cfg.gfx.wordSize");
    }

    // Compare DMA Executor options
    {
      DmaOptions dma = cfg.dma;
      System::Get().Broadcast(root, sizeof(dma), &dma);
      if (dma.useHipEvents != cfg.dma.useHipEvents) ADD_ERROR("cfg.dma.useHipEvents");
      if (dma.useHsaCopy   != cfg.dma.useHsaCopy)   ADD_ERROR("cfg.dma.useHsaCopy");
    }

    // Compare NIC options
    {
      NicOptions nic = cfg.nic;
      System::Get().Broadcast(root, sizeof(nic), &nic);
      if (nic.chunkBytes      != cfg.nic.chunkBytes)      ADD_ERROR("cfg.nic.chunkBytes");
      // nic.ibGidIndex  is permitted to be different across ranks
      // nic.ibPort      is permitted to be different across ranks
      if (nic.ipAddressFamily != cfg.nic.ipAddressFamily) ADD_ERROR("cfg.nic.ipAddressFamily");
      if (nic.maxRecvWorkReq  != cfg.nic.maxRecvWorkReq)  ADD_ERROR("cfg.nic.maxRecvWorkReq");
      if (nic.maxSendWorkReq  != cfg.nic.maxSendWorkReq)  ADD_ERROR("cfg.nic.maxSendWorkReq");
      // nic.queueSize   is permitted to be different across ranks
      if (nic.roceVersion     != cfg.nic.roceVersion)     ADD_ERROR("cfg.nic.roceVersion");
      if (nic.useRelaxedOrder != cfg.nic.useRelaxedOrder) ADD_ERROR("cfg.nic.useRelaxedOrder");
      if (nic.useNuma         != cfg.nic.useNuma)         ADD_ERROR("cfg.nic.useNuma");
    }

    #undef ADD_ERROR
  }

  // Validate configuration options - return trues if and only if an fatal error is detected
  static bool ConfigOptionsHaveErrors(ConfigOptions const&    cfg,
                                      std::vector<ErrResult>& errors)
  {
    // Check general options
    if (cfg.general.numWarmups < 0)
      errors.push_back({ERR_FATAL, "[general.numWarmups] must be a non-negative number"});

    // Check that config options are consistent (where necessary) across all ranks
    CheckMultiNodeConfigConsistency(cfg, errors);

    // Check data options
    if (cfg.data.blockBytes == 0 || cfg.data.blockBytes % 4)
      errors.push_back({ERR_FATAL, "[data.blockBytes] must be positive multiple of %lu", sizeof(float)});
    if (cfg.data.byteOffset < 0 || cfg.data.byteOffset % sizeof(float))
      errors.push_back({ERR_FATAL, "[data.byteOffset] must be positive multiple of %lu", sizeof(float)});
    if (cfg.data.fillCompress.size() > 0 && cfg.data.fillPattern.size() > 0)
      errors.push_back({ERR_WARN, "[data.fillCompress] will override [data.fillPattern] when both are specified"});
    if (cfg.data.fillCompress.size() > 0) {
      int sum = 0;
      for (int bin : cfg.data.fillCompress)
        sum += bin;
      if (sum != 100) {
        errors.push_back({ERR_FATAL, "[data.fillCompress] values must add up to 100"});
      }
    }
    if (cfg.data.fillCompress.size() > 5) {
      errors.push_back({ERR_FATAL, "[data.fillCompress] may only have up to 5 values"});
    }

    // Check GFX options
    if (cfg.gfx.blockOrder < 0 || cfg.gfx.blockOrder > 2)
      errors.push_back({ERR_FATAL,
          "[gfx.blockOrder] must be 0 for sequential, 1 for interleaved, or 2 for random"});
gilbertlee-amd's avatar
gilbertlee-amd committed
1646
1647
1648
1649

    if (cfg.gfx.useMultiStream && cfg.gfx.blockOrder > 0)
      errors.push_back({ERR_WARN, "[gfx.blockOrder] will be ignored when running in multi-stream mode"});

1650
1651
1652
1653
1654
1655
    int gfxMaxBlockSize = GetIntAttribute(ATR_GFX_MAX_BLOCKSIZE);
    if (cfg.gfx.blockSize < 0 || cfg.gfx.blockSize % 64 || cfg.gfx.blockSize > gfxMaxBlockSize)
      errors.push_back({ERR_FATAL,
                        "[gfx.blockSize] must be positive multiple of 64 less than or equal to %d",
                        gfxMaxBlockSize});

gilbertlee-amd's avatar
gilbertlee-amd committed
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
    if (cfg.gfx.temporalMode < 0 || cfg.gfx.temporalMode > 3)
      errors.push_back({ERR_FATAL,
                        "[gfx.temporalMode] must be non-negative and less than or equal to 3"});

#if defined(__NVCC__)
    if (cfg.gfx.temporalMode > 0)
      errors.push_back({ERR_FATAL,
          "[gfx.temporalMode] is not supported on NVIDIA hardware"});
#endif

1666
1667
1668
1669
1670
1671
1672
1673
1674
    int gfxMaxUnroll = GetIntAttribute(ATR_GFX_MAX_UNROLL);
    if (cfg.gfx.unrollFactor < 0 || cfg.gfx.unrollFactor > gfxMaxUnroll)
      errors.push_back({ERR_FATAL,
                        "[gfx.unrollFactor] must be non-negative and less than or equal to %d",
                        gfxMaxUnroll});
    if (cfg.gfx.waveOrder < 0 || cfg.gfx.waveOrder >= 6)
      errors.push_back({ERR_FATAL,
                        "[gfx.waveOrder] must be non-negative and less than 6"});

gilbertlee-amd's avatar
gilbertlee-amd committed
1675
1676
1677
    if (!(cfg.gfx.wordSize == 1 || cfg.gfx.wordSize == 2 || cfg.gfx.wordSize == 4))
      errors.push_back({ERR_FATAL, "[gfx.wordSize] must be either 1, 2 or 4"});

1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
    int numGpus = GetNumExecutors(EXE_GPU_GFX);
    int numXccs = GetNumExecutorSubIndices({EXE_GPU_GFX, 0});
    vector<vector<int>> const& table = cfg.gfx.prefXccTable;

    if (!table.empty()) {
      if (table.size() != numGpus) {
        errors.push_back({ERR_FATAL, "[gfx.prefXccTable] must be have size %dx%d", numGpus, numGpus});
      } else {
        for (int i = 0; i < table.size(); i++) {
          if (table[i].size() != numGpus) {
            errors.push_back({ERR_FATAL, "[gfx.prefXccTable] must be have size %dx%d", numGpus, numGpus});
            break;
          } else {
            for (auto x : table[i]) {
              if (x < 0 || x >= numXccs) {
                errors.push_back({ERR_FATAL, "[gfx.prefXccTable] must contain values between 0 and %d",
                    numXccs - 1});
                break;
              }
            }
          }
        }
      }
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
1703
1704
    // Check NIC options
#ifdef NIC_EXEC_ENABLED
1705
1706
1707
    if (cfg.nic.chunkBytes == 0 || (cfg.nic.chunkBytes % 4 != 0)) {
      errors.push_back({ERR_FATAL, "[nic.chunkBytes] must be a non-negative multiple of 4"});
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1708
1709
#endif

1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
    // NVIDIA specific
#if defined(__NVCC__)
    if (cfg.data.validateDirect)
      errors.push_back({ERR_FATAL, "[data.validateDirect] is not supported on NVIDIA hardware"});
#else
    // AMD specific
    // Check for largeBar enablement on GPUs
    for (int i = 0; i < numGpus; i++) {
      int isLargeBar = 0;
      hipError_t err = hipDeviceGetAttribute(&isLargeBar, hipDeviceAttributeIsLargeBar, i);
      if (err != hipSuccess) {
        errors.push_back({ERR_FATAL, "Unable to query if GPU %d has largeBAR enabled", i});
      } else if (!isLargeBar) {
        errors.push_back({ERR_WARN,
                          "Large BAR is not enabled for GPU %d in BIOS. "
                          "Large BAR is required to enable multi-gpu data access", i});
      }
    }
#endif

    // Check for fatal errors
    for (auto const& err : errors)
      if (err.errType == ERR_FATAL) return true;
    return false;
  }

1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
  static void CheckMultiNodeTransferConsistency(std::vector<Transfer> const& transfers,
                                                std::vector<ErrResult>& errors)
  {
    if (GetCommMode() == COMM_NONE) return;

    if (System::Get().IsVerbose()) {
      printf("[INFO] Rank %d checking transfers consistency\n", GetRank());
    }

    // To check consistency, compare against rank 0
    int root = 0;

    #define ADD_ERROR(STR)         \
    do {                          \
      isInconsistent = true;                                            \
      if (System::Get().IsVerbose())                                    \
        errors.push_back({ERR_FATAL, STR " must be the same for Transfer %d on all ranks", i}); \
    } while(0)

    size_t numTransfers = transfers.size();
    System::Get().Broadcast(root, sizeof(numTransfers), &numTransfers);
    if (numTransfers != transfers.size()) {
      errors.push_back({ERR_FATAL, "The number of Transfers to run must be consistent across ranks"});
    }

    bool isInconsistent = false;
    for (size_t i = 0; i < numTransfers; i++) {
      Transfer t = transfers[i];

      System::Get().Broadcast(root, sizeof(t.numBytes), &t.numBytes);
      System::Get().BroadcastVector(root, t.srcs);
      System::Get().BroadcastVector(root, t.dsts);
      System::Get().Broadcast(root, sizeof(t.exeDevice),   &t.exeDevice);
      System::Get().Broadcast(root, sizeof(t.exeSubIndex), &t.exeSubIndex);
      System::Get().Broadcast(root, sizeof(t.exeSubSlot),  &t.exeSubSlot);
      System::Get().Broadcast(root, sizeof(t.numSubExecs), &t.numSubExecs);

      if (t.numBytes    != transfers[i].numBytes)    ADD_ERROR("numBytes");
      if (t.srcs        != transfers[i].srcs)        ADD_ERROR("Source memory locations");
      if (t.dsts        != transfers[i].dsts)        ADD_ERROR("Destination memory locations");
      if (t.exeDevice < transfers[i].exeDevice ||
          transfers[i].exeDevice < t.exeDevice)      ADD_ERROR("Executor device");
      if (t.exeSubIndex != transfers[i].exeSubIndex) ADD_ERROR("Executor subindex");
      if (t.exeSubSlot  != transfers[i].exeSubSlot)  ADD_ERROR("Executor dst slot");
      if (t.numSubExecs != transfers[i].numSubExecs) ADD_ERROR("Num SubExecutors");
    }

    if (isInconsistent && !System::Get().IsVerbose()) {
      errors.push_back({ERR_FATAL, "Transfers to execute must be identical across all ranks"});
    }

    #undef ADD_ERROR
  }

1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
  // Validate Transfers to execute - returns true if and only if fatal error detected
  static bool TransfersHaveErrors(ConfigOptions         const& cfg,
                                  std::vector<Transfer> const& transfers,
                                  std::vector<ErrResult>&      errors)
  {
    std::set<ExeDevice>      executors;
    std::map<ExeDevice, int> transferCount;
    std::map<ExeDevice, int> useSubIndexCount;
    std::map<ExeDevice, int> totalSubExecs;

1800
1801
1802
    // Check that the set of requested transfers is consistent across all ranks
    CheckMultiNodeTransferConsistency(transfers, errors);

1803
1804
1805
1806
1807
1808
1809
    // Per-Transfer checks
    for (size_t i = 0; i < transfers.size(); i++) {
      Transfer const& t = transfers[i];

      if (t.numBytes == 0)
        errors.push_back({ERR_FATAL, "Transfer %d: Cannot perform 0-byte transfers", i});

1810
1811
1812
      // Each subexecutor is assigned a multiple of cfg.data.blockBytes, however this may
      // mean that some subexecutors might not have any work assigned to them if the amount to
      // transfer is small
1813
1814
1815
1816
1817
1818
1819
1820
      if (t.exeDevice.exeType == EXE_GPU_GFX || t.exeDevice.exeType == EXE_CPU) {
        size_t const N               = t.numBytes / sizeof(float);
        int    const targetMultiple  = cfg.data.blockBytes / sizeof(float);
        int    const maxSubExecToUse = std::min((size_t)(N + targetMultiple - 1) / targetMultiple,
                                                (size_t)t.numSubExecs);

        if (maxSubExecToUse < t.numSubExecs)
          errors.push_back({ERR_WARN,
1821
1822
                            "Transfer %d data size is too small - will only use %d of %d subexecutors due to blockBytes of %d",
                            i, maxSubExecToUse, t.numSubExecs, cfg.data.blockBytes});
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
      }

      // Check sources and destinations
      if (t.srcs.empty() && t.dsts.empty())
        errors.push_back({ERR_FATAL, "Transfer %d: Must have at least one source or destination", i});

      for (int j = 0; j < t.srcs.size(); j++) {
        ErrResult err = CheckMemDevice(t.srcs[j]);
        if (err.errType != ERR_NONE)
          errors.push_back({ERR_FATAL, "Transfer %d: SRC %d: %s", i, j, err.errMsg.c_str()});
      }
      for (int j = 0; j < t.dsts.size(); j++) {
        ErrResult err = CheckMemDevice(t.dsts[j]);
        if (err.errType != ERR_NONE)
          errors.push_back({ERR_FATAL, "Transfer %d: DST %d: %s", i, j, err.errMsg.c_str()});
      }

1840
1841
1842
1843
1844
1845
1846
      // Check executor rank
      if (t.exeDevice.exeRank < 0 || t.exeDevice.exeRank >= GetNumRanks()) {
        errors.push_back({ERR_FATAL,
            "Rank index for executor must be between 0 and %d (instead of %d)", GetNumRanks() - 1, t.exeDevice.exeRank});
        continue;
      }

1847
1848
      executors.insert(t.exeDevice);
      transferCount[t.exeDevice]++;
1849
1850
      int numExecutors = GetNumExecutors(t.exeDevice.exeType, t.exeDevice.exeRank);

1851
1852
      switch (t.exeDevice.exeType) {
      case EXE_CPU:
1853
        if (t.exeDevice.exeIndex < 0 || t.exeDevice.exeIndex >= numExecutors)
1854
          errors.push_back({ERR_FATAL,
1855
1856
                            "Transfer %d: CPU index must be between 0 and %d (instead of %d) for rank %d",
                            i, numExecutors - 1, t.exeDevice.exeIndex, t.exeDevice.exeRank});
1857
1858
        break;
      case EXE_GPU_GFX:
1859
        if (t.exeDevice.exeIndex < 0 || t.exeDevice.exeIndex >= numExecutors) {
1860
          errors.push_back({ERR_FATAL,
1861
1862
                            "Transfer %d: GFX index must be between 0 and %d (instead of %d) for rank %d",
                            i, numExecutors - 1, t.exeDevice.exeIndex, t.exeDevice.exeRank});
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
        } else {
          if (t.exeSubIndex != -1) {
#if defined(__NVCC__)
            errors.push_back({ERR_FATAL,
                              "Transfer %d: GFX executor subindex not supported on NVIDIA hardware", i});
#else
            useSubIndexCount[t.exeDevice]++;
            int numSubIndices = GetNumExecutorSubIndices(t.exeDevice);
            if (t.exeSubIndex >= numSubIndices)
              errors.push_back({ERR_FATAL,
1873
                  "Transfer %d: GFX subIndex (XCC) must be between 0 and %d for rank %d", i, numSubIndices - 1, t.exeDevice.exeRank});
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
#endif
          }
        }
        break;
      case EXE_GPU_DMA:
        if (t.srcs.size() != 1 || t.dsts.size() != 1) {
          errors.push_back({ERR_FATAL,
                            "Transfer %d: DMA executor must have exactly 1 source and 1 destination", i});
        }

1884
        if (t.exeDevice.exeIndex < 0 || t.exeDevice.exeIndex >= numExecutors) {
1885
          errors.push_back({ERR_FATAL,
1886
1887
                            "Transfer %d: DMA index must be between 0 and %d (instead of %d) for rank %d",
                            i, numExecutors - 1, t.exeDevice.exeIndex, t.exeDevice.exeRank});
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
          // Cannot proceed with any further checks
          continue;
        }

        if (t.exeSubIndex != -1) {
#if defined(__NVCC__)
          errors.push_back({ERR_FATAL,
                            "Transfer %d: DMA executor subindex not supported on NVIDIA hardware", i});
#else
          useSubIndexCount[t.exeDevice]++;
          int numSubIndices = GetNumExecutorSubIndices(t.exeDevice);
          if (t.exeSubIndex >= numSubIndices)
            errors.push_back({ERR_FATAL,
                              "Transfer %d: DMA subIndex (engine) must be between 0 and %d",
                              i, numSubIndices - 1});

          // Check that engine Id exists between agents
          hsa_agent_t srcAgent, dstAgent;
          ErrResult err;
1907
          err = System::Get().GetHsaAgent(t.srcs[0], srcAgent);
1908
1909
1910
1911
          if (err.errType != ERR_NONE) {
            errors.push_back(err);
            if (err.errType == ERR_FATAL) break;
          }
1912
          err = System::Get().GetHsaAgent(t.dsts[0], dstAgent);
1913
1914
1915
1916
1917
          if (err.errType != ERR_NONE) {
            errors.push_back(err);
            if (err.errType == ERR_FATAL) break;
          }

gilbertlee-amd's avatar
gilbertlee-amd committed
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
          // Skip check of engine Id mask for self copies
          if (srcAgent.handle != dstAgent.handle) {
            uint32_t engineIdMask = 0;
            err = hsa_amd_memory_copy_engine_status(dstAgent, srcAgent, &engineIdMask);
            if (err.errType != ERR_NONE) {
              errors.push_back(err);
              if (err.errType == ERR_FATAL) break;
            }
            hsa_amd_sdma_engine_id_t sdmaEngineId = (hsa_amd_sdma_engine_id_t)(1U << t.exeSubIndex);
            if (!(sdmaEngineId & engineIdMask)) {
              errors.push_back({ERR_FATAL,
                  "Transfer %d: DMA %d.%d does not exist or cannot copy between src/dst",
                  i, t.exeDevice.exeIndex, t.exeSubIndex});
            }
1932
1933
1934
1935
          }
#endif
        }

1936
        if (!IsGpuMemType(t.srcs[0].memType) && !IsGpuMemType(t.dsts[0].memType)) {
1937
1938
1939
1940
1941
1942
1943
1944
          errors.push_back({ERR_WARN,
              "Transfer %d: No GPU memory for source or destination.  Copy might not execute on DMA %d",
              i, t.exeDevice.exeIndex});
        } else {
          // Currently HIP will use src agent if source memory is GPU, otherwise dst agent
          if (IsGpuMemType(t.srcs[0].memType)) {
            if (t.srcs[0].memIndex != t.exeDevice.exeIndex) {
              errors.push_back({ERR_WARN,
1945
                  "Transfer %d: DMA executor may automatically switch to using the source memory device (%d) not (%d)",
1946
1947
1948
1949
                  i, t.srcs[0].memIndex, t.exeDevice.exeIndex});
            }
          } else if (t.dsts[0].memIndex != t.exeDevice.exeIndex) {
            errors.push_back({ERR_WARN,
1950
                "Transfer %d: DMA executor may automatically switch to using the destination memory device (%d) not (%d)",
1951
1952
1953
1954
                i, t.dsts[0].memIndex, t.exeDevice.exeIndex});
          }
        }
        break;
1955
      case EXE_NIC: case EXE_NIC_NEAREST:
gilbertlee-amd's avatar
gilbertlee-amd committed
1956
1957
#ifdef NIC_EXEC_ENABLED
      {
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
        // NIC Executors can only execute a copy operation
        if (t.srcs.size() != 1 || t.dsts.size() != 1) {
          errors.push_back({ERR_FATAL, "Transfer %d: NIC executor requires single SRC and single DST", i});
          break;
        }

        // NIC executor cannot do remote read + remote write - either src or dst must be local
        int srcExeRank = t.exeDevice.exeRank;
        int srcMemRank = t.srcs[0].memRank;
        int dstMemRank = t.dsts[0].memRank;
        int dstExeRank = (srcExeRank == srcMemRank ? dstMemRank : srcMemRank);
        if (srcMemRank != srcExeRank && dstMemRank != srcExeRank) {
          errors.push_back({ERR_FATAL,
              "Transfer %d: NIC executor rank (%d) must be same as SRC memory rank (%d) or DST memory rank (%d)", i, srcExeRank, srcMemRank, dstMemRank});
          break;
        }

        // The SRC NIC executor is the one that initiates either a (remote read/local write) or (local read/remote write) copy operation
gilbertlee-amd's avatar
gilbertlee-amd committed
1976
        ExeDevice srcExeDevice;
1977
        ErrResult errSrc = GetActualExecutor(t.exeDevice, srcExeDevice);
gilbertlee-amd's avatar
gilbertlee-amd committed
1978
        if (errSrc.errType != ERR_NONE) errors.push_back(errSrc);
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989

        // Check that the SRC NIC exists and is active
        if (srcExeDevice.exeIndex < 0 || srcExeDevice.exeIndex >= GetNumExecutors(EXE_NIC, srcExeRank)) {
          errors.push_back({ERR_FATAL, "Transfer %d: Rank %d SRC NIC executor indexes an out-of-range NIC (%d).  Detected %d NICs",
              i, srcExeRank, srcExeDevice.exeIndex, GetNumExecutors(EXE_NIC, srcExeRank)});
        } else if (!NicIsActive(srcExeDevice.exeIndex, srcExeDevice.exeRank)) {
          errors.push_back({ERR_FATAL, "Transfer %d: Rank %d SRC NIC executor %d is not active", i, srcExeDevice.exeRank, srcExeDevice.exeIndex});
        }

        // The DST NIC executor facilitates the copy but issues no commands
        ExeDevice dstOrgDevice = {t.exeDevice.exeType, t.exeSubIndex, dstExeRank, t.exeSubSlot};
gilbertlee-amd's avatar
gilbertlee-amd committed
1990
        ExeDevice dstExeDevice;
1991
1992
1993
1994
1995
1996
1997
1998
1999
        ErrResult errDst = GetActualExecutor(dstOrgDevice, dstExeDevice);

        // Check that the DST NIC exists and is active
        if (dstExeDevice.exeIndex < 0 || dstExeDevice.exeIndex >= GetNumExecutors(EXE_NIC, dstExeRank)) {
          errors.push_back({ERR_FATAL, "Transfer %d: Rank %d DST NIC executor indexes an out-of-range NIC (%d).  Detected %d NICs",
              i, dstExeRank, dstExeDevice.exeIndex, GetNumExecutors(EXE_NIC, dstExeRank)});
        } else if (!NicIsActive(dstExeDevice.exeIndex, dstExeDevice.exeRank)) {
          errors.push_back({ERR_FATAL, "Transfer %d: Rank %d DST NIC executor %d is not active", i, dstExeDevice.exeRank, dstExeDevice.exeIndex});
        }
gilbertlee-amd's avatar
gilbertlee-amd committed
2000
2001
      }
#else
2002
      errors.push_back({ERR_FATAL, "Transfer %d: NIC executor is requested but is not available.", i});
gilbertlee-amd's avatar
gilbertlee-amd committed
2003
#endif
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
      break;
      }

      // Check for multi-node support
      // Currently this is not supported for CPU/GPU executors
      if (IsCpuExeType(t.exeDevice.exeType) || IsGpuExeType(t.exeDevice.exeType)) {
        bool crossRank = false;
        for (auto const& src : t.srcs) {
          crossRank |= (src.memRank != t.exeDevice.exeRank);
        }
        for (auto const& dst : t.dsts) {
          crossRank |= (dst.memRank != t.exeDevice.exeRank);
        }
        if (crossRank) {
          errors.push_back({ERR_FATAL, "Transfer %d: Executor on rank %d can not access memory across ranks\n",
              i, t.exeDevice.exeRank});
        }
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
      }

      // Check subexecutors
      if (t.numSubExecs <= 0)
        errors.push_back({ERR_FATAL, "Transfer %d: # of subexecutors must be positive", i});
      else
        totalSubExecs[t.exeDevice] += t.numSubExecs;
    }

    int gpuMaxHwQueues = 4;
    if (getenv("GPU_MAX_HW_QUEUES"))
      gpuMaxHwQueues = atoi(getenv("GPU_MAX_HW_QUEUES"));

    // Aggregate checks
    for (auto const& exeDevice : executors) {
      switch (exeDevice.exeType) {
      case EXE_CPU:
      {
        // Check total number of subexecutors requested
        int numCpuSubExec = GetNumSubExecutors(exeDevice);
        if (totalSubExecs[exeDevice] > numCpuSubExec)
          errors.push_back({ERR_WARN,
                            "CPU %d requests %d total cores however only %d available. "
                            "Serialization will occur",
                            exeDevice.exeIndex, totalSubExecs[exeDevice], numCpuSubExec});
        break;
      }
      case EXE_GPU_GFX:
      {
        // Check total number of subexecutors requested
        int numGpuSubExec = GetNumSubExecutors(exeDevice);
2052
2053
2054
2055
2056
        // For warp-level dispatch, multiply by warps per threadblock
        if (cfg.gfx.seType == 1) {
          int warpsPerBlock = cfg.gfx.blockSize / GetWarpSize(&errors);
          numGpuSubExec *= warpsPerBlock;
        }
2057
2058
        if (totalSubExecs[exeDevice] > numGpuSubExec)
          errors.push_back({ERR_WARN,
2059
                            "GPU %d requests %d total %s however only %d available. "
2060
                            "Serialization will occur",
2061
2062
                            exeDevice.exeIndex, totalSubExecs[exeDevice],
                            cfg.gfx.seType == 0 ? "CUs" : "warps", numGpuSubExec});
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
        // Check that if executor subindices are used, all Transfers specify executor subindices
        if (useSubIndexCount[exeDevice] > 0 && useSubIndexCount[exeDevice] != transferCount[exeDevice]) {
          errors.push_back({ERR_FATAL,
                            "GPU %d specifies XCC on only %d of %d Transfers. "
                            "Must either specific none or all",
                            exeDevice.exeIndex, useSubIndexCount[exeDevice], transferCount[exeDevice]});
        }

        if (cfg.gfx.useMultiStream && transferCount[exeDevice] > gpuMaxHwQueues) {
          errors.push_back({ERR_WARN,
                            "GPU %d attempting %d parallel transfers, however GPU_MAX_HW_QUEUES only set to %d",
                            exeDevice.exeIndex, transferCount[exeDevice], gpuMaxHwQueues});
        }
        break;
      }
      case EXE_GPU_DMA:
      {
        // Check that if executor subindices are used, all Transfers specify executor subindices
        if (useSubIndexCount[exeDevice] > 0 && useSubIndexCount[exeDevice] != transferCount[exeDevice]) {
          errors.push_back({ERR_FATAL,
                            "DMA %d specifies engine on only %d of %d Transfers. "
                            "Must either specific none or all",
                            exeDevice.exeIndex, useSubIndexCount[exeDevice], transferCount[exeDevice]});
        }
        if (transferCount[exeDevice] > gpuMaxHwQueues) {
          errors.push_back({ERR_WARN,
                           "DMA %d attempting %d parallel transfers, however GPU_MAX_HW_QUEUES only set to %d",
                           exeDevice.exeIndex, transferCount[exeDevice], gpuMaxHwQueues});
        }

        char* enableSdma = getenv("HSA_ENABLE_SDMA");
        if (enableSdma && !strcmp(enableSdma, "0"))
          errors.push_back({ERR_WARN,
                            "DMA functionality disabled due to environment variable HSA_ENABLE_SDMA=0. "
                            "DMA %d copies will fallback to blit (GFX) kernels", exeDevice.exeIndex});
        break;
      }
      default:
        break;
      }
    }

    // Check for fatal errors
    for (auto const& err : errors)
      if (err.errType == ERR_FATAL) return true;
    return false;
  }

// Internal data structures
//========================================================================================

  // Parameters for each SubExecutor
  struct SubExecParam
  {
    // Inputs
    size_t                     N;                 ///< Number of floats this subExecutor works on
    int                        numSrcs;           ///< Number of source arrays
    int                        numDsts;           ///< Number of destination arrays
    float*                     src[MAX_SRCS];     ///< Source array pointers
    float*                     dst[MAX_DSTS];     ///< Destination array pointers
    int32_t                    preferredXccId;    ///< XCC ID to execute on (GFX only)

    // Prepared
    int                        teamSize;          ///< Index of this sub executor amongst team
    int                        teamIdx;           ///< Size of team this sub executor is part of

    // Outputs
    long long                  startCycle;        ///< Start timestamp for in-kernel timing (GPU-GFX executor)
    long long                  stopCycle;         ///< Stop  timestamp for in-kernel timing (GPU-GFX executor)
    uint32_t                   hwId;              ///< Hardware ID
    uint32_t                   xccId;             ///< XCC ID
  };

  // Internal resources allocated per Transfer
  struct TransferResources
  {
    int                        transferIdx;       ///< The associated Transfer
    size_t                     numBytes;          ///< Number of bytes to Transfer
    vector<float*>             srcMem;            ///< Source memory
    vector<float*>             dstMem;            ///< Destination memory
    vector<SubExecParam>       subExecParamCpu;   ///< Defines subarrays for each subexecutor
    vector<int>                subExecIdx;        ///< Indices into subExecParamGpu
gilbertlee-amd's avatar
gilbertlee-amd committed
2145
    int                        numaNode;          ///< NUMA node to use for this Transfer
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157

    // For GFX executor
    SubExecParam*              subExecParamGpuPtr;

    // For targeted-SDMA
#if !defined(__NVCC__)
    hsa_agent_t                dstAgent;          ///< DMA destination memory agent
    hsa_agent_t                srcAgent;          ///< DMA source memory agent
    hsa_signal_t               signal;            ///< HSA signal for completion
    hsa_amd_sdma_engine_id_t   sdmaEngineId;      ///< DMA engine ID
#endif

gilbertlee-amd's avatar
gilbertlee-amd committed
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
// For IBV executor
#ifdef NIC_EXEC_ENABLED
    int                        srcNicIndex;       ///< SRC NIC index
    int                        dstNicIndex;       ///< DST NIC index
    ibv_context*               srcContext;        ///< Device context for SRC NIC
    ibv_context*               dstContext;        ///< Device context for DST NIC
    ibv_pd*                    srcProtect;        ///< Protection domain for SRC NIC
    ibv_pd*                    dstProtect;        ///< Protection domain for DST NIC
    ibv_cq*                    srcCompQueue;      ///< Completion queue for SRC NIC
    ibv_cq*                    dstCompQueue;      ///< Completion queue for DST NIC
    ibv_port_attr              srcPortAttr;       ///< Port attributes for SRC NIC
    ibv_port_attr              dstPortAttr;       ///< Port attributes for DST NIC
    ibv_gid                    srcGid;            ///< GID handle for SRC NIC
    ibv_gid                    dstGid;            ///< GID handle for DST NIC
    vector<ibv_qp*>            srcQueuePairs;     ///< Queue pairs for SRC NIC
    vector<ibv_qp*>            dstQueuePairs;     ///< Queue pairs for DST NIC
    ibv_mr*                    srcMemRegion;      ///< Memory region for SRC
    ibv_mr*                    dstMemRegion;      ///< Memory region for DST
    uint8_t                    qpCount;           ///< Number of QPs to be used for transferring data
2177
2178
2179
    bool                       srcIsExeNic;       ///< Whether SRC or DST NIC initiates traffic
    vector<vector<ibv_sge>>    sgePerQueuePair;   ///< Scatter-gather elements per queue pair
    vector<vector<ibv_send_wr>>sendWorkRequests;  ///< Send work requests per queue pair
gilbertlee-amd's avatar
gilbertlee-amd committed
2180
2181
#endif

2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
    // Counters
    double                     totalDurationMsec; ///< Total duration for all iterations for this Transfer
    vector<double>             perIterMsec;       ///< Duration for each individual iteration
    vector<set<pair<int,int>>> perIterCUs;        ///< GFX-Executor only. XCC:CU used per iteration
  };

  // Internal resources allocated per Executor
  struct ExeInfo
  {
    size_t                     totalBytes;        ///< Total bytes this executor transfers
    double                     totalDurationMsec; ///< Total duration for all iterations for this Executor
    int                        totalSubExecs;     ///< Total number of subExecutors to use
    bool                       useSubIndices;     ///< Use subexecutor indicies
    int                        numSubIndices;     ///< Number of subindices this ExeDevice has
    vector<SubExecParam>       subExecParamCpu;   ///< Subexecutor parameters for this executor
    vector<TransferResources>  resources;         ///< Per-Transfer resources

    // For GPU-Executors
    SubExecParam*              subExecParamGpu;   ///< GPU copy of subExecutor parameters
    vector<hipStream_t>        streams;           ///< HIP streams to launch on
    vector<hipEvent_t>         startEvents;       ///< HIP start timing event
    vector<hipEvent_t>         stopEvents;        ///< HIP stop timing event
gilbertlee-amd's avatar
gilbertlee-amd committed
2204
    int                        wallClockRate;     ///< (GFX-only) Device wall clock rate
2205
2206
  };

gilbertlee-amd's avatar
gilbertlee-amd committed
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
  // Structure to track PCIe topology
  struct PCIeNode
  {
    std::string        address;                   ///< PCIe address for this PCIe node
    std::string        description;               ///< Description for this PCIe node
    std::set<PCIeNode> children;                  ///< Children PCIe nodes

    // Default constructor
    PCIeNode() : address(""), description("") {}

    // Constructor
    PCIeNode(std::string const& addr) : address(addr) {}

    // Constructor
    PCIeNode(std::string const& addr, std::string const& desc)
      :address(addr), description(desc) {}

    // Comparison operator for std::set
    bool operator<(PCIeNode const& other) const {
      return address < other.address;
    }
  };

#ifdef NIC_EXEC_ENABLED
  // Structure to track information about IBV devices
  struct IbvDevice
  {
    ibv_device* devicePtr;
    std::string name;
    std::string busId;
    bool        hasActivePort;
    int         numaNode;
gilbertlee-amd's avatar
gilbertlee-amd committed
2239
2240
2241
    int         gidIndex;
    std::string gidDescriptor;
    bool        isRoce;
gilbertlee-amd's avatar
gilbertlee-amd committed
2242
2243
2244
2245
2246
2247
  };
#endif

#ifdef NIC_EXEC_ENABLED
// Function to collect information about IBV devices
//========================================================================================
gilbertlee-amd's avatar
gilbertlee-amd committed
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
static bool IsConfiguredGid(union ibv_gid const& gid)
  {
    const struct in6_addr *a = (struct in6_addr *) gid.raw;
    int trailer = (a->s6_addr32[1] | a->s6_addr32[2] | a->s6_addr32[3]);
    if (((a->s6_addr32[0] | trailer) == 0UL) ||
        ((a->s6_addr32[0] == htonl(0xfe800000)) && (trailer == 0UL))) {
      return false;
    }
    return true;
  }

  static bool LinkLocalGid(union ibv_gid const& gid)
  {
    const struct in6_addr *a = (struct in6_addr *) gid.raw;
    if (a->s6_addr32[0] == htonl(0xfe800000) && a->s6_addr32[1] == 0UL) {
      return true;
    }
    return false;
  }

  static ErrResult GetRoceVersionNumber(struct ibv_context* const& context,
                                        int const&  portNum,
                                        int const&  gidIndex,
                                        int&        version)
  {
    char const* deviceName = ibv_get_device_name(context->device);
    char gidRoceVerStr[16]      = {};
    char roceTypePath[PATH_MAX] = {};
    sprintf(roceTypePath, "/sys/class/infiniband/%s/ports/%d/gid_attrs/types/%d",
            deviceName, portNum, gidIndex);

    int fd = open(roceTypePath, O_RDONLY);
    if (fd == -1)
      return {ERR_FATAL, "Failed while opening RoCE file path (%s)", roceTypePath};

    int ret = read(fd, gidRoceVerStr, 15);
    close(fd);

    if (ret == -1)
      return {ERR_FATAL, "Failed while reading RoCE version"};

    if (strlen(gidRoceVerStr)) {
      if (strncmp(gidRoceVerStr, "IB/RoCE v1", strlen("IB/RoCE v1")) == 0
          || strncmp(gidRoceVerStr, "RoCE v1", strlen("RoCE v1")) == 0) {
        version = 1;
      }
      else if (strncmp(gidRoceVerStr, "RoCE v2", strlen("RoCE v2")) == 0) {
        version = 2;
      }
    }
    return ERR_NONE;
  }

  static bool IsIPv4MappedIPv6(const union ibv_gid &gid)
  {
    // look for ::ffff:x.x.x.x format
    // From Broadcom documentation
    // https://techdocs.broadcom.com/us/en/storage-and-ethernet-connectivity/ethernet-nic-controllers/bcm957xxx/adapters/frequently-asked-questions1.html
    // "The IPv4 address is really an IPv4 address mapped into the IPv6 address space.
    // This can be identified by 80 “0” bits, followed by 16 “1” bits (“FFFF” in hexadecimal)
    // followed by the original 32-bit IPv4 address."
    return (gid.global.subnet_prefix == 0    &&
            gid.raw[8]               == 0    &&
            gid.raw[9]               == 0    &&
            gid.raw[10]              == 0xff &&
            gid.raw[11]              == 0xff);
  }

  static ErrResult GetGidIndex(struct ibv_context*          context,
                               int const&                   gidTblLen,
                               int const&                   portNum,
                               std::pair<int, std::string>& gidInfo)
  {
    if(gidInfo.first >= 0) return ERR_NONE; // honor user choice
    union ibv_gid gid;

    GidPriority highestPriority = GidPriority::UNKNOWN;
    int gidIndex = -1;

    for (int i = 0; i < gidTblLen; ++i) {
      IBV_CALL(ibv_query_gid, context, portNum, i, &gid);
      if (!IsConfiguredGid(gid)) continue;
      int gidCurrRoceVersion;
      if(GetRoceVersionNumber(context, portNum, i, gidCurrRoceVersion).errType != ERR_NONE) continue;
      GidPriority currPriority;
      if (IsIPv4MappedIPv6(gid)) {
        currPriority = (gidCurrRoceVersion == 2) ? GidPriority::ROCEV2_IPV4 : GidPriority::ROCEV1_IPV4;
      } else if (!LinkLocalGid(gid)) {
        currPriority = (gidCurrRoceVersion == 2) ? GidPriority::ROCEV2_IPV6 : GidPriority::ROCEV1_IPV6;
      } else {
        currPriority = (gidCurrRoceVersion == 2) ? GidPriority::ROCEV2_LINK_LOCAL : GidPriority::ROCEV1_LINK_LOCAL;
      }
      if(currPriority > highestPriority) {
        highestPriority = currPriority;
        gidIndex = i;
      }
    }

    if (highestPriority == GidPriority::UNKNOWN) {
      gidInfo.first = -1;
      return {ERR_FATAL, "Failed to auto-detect a valid GID index. Try setting it manually through IB_GID_INDEX"};
    }
    gidInfo.first = gidIndex;
    gidInfo.second = GidPriorityStr[highestPriority];
    return ERR_NONE;
  }

gilbertlee-amd's avatar
gilbertlee-amd committed
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
  static vector<IbvDevice>& GetIbvDeviceList()
  {
    static bool isInitialized = false;
    static vector<IbvDevice> ibvDeviceList = {};

    // Build list on first use
    if (!isInitialized) {

      // Query the number of IBV devices
      int numIbvDevices = 0;
      ibv_device** deviceList = ibv_get_device_list(&numIbvDevices);

2367
2368
2369
2370
      // Check for NIC_FILTER
      // By default, accept all NIC names
      std::string nicFilterPattern = getenv("NIC_FILTER") ? getenv("NIC_FILTER") : ".*";

gilbertlee-amd's avatar
gilbertlee-amd committed
2371
2372
2373
      if (deviceList && numIbvDevices > 0) {
        // Loop over each device to collect information
        for (int i = 0; i < numIbvDevices; i++) {
2374
2375
2376
2377

          // Filter by name
          if (!std::regex_match(deviceList[i]->name, std::regex(nicFilterPattern))) continue;

gilbertlee-amd's avatar
gilbertlee-amd committed
2378
2379
2380
2381
2382
2383
2384
2385
2386
          IbvDevice ibvDevice;
          ibvDevice.devicePtr = deviceList[i];
          ibvDevice.name = deviceList[i]->name;
          ibvDevice.hasActivePort = false;
          {
            struct ibv_context *context = ibv_open_device(ibvDevice.devicePtr);
            if (context) {
              struct ibv_device_attr deviceAttr;
              if (!ibv_query_device(context, &deviceAttr)) {
gilbertlee-amd's avatar
gilbertlee-amd committed
2387
2388
                int activePort;
                ibvDevice.gidIndex = -1;
gilbertlee-amd's avatar
gilbertlee-amd committed
2389
2390
2391
                for (int port = 1; port <= deviceAttr.phys_port_cnt; ++port) {
                  struct ibv_port_attr portAttr;
                  if (ibv_query_port(context, port, &portAttr)) continue;
gilbertlee-amd's avatar
gilbertlee-amd committed
2392
2393
                  if (portAttr.state == IBV_PORT_ACTIVE) {
                    activePort = port;
gilbertlee-amd's avatar
gilbertlee-amd committed
2394
                    ibvDevice.hasActivePort = true;
gilbertlee-amd's avatar
gilbertlee-amd committed
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
                    if(portAttr.link_layer == IBV_LINK_LAYER_ETHERNET) {
                      ibvDevice.isRoce = true;
                      std::pair<int, std::string> gidInfo (-1, "");
                      auto res = GetGidIndex(context, portAttr.gid_tbl_len, activePort, gidInfo);
                      if (res.errType == ERR_NONE) {
                        ibvDevice.gidIndex = gidInfo.first;
                        ibvDevice.gidDescriptor = gidInfo.second;
                      }
                    }
                    break;
                  }
gilbertlee-amd's avatar
gilbertlee-amd committed
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
                }
              }
              ibv_close_device(context);
            }
          }
          ibvDevice.busId = "";
          {
            std::string device_path(ibvDevice.devicePtr->dev_path);
            if (std::filesystem::exists(device_path)) {
              std::string pciPath = std::filesystem::canonical(device_path + "/device").string();
              std::size_t pos = pciPath.find_last_of('/');
              if (pos != std::string::npos) {
                ibvDevice.busId = pciPath.substr(pos + 1);
              }
            }
          }

          // Get nearest numa node for this device
          ibvDevice.numaNode = -1;
          std::filesystem::path devicePath = "/sys/bus/pci/devices/" + ibvDevice.busId + "/numa_node";
          std::string canonicalPath = std::filesystem::canonical(devicePath).string();

          if (std::filesystem::exists(canonicalPath)) {
            std::ifstream file(canonicalPath);
            if (file.is_open()) {
              std::string numaNodeStr;
              std::getline(file, numaNodeStr);
              int numaNodeVal;
              if (sscanf(numaNodeStr.c_str(), "%d", &numaNodeVal) == 1)
                ibvDevice.numaNode = numaNodeVal;
              file.close();
            }
          }
          ibvDeviceList.push_back(ibvDevice);
        }
      }
      ibv_free_device_list(deviceList);
      isInitialized = true;
    }
    return ibvDeviceList;
  }
#endif // NIC_EXEC_ENABLED

#ifdef NIC_EXEC_ENABLED
// PCIe-related functions
//========================================================================================

  // Prints off PCIe tree
2454
2455
2456
  static inline void PrintPCIeTree(PCIeNode    const& node,
                                   std::string const& prefix = "",
                                   bool               isLast = true)
gilbertlee-amd's avatar
gilbertlee-amd committed
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
  {
    if (!node.address.empty()) {
      printf("%s%s%s", prefix.c_str(), (isLast ? "└── " : "├── "), node.address.c_str());
      if (!node.description.empty()) {
        printf("(%s)", node.description.c_str());
      }
      printf("\n");
    }
    auto const& children = node.children;
    for (auto it = children.begin(); it != children.end(); ++it) {
      PrintPCIeTree(*it, prefix + (isLast ? "    " : "│   "), std::next(it) == children.end());
    }
  }

  // Inserts nodes along pcieAddress down a tree starting from root
  static ErrResult InsertPCIePathToTree(std::string const& pcieAddress,
                                        std::string const& description,
                                        PCIeNode&          root)
  {
    std::filesystem::path devicePath = "/sys/bus/pci/devices/" + pcieAddress;
    std::string canonicalPath = std::filesystem::canonical(devicePath).string();

    if (!std::filesystem::exists(devicePath)) {
      return {ERR_FATAL, "Device path %s does not exist", devicePath.c_str()};
    }

    std::istringstream iss(canonicalPath);
    std::string token;

    PCIeNode* currNode = &root;
    while (std::getline(iss, token, '/')) {
      auto it = (currNode->children.insert(PCIeNode(token))).first;
      currNode = const_cast<PCIeNode*>(&(*it));
    }
    currNode->description = description;

    return ERR_NONE;
  }

  // Returns root node for PCIe tree.  Constructed on first use
  static PCIeNode* GetPCIeTreeRoot()
  {
    static bool isInitialized = false;
    static PCIeNode pcieRoot;

    // Build PCIe tree on first use
    if (!isInitialized) {
      // Add NICs to the tree
      auto const& ibvDeviceList = GetIbvDeviceList();
      for (IbvDevice const& ibvDevice : ibvDeviceList) {
        if (!ibvDevice.hasActivePort || ibvDevice.busId == "") continue;
        InsertPCIePathToTree(ibvDevice.busId, ibvDevice.name, pcieRoot);
      }

      // Add GPUs to the tree
2512
2513
      int numGpus = 0;
      if (hipGetDeviceCount(&numGpus) != hipSuccess) numGpus = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
      for (int i = 0; i < numGpus; ++i) {
        char hipPciBusId[64];
        if (hipDeviceGetPCIBusId(hipPciBusId, sizeof(hipPciBusId), i) == hipSuccess) {
          InsertPCIePathToTree(hipPciBusId, "GPU " + std::to_string(i), pcieRoot);
        }
      }
#ifdef VERBS_DEBUG
      PrintPCIeTree(pcieRoot);
#endif
      isInitialized = true;
    }
    return &pcieRoot;
  }

  // Finds the lowest common ancestor in PCIe tree between two nodes
  static PCIeNode const* GetLcaBetweenNodes(PCIeNode    const* root,
                                            std::string const& node1Address,
                                            std::string const& node2Address)
  {
    if (!root || root->address == node1Address || root->address == node2Address)
      return root;

    PCIeNode const* lcaFound1 = nullptr;
    PCIeNode const* lcaFound2 = nullptr;

    // Recursively iterate over children
    for (auto const& child : root->children) {
      PCIeNode const* lca = GetLcaBetweenNodes(&child, node1Address, node2Address);
      if (!lca) continue;
      if (!lcaFound1) {
        // First time found
        lcaFound1 = lca;
      } else {
        // Second time found
        lcaFound2 = lca;
        break;
      }
    }

    // If two children were found, then current node is the lowest common ancestor
    return (lcaFound1 && lcaFound2) ? root : lcaFound1;
  }

  // Gets the depth of an node in the PCIe tree
  static int GetLcaDepth(std::string const&     targetBusID,
                         PCIeNode const* const& node,
                         int                    depth = 0)
  {
    if (!node) return -1;
    if (targetBusID == node->address) return depth;

    for (auto const& child : node->children) {
      int distance = GetLcaDepth(targetBusID, &child, depth + 1);
      if (distance != -1)
        return distance;
    }
    return -1;
  }

  // Function to extract the bus number from a PCIe address (domain:bus:device.function)
  static int ExtractBusNumber(std::string const& pcieAddress)
  {
    int domain, bus, device, function;
    char delimiter;

    std::istringstream iss(pcieAddress);
    iss >> std::hex >> domain >> delimiter >> bus >> delimiter >> device >> delimiter >> function;
    if (iss.fail()) {
#ifdef VERBS_DEBUG
      printf("Invalid PCIe address format: %s\n", pcieAddress.c_str());
#endif
      return -1;
    }
    return bus;
  }

  // Function to compute the distance between two bus IDs
  static int GetBusIdDistance(std::string const& pcieAddress1,
                              std::string const& pcieAddress2)
  {
    int bus1 = ExtractBusNumber(pcieAddress1);
    int bus2 = ExtractBusNumber(pcieAddress2);
    return (bus1 < 0 || bus2 < 0) ? -1 : std::abs(bus1 - bus2);
  }

  // Given a target busID and a set of candidate devices, returns a set of indices
  // that is "closest" to the target
  static std::set<int> GetNearestDevicesInTree(std::string              const& targetBusId,
                                               std::vector<std::string> const& candidateBusIdList)
  {
    int maxDepth = -1;
    int minDistance = std::numeric_limits<int>::max();
    std::set<int> matches = {};

    // Loop over the candidates to find the ones with the lowest common ancestor (LCA)
    for (int i = 0; i < candidateBusIdList.size(); i++) {
      std::string const& candidateBusId = candidateBusIdList[i];
      if (candidateBusId == "") continue;
      PCIeNode const* lca = GetLcaBetweenNodes(GetPCIeTreeRoot(), targetBusId, candidateBusId);
      if (!lca) continue;

      int depth = GetLcaDepth(lca->address, GetPCIeTreeRoot());
      int currDistance = GetBusIdDistance(targetBusId, candidateBusId);

      // When more than one LCA match is found, choose the one with smallest busId difference
      // NOTE: currDistance could be -1, which signals problem with parsing, however still
      //       remains a valid "closest" candidate, so is included
      if (depth > maxDepth || (depth == maxDepth && depth >= 0 && currDistance < minDistance)) {
        maxDepth = depth;
        matches.clear();
        matches.insert(i);
        minDistance = currDistance;
      } else if (depth == maxDepth && depth >= 0 && currDistance == minDistance) {
        matches.insert(i);
      }
    }
    return matches;
  }
#endif // NIC_EXEC_ENABLED

#ifdef NIC_EXEC_ENABLED
// IB Verbs-related functions
//========================================================================================

  // Create a queue pair
  static ErrResult CreateQueuePair(ConfigOptions const& cfg,
                                   struct ibv_pd*       pd,
                                   struct ibv_cq*       cq,
                                   struct ibv_qp*&      qp)
  {
    // Set queue pair attributes
    struct ibv_qp_init_attr attr = {};
    attr.qp_type          = IBV_QPT_RC;                  // Set type to reliable connection
    attr.send_cq          = cq;                          // Send completion queue
    attr.recv_cq          = cq;                          // Recv completion queue
    attr.cap.max_send_wr  = cfg.nic.maxSendWorkReq;      // Max send work requests
    attr.cap.max_recv_wr  = cfg.nic.maxRecvWorkReq;      // Max recv work requests
    attr.cap.max_send_sge = 1;                           // Max send scatter-gather entries
    attr.cap.max_recv_sge = 1;                           // Max recv scatter-gather entries

    qp = ibv_create_qp(pd, &attr);
    if (qp == NULL)
      return {ERR_FATAL, "Error while creating QP"};

    return ERR_NONE;
  }

  // Initialize a queue pair
  static ErrResult InitQueuePair(struct ibv_qp* qp,
                                 uint8_t        port,
                                 unsigned       flags)
  {
    struct ibv_qp_attr attr = {};                        // Clear all attributes
    attr.qp_state        = IBV_QPS_INIT;                 // Set the QP state to INIT
    attr.pkey_index      = 0;                            // Set the partition key index to 0
    attr.port_num        = port;                         // Set the port number to the defined IB_PORT
    attr.qp_access_flags = flags;                        // Set the QP access flags to the provided flags

    int ret = ibv_modify_qp(qp, &attr,
                            IBV_QP_STATE      |          // Modify the QP state
                            IBV_QP_PKEY_INDEX |          // Modify the partition key index
                            IBV_QP_PORT       |          // Modify the port number
                            IBV_QP_ACCESS_FLAGS);        // Modify the access flags

    if (ret != 0)
      return {ERR_FATAL, "Error during QP Init. IB Verbs Error code: %d", ret};

    return ERR_NONE;
  }

2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
  // Structure used to exchange connection information
  struct __attribute__((packed)) ConnInfo
  {
    uint16_t lid;     // Local  routing id
    ibv_gid  gid;     // Global routing id (RoCE)
    int      gidIdx;  // Global routing id index (RoCE)
    uint32_t qpn;     // Queue pair number
    uint32_t rkey;    // Remote memory access key
    uint64_t vaddr;   // Remote virtual address of the memory region
  };

gilbertlee-amd's avatar
gilbertlee-amd committed
2695
2696
  // Transition QueuePair to Ready to Receive State
  static ErrResult TransitionQpToRtr(ibv_qp*         qp,
2697
                                     ConnInfo const& connInfo,
gilbertlee-amd's avatar
gilbertlee-amd committed
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
                                     uint8_t  const& port,
                                     bool     const& isRoCE,
                                     ibv_mtu  const& mtu)
  {
    // Prepare QP attributes
    struct ibv_qp_attr attr = {};
    attr.qp_state           = IBV_QPS_RTR;
    attr.path_mtu           = mtu;
    attr.rq_psn             = 0;
    attr.max_dest_rd_atomic = 1;
    attr.min_rnr_timer      = 12;
    if (isRoCE) {
      attr.ah_attr.is_global                     = 1;
2711
2712
      attr.ah_attr.grh.dgid.global.subnet_prefix = connInfo.gid.global.subnet_prefix;
      attr.ah_attr.grh.dgid.global.interface_id  = connInfo.gid.global.interface_id;
gilbertlee-amd's avatar
gilbertlee-amd committed
2713
      attr.ah_attr.grh.flow_label                = 0;
2714
      attr.ah_attr.grh.sgid_index                = connInfo.gidIdx;
gilbertlee-amd's avatar
gilbertlee-amd committed
2715
2716
2717
      attr.ah_attr.grh.hop_limit                 = 255;
    } else {
      attr.ah_attr.is_global = 0;
2718
      attr.ah_attr.dlid      = connInfo.lid;
gilbertlee-amd's avatar
gilbertlee-amd committed
2719
2720
2721
2722
    }
    attr.ah_attr.sl            = 0;
    attr.ah_attr.src_path_bits = 0;
    attr.ah_attr.port_num      = port;
2723
    attr.dest_qp_num           = connInfo.qpn;
gilbertlee-amd's avatar
gilbertlee-amd committed
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764

    // Modify the QP
    int ret = ibv_modify_qp(qp, &attr,
                            IBV_QP_STATE              |
                            IBV_QP_AV                 |
                            IBV_QP_PATH_MTU           |
                            IBV_QP_DEST_QPN           |
                            IBV_QP_RQ_PSN             |
                            IBV_QP_MAX_DEST_RD_ATOMIC |
                            IBV_QP_MIN_RNR_TIMER);
    if (ret != 0)
      return {ERR_FATAL, "Error during QP RTR. IB Verbs Error code: %d", ret};

    return ERR_NONE;
  }

  // Transition QueuePair to Ready to Send state
  static ErrResult TransitionQpToRts(struct ibv_qp *qp)
  {
    struct ibv_qp_attr attr = {};
    attr.qp_state           = IBV_QPS_RTS;
    attr.sq_psn             = 0;
    attr.timeout            = 14;
    attr.retry_cnt          = 7;
    attr.rnr_retry          = 7;
    attr.max_rd_atomic      = 1;

    int ret = ibv_modify_qp(qp, &attr,
                            IBV_QP_STATE     |
                            IBV_QP_TIMEOUT   |
                            IBV_QP_RETRY_CNT |
                            IBV_QP_RNR_RETRY |
                            IBV_QP_SQ_PSN    |
                            IBV_QP_MAX_QP_RD_ATOMIC);
    if (ret != 0)
      return {ERR_FATAL, "Error during QP RTS. IB Verbs Error code: %d", ret};

    return ERR_NONE;
  }

  static ErrResult PrepareNicTransferResources(ConfigOptions const& cfg,
2765
                                               ExeDevice     const& nicExeDevice,
gilbertlee-amd's avatar
gilbertlee-amd committed
2766
2767
2768
2769
                                               Transfer      const& t,
                                               TransferResources&   rss)

  {
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
    // The NIC executor is the one that initiates either a (remote read/local write) or (local read/remote write) copy operation
    // The NON executor is the NIC executor that facilitates the copy but issues no commands
    // TransferResources will be mostly prepared only on the ranks that are involved in this transfer, although all ranks pass
    // through this code
    int const srcMemRank = t.srcs[0].memRank;
    int const dstMemRank = t.dsts[0].memRank;
    int const nicExeRank = nicExeDevice.exeRank;
    int const nonExeRank = (nicExeRank == srcMemRank ? dstMemRank : srcMemRank);
    rss.srcIsExeNic = (srcMemRank == nicExeRank);

    // Figure out non Executor (Accounts for possible remap due to use of EXE_NIC_NEAREST)
    ExeDevice nonOrgDevice = {t.exeDevice.exeType, t.exeSubIndex, nonExeRank, t.exeSubSlot};
    ExeDevice nonExeDevice;
    ERR_CHECK(GetActualExecutor(nonOrgDevice, nonExeDevice));

    // All ranks track which NIC was used and number of queue pairs used
    rss.srcNicIndex = (nicExeRank == srcMemRank ? nicExeDevice.exeIndex : nonExeDevice.exeIndex);
    rss.dstNicIndex = (nicExeRank == srcMemRank ? nonExeDevice.exeIndex : nicExeDevice.exeIndex);
gilbertlee-amd's avatar
gilbertlee-amd committed
2788
2789
    rss.qpCount     = t.numSubExecs;

2790
    // Establish memory access flags
gilbertlee-amd's avatar
gilbertlee-amd committed
2791
2792
2793
2794
2795
2796
2797
2798
    unsigned int rdmaAccessFlags = (IBV_ACCESS_LOCAL_WRITE    |
                                    IBV_ACCESS_REMOTE_READ    |
                                    IBV_ACCESS_REMOTE_WRITE   |
                                    IBV_ACCESS_REMOTE_ATOMIC);

    unsigned int rdmaMemRegFlags = rdmaAccessFlags;
    if (cfg.nic.useRelaxedOrder) rdmaMemRegFlags |= IBV_ACCESS_RELAXED_ORDERING;

2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
    int const port = cfg.nic.ibPort;

    // Prepare NIC on SRC mem rank
    int srcGidIndex = cfg.nic.ibGidIndex;
    bool srcIsRoCE = false;
    if (GetRank() == srcMemRank) {
      // Switch to closest CPU NUMA domain
      int numaNode = GetIbvDeviceList()[rss.srcNicIndex].numaNode;
      if (numaNode != -1)
        numa_run_on_node(numaNode);
      // Open SRC NIC context
      IBV_PTR_CALL(rss.srcContext, ibv_open_device, GetIbvDeviceList()[rss.srcNicIndex].devicePtr);
      // Open SRC protection domain
      IBV_PTR_CALL(rss.srcProtect, ibv_alloc_pd, rss.srcContext);
      // Register SRC memory region
      IBV_PTR_CALL(rss.srcMemRegion, ibv_reg_mr, rss.srcProtect, rss.srcMem[0], rss.numBytes, rdmaMemRegFlags);
      // Create SRC completion queues
      IBV_PTR_CALL(rss.srcCompQueue, ibv_create_cq, rss.srcContext, cfg.nic.queueSize, NULL, NULL, 0);
      // Get SRC port attributes
      IBV_CALL(ibv_query_port, rss.srcContext, port, &rss.srcPortAttr);
      // Check for RDMA over Converged Ethernet (RoCE) and update GID index appropriately
      srcIsRoCE = (rss.srcPortAttr.link_layer == IBV_LINK_LAYER_ETHERNET);
      if (srcIsRoCE) {
        // Try to auto-detect the GID index
        std::pair<int, std::string> srcGidInfo (srcGidIndex, "");
        ERR_CHECK(GetGidIndex(rss.srcContext, rss.srcPortAttr.gid_tbl_len, port, srcGidInfo));
        srcGidIndex = srcGidInfo.first;
        IBV_CALL(ibv_query_gid, rss.srcContext, port, srcGidIndex, &rss.srcGid);
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
2828

2829
2830
2831
2832
2833
2834
2835
2836
2837
      // Prepare queue pairs and send elements
      rss.srcQueuePairs.resize(rss.qpCount);
      for (int i = 0; i < rss.qpCount; i++) {
       // Create SRC queue pair
        ERR_CHECK(CreateQueuePair(cfg, rss.srcProtect, rss.srcCompQueue, rss.srcQueuePairs[i]));
        // Initialize SRC queue pairs
        ERR_CHECK(InitQueuePair(rss.srcQueuePairs[i], port, rdmaAccessFlags));
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2838

2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
    // Prepare NIC on DST mem rank
    int dstGidIndex = cfg.nic.ibGidIndex;
    bool dstIsRoCE = false;
    if (GetRank() == dstMemRank) {
      // Switch to closest CPU NUMA domain
      int numaNode = GetIbvDeviceList()[rss.dstNicIndex].numaNode;
      if (numaNode != -1)
        numa_run_on_node(numaNode);
      // Open DST NIC contexts
      IBV_PTR_CALL(rss.dstContext, ibv_open_device, GetIbvDeviceList()[rss.dstNicIndex].devicePtr);
      // Open DST protection domain
      IBV_PTR_CALL(rss.dstProtect, ibv_alloc_pd, rss.dstContext);
      // Register DST memory region
      IBV_PTR_CALL(rss.dstMemRegion, ibv_reg_mr, rss.dstProtect, rss.dstMem[0], rss.numBytes, rdmaMemRegFlags);
      // Create DST completion queues
      IBV_PTR_CALL(rss.dstCompQueue, ibv_create_cq, rss.dstContext, cfg.nic.queueSize, NULL, NULL, 0);
      // Get DST port attributes
      IBV_CALL(ibv_query_port, rss.dstContext, port, &rss.dstPortAttr);
      // Check for RDMA over Converged Ethernet (RoCE) and update GID index appropriately
      dstIsRoCE = (rss.dstPortAttr.link_layer == IBV_LINK_LAYER_ETHERNET);
      if (dstIsRoCE) {
        // Try to auto-detect the GID index
        std::pair<int, std::string> dstGidInfo (dstGidIndex, "");
        ERR_CHECK(GetGidIndex(rss.dstContext, rss.dstPortAttr.gid_tbl_len, port, dstGidInfo));
        dstGidIndex = dstGidInfo.first;
        IBV_CALL(ibv_query_gid, rss.dstContext, port, dstGidIndex, &rss.dstGid);
      }
      // Prepare queue pairs
      rss.dstQueuePairs.resize(rss.qpCount);
      for (int i = 0; i < rss.qpCount; i++) {
        // Create DST queue pair
        ERR_CHECK(CreateQueuePair(cfg, rss.dstProtect, rss.dstCompQueue, rss.dstQueuePairs[i]));
        // Initialize SRC/DST queue pairs
        ERR_CHECK(InitQueuePair(rss.dstQueuePairs[i], port, rdmaAccessFlags));
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2875

2876
2877
2878
2879
2880
    // Executor rank prepares send elements and work requests
    if (GetRank() == nicExeRank) {
      rss.sgePerQueuePair.resize(rss.qpCount);
      rss.sendWorkRequests.resize(rss.qpCount);
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2881

2882
2883
2884
2885
2886
2887
2888
2889
    // Broadcast SRC/DST port link_layer so that all ranks know it so that they can be compared
    System::Get().Broadcast(srcMemRank, sizeof(rss.srcPortAttr.link_layer), &rss.srcPortAttr.link_layer);
    System::Get().Broadcast(dstMemRank, sizeof(rss.dstPortAttr.link_layer), &rss.dstPortAttr.link_layer);
    if (rss.srcPortAttr.link_layer != rss.dstPortAttr.link_layer) {
      printf("[ERROR] Link layer do not match (%d vs %d)\n", rss.srcPortAttr.link_layer, rss.dstPortAttr.link_layer);
      return {ERR_FATAL, "SRC NIC (%d) [Rank %d] and DST NIC (%d) [Rank %d] do not have the same link layer [%d vs %d]",
        rss.srcNicIndex, srcMemRank, rss.dstNicIndex, dstMemRank, rss.srcPortAttr.link_layer, rss.dstPortAttr.link_layer};
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2890

2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
    ConnInfo dstConnInfo = {};
    ConnInfo srcConnInfo = {};
    for (int i = 0; i < rss.qpCount; i++) {
      // Prepare and exchange SRC connection information
      if (GetRank() == srcMemRank) {
        srcConnInfo.lid    = rss.srcPortAttr.lid;
        srcConnInfo.gid    = rss.srcGid;
        srcConnInfo.gidIdx = srcGidIndex;
        srcConnInfo.qpn    = rss.srcQueuePairs[i]->qp_num;
        srcConnInfo.rkey   = rss.srcMemRegion->rkey;
        srcConnInfo.vaddr  = (uint64_t)rss.subExecParamCpu[i].src[0];
      }
      System::Get().Broadcast(srcMemRank, sizeof(srcConnInfo), &srcConnInfo);

      // Prepare and exchange DST connection information
      if (GetRank() == dstMemRank) {
        dstConnInfo.lid    = rss.dstPortAttr.lid;
        dstConnInfo.gid    = rss.dstGid;
        dstConnInfo.gidIdx = dstGidIndex;
        dstConnInfo.qpn    = rss.dstQueuePairs[i]->qp_num;
        dstConnInfo.rkey   = rss.dstMemRegion->rkey;
        dstConnInfo.vaddr  = (uint64_t)rss.subExecParamCpu[i].dst[0];
      }
      System::Get().Broadcast(dstMemRank, sizeof(dstConnInfo), &dstConnInfo);
gilbertlee-amd's avatar
gilbertlee-amd committed
2915

2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
      // Move queue pairs to ready-to-receive (RTR), using exchanged connection info
      // Then move them to read-to-send (RTS)
      if (GetRank() == srcMemRank) {
        ERR_CHECK(TransitionQpToRtr(rss.srcQueuePairs[i], dstConnInfo, port, srcIsRoCE, rss.srcPortAttr.active_mtu));
        ERR_CHECK(TransitionQpToRts(rss.srcQueuePairs[i]));
      }
      if (GetRank() == dstMemRank) {
        ERR_CHECK(TransitionQpToRtr(rss.dstQueuePairs[i], srcConnInfo, port, dstIsRoCE, rss.dstPortAttr.active_mtu));
        ERR_CHECK(TransitionQpToRts(rss.dstQueuePairs[i]));
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
2926

2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
      // Prepare scatter-gather element / work request for this queue pair in advance
      if (GetRank() == nicExeRank) {
        // Process the data to transfer in chunks (of cfg.nic.chunkBytes)
        size_t       remaining = rss.subExecParamCpu[i].N * sizeof(float);
        size_t const numChunks = (remaining + cfg.nic.chunkBytes - 1) / cfg.nic.chunkBytes;
        uint8_t*     local     = (nicExeRank == srcMemRank ? (uint8_t*)rss.subExecParamCpu[i].src[0]
                                                           : (uint8_t*)rss.subExecParamCpu[i].dst[0]);
        auto const   opcode    = (nicExeRank == srcMemRank ? IBV_WR_RDMA_WRITE             : IBV_WR_RDMA_READ);
        uint64_t     remote    = (nicExeRank == srcMemRank ? dstConnInfo.vaddr             : srcConnInfo.vaddr);
        auto const   lkey      = (nicExeRank == srcMemRank ? rss.srcMemRegion->lkey        : rss.dstMemRegion->lkey);
        auto const   rkey      = (nicExeRank == srcMemRank ? dstConnInfo.rkey              : srcConnInfo.rkey);
        if (System::Get().IsVerbose()) {
          printf("[INFO] Transfer %d SubExec %d executed by rank %d NIC %d is %s with %lu chunks\n",
                 rss.transferIdx, i, nicExeRank, nicExeDevice.exeIndex,
                 (opcode == IBV_WR_RDMA_WRITE ? "remote write" : "remote read"),
                 numChunks);
        }
        rss.sgePerQueuePair[i].resize(numChunks, {});
        rss.sendWorkRequests[i].resize(numChunks, {});

        for (size_t chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) {
          bool   isLastChunk    = (chunkIdx == numChunks - 1);
          size_t currChunkBytes = isLastChunk ? remaining : cfg.nic.chunkBytes;

          // Prepare scatter gather element
          ibv_sge& sg = rss.sgePerQueuePair[i][chunkIdx];
          sg.length = currChunkBytes;
          sg.addr   = (uintptr_t)local;
          sg.lkey   = lkey;

          // Prepare work request
          ibv_send_wr& wr = rss.sendWorkRequests[i][chunkIdx];
          wr.wr_id               = i;
          wr.sg_list             = &rss.sgePerQueuePair[i][chunkIdx];
          wr.num_sge             = 1;
          wr.send_flags          = isLastChunk ? IBV_SEND_SIGNALED : 0;  // Only last chunk is signalled
          wr.opcode              = opcode;
          wr.wr.rdma.remote_addr = remote;
          wr.wr.rdma.rkey        = rkey;

          if (System::Get().IsVerbose()) {
            printf("[INFO] Transfer %d SubExec %d chunk %lu local %p remote %p of size %lu\n",
                   rss.transferIdx, i, chunkIdx, (void*)local, (void*)remote, currChunkBytes);
          }
gilbertlee-amd's avatar
gilbertlee-amd committed
2971

2972
2973
2974
2975
2976
2977
          // Increment locations
          remaining -= currChunkBytes;
          local     += currChunkBytes;
          remote    += currChunkBytes;
        }
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
2978
2979
2980
2981
    }
    return ERR_NONE;
  }

2982
  static ErrResult TeardownNicTransferResources(TransferResources& rss, Transfer const& t)
gilbertlee-amd's avatar
gilbertlee-amd committed
2983
  {
2984
2985
2986
    bool isSrcRank = (GetRank() == t.srcs[0].memRank);
    bool isDstRank = (GetRank() == t.dsts[0].memRank);

gilbertlee-amd's avatar
gilbertlee-amd committed
2987
    // Deregister memory regions
2988
2989
    if (isSrcRank) IBV_CALL(ibv_dereg_mr, rss.srcMemRegion);
    if (isDstRank) IBV_CALL(ibv_dereg_mr, rss.dstMemRegion);
gilbertlee-amd's avatar
gilbertlee-amd committed
2990
2991

    // Destroy queue pairs
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
    if (isSrcRank) {
      for (auto srcQueuePair : rss.srcQueuePairs)
        IBV_CALL(ibv_destroy_qp, srcQueuePair);
      rss.srcQueuePairs.clear();
    }
    if (isDstRank) {
      for (auto dstQueuePair : rss.dstQueuePairs)
        IBV_CALL(ibv_destroy_qp, dstQueuePair);
      rss.dstQueuePairs.clear();
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
3002
3003

    // Destroy completion queues
3004
3005
    if (isSrcRank) IBV_CALL(ibv_destroy_cq, rss.srcCompQueue);
    if (isDstRank) IBV_CALL(ibv_destroy_cq, rss.dstCompQueue);
gilbertlee-amd's avatar
gilbertlee-amd committed
3006
3007

    // Deallocate protection domains
3008
3009
    if (isSrcRank) IBV_CALL(ibv_dealloc_pd, rss.srcProtect);
    if (isDstRank) IBV_CALL(ibv_dealloc_pd, rss.dstProtect);
gilbertlee-amd's avatar
gilbertlee-amd committed
3010
3011

    // Destroy context
3012
3013
    if (isSrcRank) IBV_CALL(ibv_close_device, rss.srcContext);
    if (isDstRank) IBV_CALL(ibv_close_device, rss.dstContext);
gilbertlee-amd's avatar
gilbertlee-amd committed
3014
3015
3016
3017
3018

    return ERR_NONE;
  }
#endif // NIC_EXEC_ENABLED

3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
// Data validation-related functions
//========================================================================================

  // Pseudo-random formula for each element in array
  static __host__ float PrepSrcValue(int srcBufferIdx, size_t idx)
  {
    return (((idx % 383) * 517) % 383 + 31) * (srcBufferIdx + 1);
  }

  // Fills a pre-sized buffer with the pattern, based on which src index buffer
  // Note: Can also generate expected dst buffer
  static void PrepareReference(ConfigOptions const& cfg, std::vector<float>& cpuBuffer, int bufferIdx)
  {
    size_t N = cpuBuffer.size();

gilbertlee-amd's avatar
gilbertlee-amd committed
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
    if (!cfg.data.fillCompress.empty()) {
      // 0 -> Random
      // 1 ->  1B0 - The upper  1 byte  of each aligned 2 bytes is 0
      // 2 ->  2B0 - The upper  2 bytes of each aligned 4 bytes are 0
      // 3 ->  4B0 - The upper  4 bytes of each aligned 8 bytes are 0
      // 4 -> 32B0 - The upper 32 bytes of each 64-byte line are 0

      // Fill buffer with random floats
      std::mt19937 gen;
      gen.seed(bufferIdx * 425);
      std::uniform_real_distribution<float> dist(-100000.0f, +100000.0f);
      for (size_t i = 0; i < N; i++) {
        cpuBuffer[i] = dist(gen);
      }

      // Figure out distribution for lines based on the percentages given
      size_t numLines = N / 16;
      size_t leftover = numLines;
      std::vector<size_t> lineCounts(5, 0);
      std::set<std::pair<double, int>> remainder;

      // Assign rounded down values first
      std::vector<int> percentages = cfg.data.fillCompress;
      while (percentages.size() < 5) percentages.push_back(0);
      for (int i = 0; i < percentages.size(); i++){
        lineCounts[i] = (size_t)(numLines * (percentages[i] / 100.0));
        leftover -= lineCounts[i];
        remainder.insert(std::make_pair(numLines * (percentages[i] / 100.0) - lineCounts[i], i));
      }

      // Assign leftovers based on largest remainder
      while (leftover != 0) {
        auto last = *remainder.rbegin();
        lineCounts[last.second]++;
        remainder.erase(last);
        leftover--;
      }

      // Randomly decide which lines get assigned to which types
      std::vector<int> lineTypes(numLines, 0);
      int offset = lineCounts[0];
      for (int i = 1; i < 5; i++) {
        for (int j = 0; j < lineCounts[i]; j++)
          lineTypes[offset++] = i;
      }
      std::shuffle(lineTypes.begin(), lineTypes.end(), gen);

      // Apply zero-ing
      int dumpLines = getenv("DUMP_LINES") ? atoi(getenv("DUMP_LINES")) : 0;

      if (dumpLines) {
        printf("Input pattern 64B line statistics for bufferIdx %d:\n", bufferIdx);
        printf("Total lines: %lu\n", numLines);
        printf("- 0: Random : %8lu (%8.3f%%)\n", lineCounts[0], 100.0 * lineCounts[0] / (1.0 * numLines));
        printf("- 1: 1B0    : %8lu (%8.3f%%)\n", lineCounts[1], 100.0 * lineCounts[1] / (1.0 * numLines));
        printf("- 2: 2B0    : %8lu (%8.3f%%)\n", lineCounts[2], 100.0 * lineCounts[2] / (1.0 * numLines));
        printf("- 3: 4B0    : %8lu (%8.3f%%)\n", lineCounts[3], 100.0 * lineCounts[3] / (1.0 * numLines));
        printf("- 4: 32B0   : %8lu (%8.3f%%)\n", lineCounts[4], 100.0 * lineCounts[4] / (1.0 * numLines));
      }

      for (int line = 0; line < numLines; line++) {
        unsigned char* linePtr = (unsigned char*)&cpuBuffer[line * 16];

        switch (lineTypes[line]) {
        case 1: // 1B0
          for (int i = 0; i < 32; i++)
            linePtr[2*i+1] = 0;
          break;
        case 2: // 2B0
          for (int i = 0; i < 16; i++) {
            linePtr[4*i+2] = 0;
            linePtr[4*i+3] = 0;
          }
          break;
        case 3: // 4B0
          for (int i = 0; i < 8; i++) {
            linePtr[8*i+4] = 0;
            linePtr[8*i+5] = 0;
            linePtr[8*i+6] = 0;
            linePtr[8*i+7] = 0;
          }
          break;
        case 4: // 32B0
          for (int i = 32; i < 64; i++)
            linePtr[i] = 0;
          break;
        }

        if (line < dumpLines) {
          printf("Line %02d [%d]: ", line, lineTypes[line]);
          for (int j = 63; j >= 0; j--){
            printf("%02x ", linePtr[j]);
            if (j % 16 == 0) printf(" ");
          }
          printf("\n");
        }
      }
    } else {
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
      // Use fill pattern if specified
      size_t patternLen = cfg.data.fillPattern.size();
      if (patternLen > 0) {
        size_t copies   = N / patternLen;
        size_t leftOver = N % patternLen;
        float* cpuBufferPtr = cpuBuffer.data();
        for (int i = 0; i < copies; i++) {
          memcpy(cpuBufferPtr, cfg.data.fillPattern.data(), patternLen * sizeof(float));
          cpuBufferPtr += patternLen;
        }
        if (leftOver)
          memcpy(cpuBufferPtr, cfg.data.fillPattern.data(), leftOver * sizeof(float));
      } else {
gilbertlee-amd's avatar
gilbertlee-amd committed
3145
        // Fall back to pseudo-random
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
        for (size_t i = 0; i < N; ++i)
          cpuBuffer[i] = PrepSrcValue(bufferIdx, i);
      }
    }
  }

  // Checks that destination buffers match expected values
  static ErrResult ValidateAllTransfers(ConfigOptions              const& cfg,
                                        vector<Transfer>           const& transfers,
                                        vector<TransferResources*> const& transferResources,
                                        vector<vector<float>>      const& dstReference,
                                        vector<float>&                    outputBuffer)
  {
    float* output;
    size_t initOffset = cfg.data.byteOffset / sizeof(float);

gilbertlee-amd's avatar
gilbertlee-amd committed
3162
3163
    for (auto rss : transferResources) {
      int transferIdx = rss->transferIdx;
3164
3165
3166
3167
      Transfer const& t = transfers[transferIdx];
      size_t N = t.numBytes / sizeof(float);

      float const* expected = dstReference[t.srcs.size()].data();
gilbertlee-amd's avatar
gilbertlee-amd committed
3168
      for (int dstIdx = 0; dstIdx < rss->dstMem.size(); dstIdx++) {
3169
3170
        // Validation is only done on the rank the destination memory is on
        if (t.dsts[dstIdx].memRank != GetRank()) continue;
3171
        if (IsCpuMemType(t.dsts[dstIdx].memType) || cfg.data.validateDirect) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3172
          output = (rss->dstMem[dstIdx]) + initOffset;
3173
        } else {
gilbertlee-amd's avatar
gilbertlee-amd committed
3174
          ERR_CHECK(hipMemcpy(outputBuffer.data(), (rss->dstMem[dstIdx]) + initOffset, t.numBytes, hipMemcpyDefault));
3175
3176
3177
3178
3179
3180
3181
3182
          ERR_CHECK(hipDeviceSynchronize());
          output = outputBuffer.data();
        }

        if (memcmp(output, expected, t.numBytes)) {
          // Difference found - find first error
          for (size_t i = 0; i < N; i++) {
            if (output[i] != expected[i]) {
3183
3184
              return {ERR_FATAL, "Transfer %d: Unexpected mismatch at index %lu of destination %d on rank %d: Expected %10.5f Actual: %10.5f",
                transferIdx, i, dstIdx, t.dsts[dstIdx].memRank, expected[i], output[i]};
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
            }
          }
          return {ERR_FATAL, "Transfer %d: Unexpected output mismatch for destination %d", transferIdx, dstIdx};
        }
      }
    }
    return ERR_NONE;
  }

// Preparation-related functions
//========================================================================================

  // Prepares input parameters for each subexecutor
  // Determines how sub-executors will split up the work
  // Initializes counters
  static ErrResult PrepareSubExecParams(ConfigOptions const& cfg,
                                        Transfer      const& transfer,
gilbertlee-amd's avatar
gilbertlee-amd committed
3202
                                        TransferResources&   rss)
3203
3204
3205
3206
3207
  {
    // Each subExecutor needs to know src/dst pointers and how many elements to transfer
    // Figure out the sub-array each subExecutor works on for this Transfer
    // - Partition N as evenly as possible, but try to keep subarray sizes as multiples of data.blockBytes
    //   except the very last one, for alignment reasons
3208
    size_t const N              = transfer.numBytes   / sizeof(float);
3209
3210
3211
    int    const initOffset     = cfg.data.byteOffset / sizeof(float);
    int    const targetMultiple = cfg.data.blockBytes / sizeof(float);

3212
    // In some cases, there may not be enough data for all subExecutors
3213
3214
3215
    int const maxSubExecToUse = std::min((size_t)(N + targetMultiple - 1) / targetMultiple,
                                         (size_t)transfer.numSubExecs);

gilbertlee-amd's avatar
gilbertlee-amd committed
3216
    vector<SubExecParam>& subExecParam = rss.subExecParamCpu;
3217
3218
3219
3220
3221
3222
    subExecParam.clear();
    subExecParam.resize(transfer.numSubExecs);

    size_t assigned = 0;
    for (int i = 0; i < transfer.numSubExecs; ++i) {
      SubExecParam& p  = subExecParam[i];
gilbertlee-amd's avatar
gilbertlee-amd committed
3223
3224
      p.numSrcs        = rss.srcMem.size();
      p.numDsts        = rss.dstMem.size();
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
      p.startCycle     = 0;
      p.stopCycle      = 0;
      p.hwId           = 0;
      p.xccId          = 0;

      // In single team mode, subexecutors stripe across the entire array
      if (cfg.gfx.useSingleTeam && transfer.exeDevice.exeType == EXE_GPU_GFX) {
        p.N        = N;
        p.teamSize = transfer.numSubExecs;
        p.teamIdx  = i;
gilbertlee-amd's avatar
gilbertlee-amd committed
3235
3236
        for (int iSrc = 0; iSrc < p.numSrcs; ++iSrc) p.src[iSrc] = rss.srcMem[iSrc] + initOffset;
        for (int iDst = 0; iDst < p.numDsts; ++iDst) p.dst[iDst] = rss.dstMem[iDst] + initOffset;
3237
3238
3239
3240
3241
3242
3243
3244
3245
      } else {
        // Otherwise, each subexecutor works on separate subarrays
        int    const subExecLeft = std::max(0, maxSubExecToUse - i);
        size_t const leftover    = N - assigned;
        size_t const roundedN    = (leftover + targetMultiple - 1) / targetMultiple;

        p.N        = subExecLeft ? std::min(leftover, ((roundedN / subExecLeft) * targetMultiple)) : 0;
        p.teamSize = 1;
        p.teamIdx  = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
3246
3247
        for (int iSrc = 0; iSrc < p.numSrcs; ++iSrc) p.src[iSrc] = rss.srcMem[iSrc] + initOffset + assigned;
        for (int iDst = 0; iDst < p.numDsts; ++iDst) p.dst[iDst] = rss.dstMem[iDst] + initOffset + assigned;
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
        assigned += p.N;
      }

      p.preferredXccId = transfer.exeSubIndex;
      // Override if XCC table has been specified
      vector<vector<int>> const& table = cfg.gfx.prefXccTable;
      if (transfer.exeDevice.exeType == EXE_GPU_GFX && transfer.exeSubIndex == -1 && !table.empty() &&
          transfer.dsts.size() == 1 && IsGpuMemType(transfer.dsts[0].memType)) {
        if (table.size() <= transfer.exeDevice.exeIndex ||
            table[transfer.exeDevice.exeIndex].size() <= transfer.dsts[0].memIndex) {
          return {ERR_FATAL, "[gfx.xccPrefTable] is too small"};
        }
        p.preferredXccId = table[transfer.exeDevice.exeIndex][transfer.dsts[0].memIndex];
        if (p.preferredXccId < 0 || p.preferredXccId >= GetNumExecutorSubIndices(transfer.exeDevice)) {
          return {ERR_FATAL, "[gfx.xccPrefTable] defines out-of-bound XCC index %d", p.preferredXccId};
        }
      }
    }

    // Clear counters
gilbertlee-amd's avatar
gilbertlee-amd committed
3268
    rss.totalDurationMsec = 0.0;
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280

    return ERR_NONE;
  }

  // Prepare each executor
  // Allocates memory for src/dst, prepares subexecutors, executor-specific data structures
  static ErrResult PrepareExecutor(ConfigOptions    const& cfg,
                                   vector<Transfer> const& transfers,
                                   ExeDevice        const& exeDevice,
                                   ExeInfo&                exeInfo)
  {
    exeInfo.totalDurationMsec = 0.0;
3281
3282
3283
3284
3285
    int const localRank = GetRank();
    if (System::Get().IsVerbose()) {
      printf("[INFO] Rank %d preparing executor (%c%d on Rank %d)\n",
             localRank, ExeTypeStr[exeDevice.exeType], exeDevice.exeIndex, exeDevice.exeRank);
    }
3286
3287

    // Loop over each transfer this executor is involved in
gilbertlee-amd's avatar
gilbertlee-amd committed
3288
3289
3290
    for (auto& rss : exeInfo.resources) {
      Transfer const& t = transfers[rss.transferIdx];
      rss.numBytes = t.numBytes;
3291

3292
3293
3294
3295
3296
      if (System::Get().IsVerbose()) {
        printf("[INFO] Rank %d preparing transfer %d (%lu SRC %lu DST)\n",
               localRank, rss.transferIdx, t.srcs.size(), t.dsts.size());
      }

3297
      // Allocate source memory
gilbertlee-amd's avatar
gilbertlee-amd committed
3298
      rss.srcMem.resize(t.srcs.size());
3299
3300
3301
3302
      for (int iSrc = 0; iSrc < t.srcs.size(); ++iSrc) {
        MemDevice const& srcMemDevice = t.srcs[iSrc];

        // Ensure executing GPU can access source memory
3303
3304
3305
3306
3307
        // This only applies to memory being accessed by a local GPU executor
        if (IsGpuExeType(exeDevice.exeType)    &&
            IsGpuMemType(srcMemDevice.memType) &&
            srcMemDevice.memRank == localRank  &&
            exeDevice.exeRank    == localRank  &&
3308
3309
3310
            srcMemDevice.memIndex != exeDevice.exeIndex) {
          ERR_CHECK(EnablePeerAccess(exeDevice.exeIndex, srcMemDevice.memIndex));
        }
3311
3312
3313
3314
3315
3316
3317
3318

        // Allocate source memory (on the correct rank)
        if (srcMemDevice.memRank == localRank) {
          ERR_CHECK(AllocateMemory(srcMemDevice, t.numBytes + cfg.data.byteOffset, (void**)&rss.srcMem[iSrc]));
        }

        // Pass this pointer to all ranks (Used for pointer arithmetic, not defererenced on non-local ranks)
        System::Get().Broadcast(srcMemDevice.memRank, sizeof(rss.srcMem[iSrc]), &rss.srcMem[iSrc]);
3319
3320
3321
      }

      // Allocate destination memory
gilbertlee-amd's avatar
gilbertlee-amd committed
3322
      rss.dstMem.resize(t.dsts.size());
3323
3324
3325
3326
      for (int iDst = 0; iDst < t.dsts.size(); ++iDst) {
        MemDevice const& dstMemDevice = t.dsts[iDst];

        // Ensure executing GPU can access destination memory
3327
3328
3329
3330
        if (IsGpuExeType(exeDevice.exeType)    &&
            IsGpuMemType(dstMemDevice.memType) &&
            dstMemDevice.memRank == localRank  &&
            exeDevice.exeRank    == localRank  &&
3331
3332
3333
            dstMemDevice.memIndex != exeDevice.exeIndex) {
          ERR_CHECK(EnablePeerAccess(exeDevice.exeIndex, dstMemDevice.memIndex));
        }
3334
3335
3336
3337
3338
3339
3340

        // Allocate destination memory (on the correct rank)
        if (dstMemDevice.memRank == localRank) {
          ERR_CHECK(AllocateMemory(dstMemDevice, t.numBytes + cfg.data.byteOffset, (void**)&rss.dstMem[iDst]));
        }
        // Pass this pointer to all ranks (Used for pointer arithmetic, not defererenced on non-local ranks)
        System::Get().Broadcast(dstMemDevice.memRank, sizeof(rss.dstMem[iDst]), &rss.dstMem[iDst]);
3341
3342
      }

3343
3344
      // Prepare HSA DMA copy specific resources
      if (exeDevice.exeType == EXE_GPU_DMA && (t.exeSubIndex != -1 || cfg.dma.useHsaCopy) && exeDevice.exeRank == localRank) {
3345
3346
3347
3348
#if !defined(__NVCC__)
        // Collect HSA agent information
        hsa_amd_pointer_info_t info;
        info.size = sizeof(info);
gilbertlee-amd's avatar
gilbertlee-amd committed
3349
3350
        ERR_CHECK(hsa_amd_pointer_info(rss.dstMem[0], &info, NULL, NULL, NULL));
        rss.dstAgent = info.agentOwner;
3351

gilbertlee-amd's avatar
gilbertlee-amd committed
3352
3353
        ERR_CHECK(hsa_amd_pointer_info(rss.srcMem[0], &info, NULL, NULL, NULL));
        rss.srcAgent = info.agentOwner;
3354
3355

        // Create HSA completion signal
gilbertlee-amd's avatar
gilbertlee-amd committed
3356
        ERR_CHECK(hsa_signal_create(1, 0, NULL, &rss.signal));
3357
3358

        if (t.exeSubIndex != -1)
gilbertlee-amd's avatar
gilbertlee-amd committed
3359
          rss.sdmaEngineId = (hsa_amd_sdma_engine_id_t)(1U << t.exeSubIndex);
3360
3361
3362
#endif
      }

3363
      // Prepare subexecutor parameters (on all ranks)
gilbertlee-amd's avatar
gilbertlee-amd committed
3364
      ERR_CHECK(PrepareSubExecParams(cfg, t, rss));
3365
3366
3367
    }

    // Prepare additional requirements for GPU-based executors
3368
    if ((exeDevice.exeType == EXE_GPU_GFX || exeDevice.exeType == EXE_GPU_DMA) && exeDevice.exeRank == localRank) {
3369
3370
3371
3372
      ERR_CHECK(hipSetDevice(exeDevice.exeIndex));

      // Determine how many streams to use
      int const numStreamsToUse = (exeDevice.exeType == EXE_GPU_DMA ||
3373
3374
                                  (exeDevice.exeType == EXE_GPU_GFX && cfg.gfx.useMultiStream))
                                  ? exeInfo.resources.size() : 1;
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
      exeInfo.streams.resize(numStreamsToUse);

      // Create streams
      for (int i = 0; i < numStreamsToUse; ++i) {
        if (cfg.gfx.cuMask.size()) {
#if !defined(__NVCC__)
          ERR_CHECK(hipExtStreamCreateWithCUMask(&exeInfo.streams[i], cfg.gfx.cuMask.size(),
                                                 cfg.gfx.cuMask.data()));
#else
          return {ERR_FATAL, "CU Masking in not supported on NVIDIA hardware"};
#endif
        } else {
          ERR_CHECK(hipStreamCreate(&exeInfo.streams[i]));
        }
      }

      if (cfg.gfx.useHipEvents || cfg.dma.useHipEvents) {
        exeInfo.startEvents.resize(numStreamsToUse);
        exeInfo.stopEvents.resize(numStreamsToUse);
        for (int i = 0; i < numStreamsToUse; ++i) {
          ERR_CHECK(hipEventCreate(&exeInfo.startEvents[i]));
          ERR_CHECK(hipEventCreate(&exeInfo.stopEvents[i]));
        }
      }
    }

    // Prepare for GPU GFX executor
3402
    if (exeDevice.exeType == EXE_GPU_GFX && exeDevice.exeRank == localRank) {
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
      // Allocate one contiguous chunk of GPU memory for threadblock parameters
      // This allows support for executing one transfer per stream, or all transfers in a single stream
#if !defined(__NVCC__)
      MemType memType = MEM_GPU;      // AMD hardware can directly access GPU memory from host
#else
      MemType memType = MEM_MANAGED;  // NVIDIA hardware requires managed memory to access from host
#endif
      ERR_CHECK(AllocateMemory({memType, exeDevice.exeIndex}, exeInfo.totalSubExecs * sizeof(SubExecParam),
                               (void**)&exeInfo.subExecParamGpu));

      // Create subexecutor parameter array for entire executor
      exeInfo.subExecParamCpu.clear();
      exeInfo.numSubIndices = GetNumExecutorSubIndices(exeDevice);
#if defined(__NVCC__)
      exeInfo.wallClockRate = 1000000;
#else
      ERR_CHECK(hipDeviceGetAttribute(&exeInfo.wallClockRate, hipDeviceAttributeWallClockRate,
                                      exeDevice.exeIndex));
#endif
      int transferOffset = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
      if (cfg.gfx.useMultiStream || cfg.gfx.blockOrder == 0) {
        // Threadblocks are ordered sequentially one transfer at a time
        for (auto& rss : exeInfo.resources) {
          rss.subExecParamGpuPtr = exeInfo.subExecParamGpu + transferOffset;
          for (auto p : rss.subExecParamCpu) {
            rss.subExecIdx.push_back(exeInfo.subExecParamCpu.size());
            exeInfo.subExecParamCpu.push_back(p);
            transferOffset++;
          }
        }
      } else if (cfg.gfx.blockOrder == 1) {
        // Interleave threadblocks of different Transfers
        for (int subExecIdx = 0; exeInfo.subExecParamCpu.size() < exeInfo.totalSubExecs; ++subExecIdx) {
          for (auto& rss : exeInfo.resources) {
            Transfer const& t = transfers[rss.transferIdx];
            if (subExecIdx < t.numSubExecs) {
              rss.subExecIdx.push_back(exeInfo.subExecParamCpu.size());
              exeInfo.subExecParamCpu.push_back(rss.subExecParamCpu[subExecIdx]);
            }
          }
        }
      } else if (cfg.gfx.blockOrder == 2) {
        // Build randomized threadblock list
        std::vector<std::pair<int,int>> indices;
        for (int i = 0; i < exeInfo.resources.size(); i++) {
          auto const& rss = exeInfo.resources[i];
          Transfer const& t = transfers[rss.transferIdx];
          for (int j = 0; j < t.numSubExecs; j++)
            indices.push_back(std::make_pair(i,j));
        }

        std::random_device rd;
gilbertlee-amd's avatar
gilbertlee-amd committed
3455
        std::mt19937 gen(rd());
gilbertlee-amd's avatar
gilbertlee-amd committed
3456
3457
3458
3459
3460
        std::shuffle(indices.begin(), indices.end(), gen);

        // Build randomized threadblock list
        for (auto p : indices) {
          auto& rss = exeInfo.resources[p.first];
gilbertlee-amd's avatar
gilbertlee-amd committed
3461
          rss.subExecIdx.push_back(exeInfo.subExecParamCpu.size());
gilbertlee-amd's avatar
gilbertlee-amd committed
3462
          exeInfo.subExecParamCpu.push_back(rss.subExecParamCpu[p.second]);
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
        }
      }

      // Copy sub executor parameters to GPU
      ERR_CHECK(hipSetDevice(exeDevice.exeIndex));
      ERR_CHECK(hipMemcpy(exeInfo.subExecParamGpu,
                          exeInfo.subExecParamCpu.data(),
                          exeInfo.totalSubExecs * sizeof(SubExecParam),
                          hipMemcpyHostToDevice));
      ERR_CHECK(hipDeviceSynchronize());
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
    // Prepare for NIC-based executors
    if (IsNicExeType(exeDevice.exeType)) {
#ifdef NIC_EXEC_ENABLED
      for (auto& rss : exeInfo.resources) {
        Transfer const& t = transfers[rss.transferIdx];
        ERR_CHECK(PrepareNicTransferResources(cfg, exeDevice, t, rss));
      }
#else
      return {ERR_FATAL, "RDMA executor is not supported"};
#endif
    }
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
    return ERR_NONE;
  }

// Teardown-related functions
//========================================================================================

  // Clean up all resources
  static ErrResult TeardownExecutor(ConfigOptions    const& cfg,
                                    ExeDevice        const& exeDevice,
                                    vector<Transfer> const& transfers,
                                    ExeInfo&                exeInfo)
  {
3498
3499
    int const localRank = GetRank();

3500
    // Loop over each transfer this executor is involved in
gilbertlee-amd's avatar
gilbertlee-amd committed
3501
3502
    for (auto& rss : exeInfo.resources) {
      Transfer const& t = transfers[rss.transferIdx];
3503
3504
3505

      // Deallocate source memory
      for (int iSrc = 0; iSrc < t.srcs.size(); ++iSrc) {
3506
3507
3508
        if (t.srcs[iSrc].memRank == localRank) {
          ERR_CHECK(DeallocateMemory(t.srcs[iSrc].memType, rss.srcMem[iSrc], t.numBytes + cfg.data.byteOffset));
        }
3509
3510
3511
3512
      }

      // Deallocate destination memory
      for (int iDst = 0; iDst < t.dsts.size(); ++iDst) {
3513
3514
3515
        if (t.dsts[iDst].memRank == localRank) {
          ERR_CHECK(DeallocateMemory(t.dsts[iDst].memType, rss.dstMem[iDst], t.numBytes + cfg.data.byteOffset));
        }
3516
3517
3518
3519
      }

      // Destroy HSA signal for DMA executor
#if !defined(__NVCC__)
3520
      if (exeDevice.exeType == EXE_GPU_DMA && (t.exeSubIndex != -1 || cfg.dma.useHsaCopy) && exeDevice.exeRank == localRank) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3521
3522
3523
3524
3525
3526
3527
        ERR_CHECK(hsa_signal_destroy(rss.signal));
      }
#endif

      // Destroy NIC related resources
#ifdef NIC_EXEC_ENABLED
      if (IsNicExeType(exeDevice.exeType)) {
3528
        ERR_CHECK(TeardownNicTransferResources(rss, t));
3529
3530
3531
3532
3533
      }
#endif
    }

    // Teardown additional requirements for GPU-based executors
3534
    if ((exeDevice.exeType == EXE_GPU_GFX || exeDevice.exeType == EXE_GPU_DMA) && exeDevice.exeRank == localRank) {
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
      for (auto stream : exeInfo.streams)
        ERR_CHECK(hipStreamDestroy(stream));
      if (cfg.gfx.useHipEvents || cfg.dma.useHipEvents) {
        for (auto event : exeInfo.startEvents)
          ERR_CHECK(hipEventDestroy(event));
        for (auto event : exeInfo.stopEvents)
          ERR_CHECK(hipEventDestroy(event));
      }
    }

3545
    if (exeDevice.exeType == EXE_GPU_GFX && exeDevice.exeRank == localRank) {
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
#if !defined(__NVCC__)
      MemType memType = MEM_GPU;
#else
      MemType memType = MEM_MANAGED;
#endif
      ERR_CHECK(DeallocateMemory(memType, exeInfo.subExecParamGpu, exeInfo.totalSubExecs * sizeof(SubExecParam)));
    }

    return ERR_NONE;
  }

// CPU Executor-related functions
//========================================================================================

  // Kernel for CPU execution (run by a single subexecutor)
gilbertlee-amd's avatar
gilbertlee-amd committed
3561
  static void CpuReduceKernel(SubExecParam const& p, int numSubIterations)
3562
3563
3564
  {
    if (p.N == 0) return;

gilbertlee-amd's avatar
gilbertlee-amd committed
3565
3566
3567
3568
    int subIteration = 0;
    do {
      int const& numSrcs = p.numSrcs;
      int const& numDsts = p.numDsts;
3569

gilbertlee-amd's avatar
gilbertlee-amd committed
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
      if (numSrcs == 0) {
        for (int i = 0; i < numDsts; ++i) {
          memset(p.dst[i], MEMSET_CHAR, p.N * sizeof(float));
          //for (int j = 0; j < p.N; j++) p.dst[i][j] = MEMSET_VAL;
        }
      } else if (numSrcs == 1) {
        float const* __restrict__ src = p.src[0];
        if (numDsts == 0) {
          float sum = 0.0;
          for (int j = 0; j < p.N; j++)
            sum += p.src[0][j];

          // Add a dummy check to ensure the read is not optimized out
          if (sum != sum) {
            printf("[ERROR] Nan detected\n");
          }
        } else {
          for (int i = 0; i < numDsts; ++i)
            memcpy(p.dst[i], src, p.N * sizeof(float));
3589
3590
        }
      } else {
gilbertlee-amd's avatar
gilbertlee-amd committed
3591
3592
3593
3594
3595
3596
        float sum = 0.0f;
        for (int j = 0; j < p.N; j++) {
          sum = p.src[0][j];
          for (int i = 1; i < numSrcs; i++) sum += p.src[i][j];
          for (int i = 0; i < numDsts; i++) p.dst[i][j] = sum;
        }
3597
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
3598
    } while (++subIteration != numSubIterations);
3599
3600
3601
3602
3603
3604
  }

  // Execution of a single CPU Transfers
  static void ExecuteCpuTransfer(int           const  iteration,
                                 ConfigOptions const& cfg,
                                 int           const  exeIndex,
gilbertlee-amd's avatar
gilbertlee-amd committed
3605
                                 TransferResources&   rss)
3606
3607
3608
3609
  {
    auto cpuStart = std::chrono::high_resolution_clock::now();
    vector<std::thread> childThreads;

gilbertlee-amd's avatar
gilbertlee-amd committed
3610
3611
3612
3613
3614
3615
    for (auto const& subExecParam : rss.subExecParamCpu)
      childThreads.emplace_back(std::thread(CpuReduceKernel, std::cref(subExecParam), cfg.general.numSubIterations));

    for (auto& subExecThread : childThreads)
      subExecThread.join();
    childThreads.clear();
3616
3617

    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
3618
    double deltaMsec = (std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0) / cfg.general.numSubIterations;
3619
3620

    if (iteration >= 0) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3621
      rss.totalDurationMsec += deltaMsec;
3622
      if (cfg.general.recordPerIteration)
gilbertlee-amd's avatar
gilbertlee-amd committed
3623
        rss.perIterMsec.push_back(deltaMsec);
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
    }
  }

  // Execution of a single CPU executor
  static ErrResult RunCpuExecutor(int           const  iteration,
                                  ConfigOptions const& cfg,
                                  int           const  exeIndex,
                                  ExeInfo&             exeInfo)
  {
    numa_run_on_node(exeIndex);
    auto cpuStart = std::chrono::high_resolution_clock::now();

    vector<std::thread> asyncTransfers;
gilbertlee-amd's avatar
gilbertlee-amd committed
3637
    for (auto& rss : exeInfo.resources) {
3638
3639
3640
3641
      asyncTransfers.emplace_back(std::thread(ExecuteCpuTransfer,
                                              iteration,
                                              std::cref(cfg),
                                              exeIndex,
gilbertlee-amd's avatar
gilbertlee-amd committed
3642
                                              std::ref(rss)));
3643
3644
3645
3646
3647
    }
    for (auto& asyncTransfer : asyncTransfers)
      asyncTransfer.join();

    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
3648
3649
    double deltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0 / cfg.general.numSubIterations;

3650
3651
3652
3653
3654
    if (iteration >= 0)
      exeInfo.totalDurationMsec += deltaMsec;
    return ERR_NONE;
  }

gilbertlee-amd's avatar
gilbertlee-amd committed
3655
3656
3657
3658
3659
3660
3661
#ifdef NIC_EXEC_ENABLED
  // Execution of a single NIC Transfer
  static ErrResult ExecuteNicTransfer(int           const  iteration,
                                      ConfigOptions const& cfg,
                                      int           const  exeIndex,
                                      TransferResources&   rss)
  {
3662
    // Loop over each of the queue pairs and post work request
gilbertlee-amd's avatar
gilbertlee-amd committed
3663
3664
    ibv_send_wr* badWorkReq;
    for (int qpIndex = 0; qpIndex < rss.qpCount; qpIndex++) {
3665
3666
3667
3668
3669
3670
3671
3672
      size_t numChunks = rss.sendWorkRequests[qpIndex].size();
      for (size_t chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) {
        int error = ibv_post_send(rss.srcIsExeNic ? rss.srcQueuePairs[qpIndex] : rss.dstQueuePairs[qpIndex],
                                  &rss.sendWorkRequests[qpIndex][chunkIdx], &badWorkReq);
        if (error)
          return {ERR_FATAL, "Transfer %d: Error when calling ibv_post_send for QP %d chunk %lu of %lu (Error code %d = %s)\n",
            rss.transferIdx, qpIndex, chunkIdx, numChunks, error, strerror(error)};
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
    }
    return ERR_NONE;
  }

  // Execution of a single NIC executor
  static ErrResult RunNicExecutor(int           const  iteration,
                                  ConfigOptions const& cfg,
                                  int           const  exeIndex,
                                  ExeInfo&             exeInfo)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
3683
3684
3685
3686
3687
    // Switch to the closest NUMA node to this NIC
    if (cfg.nic.useNuma) {
      int numaNode = GetIbvDeviceList()[exeIndex].numaNode;
      if (numaNode != -1)
        numa_run_on_node(numaNode);
gilbertlee-amd's avatar
gilbertlee-amd committed
3688
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
3689
3690
3691
3692

    auto transferCount = exeInfo.resources.size();
    std::vector<double> totalTimeMsec(transferCount, 0.0);

gilbertlee-amd's avatar
gilbertlee-amd committed
3693
    int subIterations = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
3694
3695
3696
    auto cpuStart = std::chrono::high_resolution_clock::now();
    std::vector<std::chrono::high_resolution_clock::time_point> transferTimers(transferCount);

gilbertlee-amd's avatar
gilbertlee-amd committed
3697
    do {
gilbertlee-amd's avatar
gilbertlee-amd committed
3698
      std::vector<uint8_t> receivedQPs(transferCount, 0);
gilbertlee-amd's avatar
gilbertlee-amd committed
3699
3700
3701
3702
3703
3704
      // post the sends
      for (auto i = 0; i < transferCount; i++) {
        transferTimers[i] = std::chrono::high_resolution_clock::now();
        ERR_CHECK(ExecuteNicTransfer(iteration, cfg, exeIndex, exeInfo.resources[i]));
      }
      // poll for completions
gilbertlee-amd's avatar
gilbertlee-amd committed
3705
3706
      size_t completedTransfers = 0;
      while (completedTransfers < transferCount) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3707
3708
3709
3710
3711
3712
        for (auto i = 0; i < transferCount; i++) {
          if(receivedQPs[i] < exeInfo.resources[i].qpCount) {
            auto& rss = exeInfo.resources[i];
            // Poll the completion queue until all queue pairs are complete
            // The order of completion doesn't matter because this completion queue is dedicated to this Transfer
            ibv_wc wc;
3713
            int nc = ibv_poll_cq(rss.srcIsExeNic ? rss.srcCompQueue : rss.dstCompQueue, 1, &wc);
gilbertlee-amd's avatar
gilbertlee-amd committed
3714
3715
3716
            if (nc > 0) {
              receivedQPs[i]++;
              if (wc.status != IBV_WC_SUCCESS) {
3717
                return {ERR_FATAL, "Transfer %d: Received unsuccessful work completion [status code %d]", rss.transferIdx, wc.status};
gilbertlee-amd's avatar
gilbertlee-amd committed
3718
3719
3720
3721
3722
3723
3724
3725
              }
            } else if (nc < 0) {
              return {ERR_FATAL, "Transfer %d: Received negative work completion", rss.transferIdx};
            }
            if(receivedQPs[i] == rss.qpCount) {
              auto cpuDelta = std::chrono::high_resolution_clock::now() - transferTimers[i];
              double deltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0;
              if (iteration >= 0) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3726
                totalTimeMsec[i] += deltaMsec;
gilbertlee-amd's avatar
gilbertlee-amd committed
3727
3728
3729
3730
3731
              }
              completedTransfers++;
            }
          }
        }
gilbertlee-amd's avatar
gilbertlee-amd committed
3732
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
3733
    } while(++subIterations < cfg.general.numSubIterations);
gilbertlee-amd's avatar
gilbertlee-amd committed
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747

    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
    double deltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0 / cfg.general.numSubIterations;

    if (iteration >= 0) {
      exeInfo.totalDurationMsec += deltaMsec;
      for (int i = 0; i < transferCount; i++) {
        auto& rss = exeInfo.resources[i];
        double transferTimeMsec = totalTimeMsec[i] / cfg.general.numSubIterations;
        rss.totalDurationMsec += transferTimeMsec;
        if (cfg.general.recordPerIteration)
          rss.perIterMsec.push_back(transferTimeMsec);
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
3748
3749
3750
    return ERR_NONE;
  }
#endif
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
// GFX Executor-related functions
//========================================================================================

  // Converts register value to a CU/SM index
  static uint32_t GetId(uint32_t hwId)
  {
#if defined(__NVCC_)
    return hwId;
#else
    // Based on instinct-mi200-cdna2-instruction-set-architecture.pdf
    int const shId = (hwId >> 12) &  1;
    int const cuId = (hwId >>  8) & 15;
    int const seId = (hwId >> 13) &  3;
    return (shId << 5) + (cuId << 2) + seId;
#endif
  }

  // Device level timestamp function
  __device__ int64_t GetTimestamp()
  {
#if defined(__NVCC__)
    int64_t result;
    asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(result));
    return result;
#else
    return wall_clock64();
#endif
  }

  // Helper function for memset
  template <typename T> __device__ __forceinline__ T      MemsetVal();
  template <>           __device__ __forceinline__ float  MemsetVal(){ return MEMSET_VAL; };
gilbertlee-amd's avatar
gilbertlee-amd committed
3783
3784
  template <>           __device__ __forceinline__ float2 MemsetVal(){ return make_float2(MEMSET_VAL,
                                                                                          MEMSET_VAL); };
3785
3786
3787
3788
3789
  template <>           __device__ __forceinline__ float4 MemsetVal(){ return make_float4(MEMSET_VAL,
                                                                                          MEMSET_VAL,
                                                                                          MEMSET_VAL,
                                                                                          MEMSET_VAL); }

gilbertlee-amd's avatar
gilbertlee-amd committed
3790

gilbertlee-amd's avatar
gilbertlee-amd committed
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
  // Helper function for temporal/non-temporal reads / writes
  #define TEMPORAL_NONE  0
  #define TEMPORAL_LOAD  1
  #define TEMPORAL_STORE 2
  #define TEMPORAL_BOTH  3

  template <int TEMPORAL_MODE>
  __device__ __forceinline__ void Load(float const* src, float& dst) {
    if (TEMPORAL_MODE & TEMPORAL_LOAD) {
#if !defined(__NVCC__)
      dst = __builtin_nontemporal_load(src);

#endif
    } else {
      dst = *src;
    }
  }

  template <int TEMPORAL_MODE>
  __device__ __forceinline__ void Load(float2 const* src, float2& dst) {
    if (TEMPORAL_MODE & TEMPORAL_LOAD) {
#if !defined(__NVCC__)
      dst.x = __builtin_nontemporal_load(&(src->x));
      dst.y = __builtin_nontemporal_load(&(src->y));
#endif
    } else {
      dst = *src;
    }
  }

  template <int TEMPORAL_MODE>
  __device__ __forceinline__ void Load(float4 const* src, float4& dst) {
    if (TEMPORAL_MODE & TEMPORAL_LOAD) {
#if !defined(__NVCC__)
      dst.x = __builtin_nontemporal_load(&(src->x));
      dst.y = __builtin_nontemporal_load(&(src->y));
      dst.z = __builtin_nontemporal_load(&(src->z));
      dst.w = __builtin_nontemporal_load(&(src->w));
#endif
    } else {
      dst = *src;
    }
  }

  template <int TEMPORAL_MODE>
  __device__ __forceinline__ void Store(float const& src, float* dst) {
    if (TEMPORAL_MODE & TEMPORAL_STORE) {
#if !defined(__NVCC__)
      __builtin_nontemporal_store(src, dst);
#endif
    } else {
      *dst = src;
    }
  }

  template <int TEMPORAL_MODE>
  __device__ __forceinline__ void Store(float2 const& src, float2* dst) {
    if (TEMPORAL_MODE & TEMPORAL_STORE) {
#if !defined(__NVCC__)
      __builtin_nontemporal_store(src.x, &(dst->x));
      __builtin_nontemporal_store(src.y, &(dst->y));
#endif
    } else {
      *dst = src;
    }
  }

  template <int TEMPORAL_MODE>
  __device__ __forceinline__ void Store(float4 const& src, float4* dst) {
    if (TEMPORAL_MODE & TEMPORAL_STORE) {
#if !defined(__NVCC__)
      __builtin_nontemporal_store(src.x, &(dst->x));
      __builtin_nontemporal_store(src.y, &(dst->y));
      __builtin_nontemporal_store(src.z, &(dst->z));
      __builtin_nontemporal_store(src.w, &(dst->w));
#endif
    } else {
      *dst = src;
    }
  }

  // Kernel for GFX execution
3873
3874
  template <typename PACKED_FLOAT, int LAUNCH_BOUND, int UNROLL, int TEMPORAL_MODE>
  __global__ void __launch_bounds__(LAUNCH_BOUND)
3875
    GpuReduceKernel(SubExecParam* params, int seType, int waveOrder, int numSubIterations)
3876
3877
  {
    int64_t startCycle;
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
    // For warp-level, each warp's first thread records timing; for threadblock-level, only first thread of block
    bool shouldRecordTiming = (seType == 1) ? (threadIdx.x % warpSize == 0) : (threadIdx.x == 0);
    if (shouldRecordTiming) startCycle = GetTimestamp();

    // seType: 0=threadblock, 1=warp
    int subExecIdx;
    if (seType == 0) {
      // Threadblock-level: each threadblock is a subexecutor
      subExecIdx = blockIdx.y;
    } else {
      // Warp-level: each warp is a subexecutor
3889
3890
      int warpIdx       = threadIdx.x / warpSize;
      int warpsPerBlock = blockDim.x  / warpSize;
3891
3892
3893
3894
      subExecIdx = blockIdx.y * warpsPerBlock + warpIdx;
    }

    SubExecParam& p = params[subExecIdx];
3895

3896
3897
    // For warp-level dispatch, inactive warps should return early
    if (seType == 1 && p.N == 0) return;
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908

    // Filter by XCC
#if !defined(__NVCC__)
    int32_t xccId;
    GetXccId(xccId);
    if (p.preferredXccId != -1 && xccId != p.preferredXccId) return;
#endif

    // Collect data information
    int32_t const  numSrcs  = p.numSrcs;
    int32_t const  numDsts  = p.numDsts;
gilbertlee-amd's avatar
gilbertlee-amd committed
3909
3910
3911
3912
    PACKED_FLOAT const* __restrict__ srcFloatPacked[MAX_SRCS];
    PACKED_FLOAT*       __restrict__ dstFloatPacked[MAX_DSTS];
    for (int i = 0; i < numSrcs; i++) srcFloatPacked[i] = (PACKED_FLOAT const*)p.src[i];
    for (int i = 0; i < numDsts; i++) dstFloatPacked[i] = (PACKED_FLOAT*)p.dst[i];
3913
3914
3915
3916

    // Operate on wavefront granularity
    int32_t const nTeams   = p.teamSize;             // Number of threadblocks working together on this subarray
    int32_t const teamIdx  = p.teamIdx;              // Index of this threadblock within the team
3917
3918
3919
    int32_t nWaves, waveIdx;
    if (seType == 0) {
      // Threadblock-level: all wavefronts in block work together
3920
      nWaves  = blockDim.x  / warpSize;              // Number of wavefronts within this threadblock
3921
3922
3923
3924
3925
3926
      waveIdx = threadIdx.x / warpSize;              // Index of this wavefront within the threadblock
    } else {
      // Warp-level: each warp works independently
      nWaves  = 1;
      waveIdx = 0;
    }
3927
3928
    int32_t const tIdx     = threadIdx.x % warpSize; // Thread index within wavefront

gilbertlee-amd's avatar
gilbertlee-amd committed
3929
    size_t  const numPackedFloat = p.N / (sizeof(PACKED_FLOAT)/sizeof(float));
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942

    int32_t teamStride, waveStride, unrlStride, teamStride2, waveStride2;
    switch (waveOrder) {
    case 0: /* U,W,C */ unrlStride = 1; waveStride = UNROLL; teamStride = UNROLL * nWaves;  teamStride2 = nWaves; waveStride2 = 1     ; break;
    case 1: /* U,C,W */ unrlStride = 1; teamStride = UNROLL; waveStride = UNROLL * nTeams;  teamStride2 = 1;      waveStride2 = nTeams; break;
    case 2: /* W,U,C */ waveStride = 1; unrlStride = nWaves; teamStride = nWaves * UNROLL;  teamStride2 = nWaves; waveStride2 = 1     ; break;
    case 3: /* W,C,U */ waveStride = 1; teamStride = nWaves; unrlStride = nWaves * nTeams;  teamStride2 = nWaves; waveStride2 = 1     ; break;
    case 4: /* C,U,W */ teamStride = 1; unrlStride = nTeams; waveStride = nTeams * UNROLL;  teamStride2 = 1;      waveStride2 = nTeams; break;
    case 5: /* C,W,U */ teamStride = 1; waveStride = nTeams; unrlStride = nTeams * nWaves;  teamStride2 = 1;      waveStride2 = nTeams; break;
    }

    int subIterations = 0;
    while (1) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3943
      // First loop: Each wavefront in the team works on UNROLL PACKED_FLOAT per thread
3944
      size_t const loop1Stride = nTeams * nWaves * UNROLL * warpSize;
gilbertlee-amd's avatar
gilbertlee-amd committed
3945
      size_t const loop1Limit  = numPackedFloat / loop1Stride * loop1Stride;
3946
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
3947
        PACKED_FLOAT val[UNROLL];
gilbertlee-amd's avatar
gilbertlee-amd committed
3948
        PACKED_FLOAT tmp[UNROLL];
3949
3950
3951
        if (numSrcs == 0) {
          #pragma unroll
          for (int u = 0; u < UNROLL; u++)
gilbertlee-amd's avatar
gilbertlee-amd committed
3952
            val[u] = MemsetVal<PACKED_FLOAT>();
3953
3954
3955
3956
3957
        }

        for (size_t idx = (teamIdx * teamStride + waveIdx * waveStride) * warpSize + tIdx; idx < loop1Limit; idx += loop1Stride) {
          // Read sources into memory and accumulate in registers
          if (numSrcs) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3958
            #pragma unroll
3959
            for (int u = 0; u < UNROLL; u++)
gilbertlee-amd's avatar
gilbertlee-amd committed
3960
3961
3962
3963
3964
3965
3966
              Load<TEMPORAL_MODE>(&srcFloatPacked[0][idx + u * unrlStride * warpSize], val[u]);

            for (int s = 1; s < numSrcs; s++) {
              #pragma unroll
              for (int u = 0; u < UNROLL; u++)
                Load<TEMPORAL_MODE>(&srcFloatPacked[s][idx + u * unrlStride * warpSize], tmp[u]);
              #pragma unroll
3967
              for (int u = 0; u < UNROLL; u++)
gilbertlee-amd's avatar
gilbertlee-amd committed
3968
3969
                val[u] += tmp[u];
            }
3970
3971
3972
3973
3974
3975
          }

          // Write accumulation to all outputs
          for (int d = 0; d < numDsts; d++) {
            #pragma unroll
            for (int u = 0; u < UNROLL; u++)
gilbertlee-amd's avatar
gilbertlee-amd committed
3976
              Store<TEMPORAL_MODE>(val[u], &dstFloatPacked[d][idx + u * unrlStride * warpSize]);
3977
3978
3979
3980
          }
        }
      }

gilbertlee-amd's avatar
gilbertlee-amd committed
3981
      // Second loop: Deal with remaining PACKED_FLOAT
3982
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
3983
        if (loop1Limit < numPackedFloat) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3984
          PACKED_FLOAT val, tmp;
gilbertlee-amd's avatar
gilbertlee-amd committed
3985
          if (numSrcs == 0) val = MemsetVal<PACKED_FLOAT>();
3986
3987
3988

          size_t const loop2Stride = nTeams * nWaves * warpSize;
          for (size_t idx = loop1Limit + (teamIdx * teamStride2 + waveIdx * waveStride2) * warpSize + tIdx;
gilbertlee-amd's avatar
gilbertlee-amd committed
3989
               idx < numPackedFloat; idx += loop2Stride) {
3990
            if (numSrcs) {
gilbertlee-amd's avatar
gilbertlee-amd committed
3991
3992
3993
3994
3995
              Load<TEMPORAL_MODE>(&srcFloatPacked[0][idx], val);
              for (int s = 1; s < numSrcs; s++) {
                Load<TEMPORAL_MODE>(&srcFloatPacked[s][idx], tmp);
                val += tmp;
              }
3996
3997
            }
            for (int d = 0; d < numDsts; d++)
gilbertlee-amd's avatar
gilbertlee-amd committed
3998
              Store<TEMPORAL_MODE>(val, &dstFloatPacked[d][idx]);
3999
4000
4001
4002
4003
4004
          }
        }
      }

      // Third loop; Deal with remaining floats
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
4005
        if (numPackedFloat * (sizeof(PACKED_FLOAT)/sizeof(float)) < p.N) {
gilbertlee-amd's avatar
gilbertlee-amd committed
4006
          float val, tmp;
4007
4008
4009
          if (numSrcs == 0) val = MemsetVal<float>();

          size_t const loop3Stride = nTeams * nWaves * warpSize;
gilbertlee-amd's avatar
gilbertlee-amd committed
4010
          for (size_t idx = numPackedFloat * (sizeof(PACKED_FLOAT)/sizeof(float)) + (teamIdx * teamStride2 + waveIdx * waveStride2) * warpSize + tIdx; idx < p.N; idx += loop3Stride) {
4011
            if (numSrcs) {
gilbertlee-amd's avatar
gilbertlee-amd committed
4012
4013
4014
4015
4016
              Load<TEMPORAL_MODE>(&p.src[0][idx], val);
              for (int s = 1; s < numSrcs; s++) {
                Load<TEMPORAL_MODE>(&p.src[s][idx], tmp);
                val += tmp;
              }
4017
4018
4019
            }

            for (int d = 0; d < numDsts; d++)
gilbertlee-amd's avatar
gilbertlee-amd committed
4020
              Store<TEMPORAL_MODE>(val, &p.dst[d][idx]);
4021
4022
4023
4024
4025
4026
4027
4028
          }
        }
      }

      if (++subIterations == numSubIterations) break;
    }

    // Wait for all threads to finish
4029
4030
    if (seType == 1) {
      // For warp-level, sync within warp only
4031
4032
4033
4034
 #if defined(__HIP_PLATFORM_AMD__) && (HIP_VERSION_MAJOR < 7)
      __builtin_amdgcn_wave_barrier();
 #else

4035
      __syncwarp();
4036
 #endif
4037
4038
4039
4040
4041
4042
    } else {
      // For threadblock-level, sync all threads
      __syncthreads();
    }

    if (shouldRecordTiming) {
4043
4044
4045
4046
4047
4048
4049
4050
      __threadfence_system();
      p.stopCycle  = GetTimestamp();
      p.startCycle = startCycle;
      GetHwId(p.hwId);
      GetXccId(p.xccId);
    }
  }

4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
#define GPU_KERNEL_TEMPORAL_DECL(LAUNCH_BOUND, UNROLL, DWORD)           \
  {GpuReduceKernel<DWORD, LAUNCH_BOUND, UNROLL, TEMPORAL_NONE>,      \
   GpuReduceKernel<DWORD, LAUNCH_BOUND, UNROLL, TEMPORAL_LOAD>,      \
   GpuReduceKernel<DWORD, LAUNCH_BOUND, UNROLL, TEMPORAL_STORE>,     \
   GpuReduceKernel<DWORD, LAUNCH_BOUND, UNROLL, TEMPORAL_BOTH>}

#define GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, UNROLL)        \
  {GPU_KERNEL_TEMPORAL_DECL(LAUNCH_BOUND, UNROLL, float),  \
   GPU_KERNEL_TEMPORAL_DECL(LAUNCH_BOUND, UNROLL, float2), \
   GPU_KERNEL_TEMPORAL_DECL(LAUNCH_BOUND, UNROLL, float4)}

#define GPU_KERNEL_UNROLL_DECL(LAUNCH_BOUND)    \
  {GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 1),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 2),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 3),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 4),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 5),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 6),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 7),      \
   GPU_KERNEL_DWORD_DECL(LAUNCH_BOUND, 8)}
gilbertlee-amd's avatar
gilbertlee-amd committed
4071

4072
4073
  // Table of all GPU Reduction kernel functions (templated blocksize / unroll / dword size / temporal)
  typedef void (*GpuKernelFuncPtr)(SubExecParam*, int, int, int);
4074
4075
#ifndef SINGLE_KERNEL
  GpuKernelFuncPtr GpuKernelTable[4][MAX_UNROLL][3][4] =
4076
4077
  {
    GPU_KERNEL_UNROLL_DECL(256),
gilbertlee-amd's avatar
gilbertlee-amd committed
4078
4079
4080
    GPU_KERNEL_UNROLL_DECL(512),
    GPU_KERNEL_UNROLL_DECL(768),
    GPU_KERNEL_UNROLL_DECL(1024),
4081
  };
4082
4083
#endif

4084
  #undef GPU_KERNEL_UNROLL_DECL
gilbertlee-amd's avatar
gilbertlee-amd committed
4085
4086
  #undef GPU_KERNEL_DWORD_DECL
  #undef GPU_KERNEL_TEMPORAL_DECL
4087
  #undef GPU_KERNEL_SE_TYPE_DECL
4088
4089
4090
4091

  // Execute a single GPU Transfer (when using 1 stream per Transfer)
  static ErrResult ExecuteGpuTransfer(int           const  iteration,
                                      hipStream_t   const  stream,
4092
4093
                                      hipEvent_t    const  startEvent,
                                      hipEvent_t    const  stopEvent,
4094
4095
                                      int           const  xccDim,
                                      ConfigOptions const& cfg,
gilbertlee-amd's avatar
gilbertlee-amd committed
4096
                                      TransferResources&   rss)
4097
4098
4099
  {
    auto cpuStart = std::chrono::high_resolution_clock::now();

gilbertlee-amd's avatar
gilbertlee-amd committed
4100
    int numSubExecs = rss.subExecParamCpu.size();
4101
4102
    int gridY = CalculateGridY(cfg.gfx.seType, cfg.gfx.blockSize, numSubExecs);
    dim3 const gridSize(xccDim, gridY, 1);
4103
4104
    dim3 const blockSize(cfg.gfx.blockSize, 1);

gilbertlee-amd's avatar
gilbertlee-amd committed
4105
4106
4107
    int wordSizeIdx = cfg.gfx.wordSize == 1 ? 0 :
                      cfg.gfx.wordSize == 2 ? 1 :
                                              2;
4108
4109
4110
4111
4112
#ifdef SINGLE_KERNEL
    auto gpuKernel = GpuReduceKernel<float4, 256, 1, 0>;
#else
    auto gpuKernel = GpuKernelTable[(cfg.gfx.blockSize+255)/256 - 1][cfg.gfx.unrollFactor - 1][wordSizeIdx][cfg.gfx.temporalMode];
#endif
gilbertlee-amd's avatar
gilbertlee-amd committed
4113

4114
#if defined(__NVCC__)
4115
4116
    if (startEvent != NULL)
      ERR_CHECK(hipEventRecord(startEvent, stream));
4117
    gpuKernel<<<gridSize, blockSize, 0, stream>>>(rss.subExecParamGpuPtr, cfg.gfx.seType, cfg.gfx.waveOrder, cfg.general.numSubIterations);
4118
4119
    if (stopEvent != NULL)
      ERR_CHECK(hipEventRecord(stopEvent, stream));
4120
#else
gilbertlee-amd's avatar
gilbertlee-amd committed
4121
    hipExtLaunchKernelGGL(gpuKernel, gridSize, blockSize, 0, stream, startEvent, stopEvent,
4122
                          0, rss.subExecParamGpuPtr, cfg.gfx.seType, cfg.gfx.waveOrder, cfg.general.numSubIterations);
4123
4124
4125
4126
4127
#endif

    ERR_CHECK(hipStreamSynchronize(stream));

    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
4128
    double cpuDeltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0 / cfg.general.numSubIterations;
4129
4130

    if (iteration >= 0) {
4131
4132
4133
4134
      double deltaMsec = cpuDeltaMsec;
      if (startEvent != NULL) {
        float gpuDeltaMsec;
        ERR_CHECK(hipEventElapsedTime(&gpuDeltaMsec, startEvent, stopEvent));
gilbertlee-amd's avatar
gilbertlee-amd committed
4135
        deltaMsec = gpuDeltaMsec / cfg.general.numSubIterations;
4136
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
4137
      rss.totalDurationMsec += deltaMsec;
4138
      if (cfg.general.recordPerIteration) {
gilbertlee-amd's avatar
gilbertlee-amd committed
4139
        rss.perIterMsec.push_back(deltaMsec);
4140
4141
        std::set<std::pair<int,int>> CUs;
        for (int i = 0; i < numSubExecs; i++) {
gilbertlee-amd's avatar
gilbertlee-amd committed
4142
4143
          CUs.insert(std::make_pair(rss.subExecParamGpuPtr[i].xccId,
                                    GetId(rss.subExecParamGpuPtr[i].hwId)));
4144
        }
gilbertlee-amd's avatar
gilbertlee-amd committed
4145
        rss.perIterCUs.push_back(CUs);
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
      }
    }
    return ERR_NONE;
  }

  // Execute a single GPU executor
  static ErrResult RunGpuExecutor(int           const  iteration,
                                  ConfigOptions const& cfg,
                                  int           const  exeIndex,
                                  ExeInfo&             exeInfo)
  {
    auto cpuStart = std::chrono::high_resolution_clock::now();
    ERR_CHECK(hipSetDevice(exeIndex));

    int xccDim = exeInfo.useSubIndices ? exeInfo.numSubIndices : 1;

    if (cfg.gfx.useMultiStream) {
      // Launch each Transfer separately in its own stream
      vector<std::future<ErrResult>> asyncTransfers;
      for (int i = 0; i < exeInfo.streams.size(); i++) {
        asyncTransfers.emplace_back(std::async(std::launch::async,
                                               ExecuteGpuTransfer,
                                               iteration,
                                               exeInfo.streams[i],
4170
4171
                                               cfg.gfx.useHipEvents ? exeInfo.startEvents[i] : NULL,
                                               cfg.gfx.useHipEvents ? exeInfo.stopEvents[i] : NULL,
4172
4173
4174
4175
4176
4177
4178
4179
4180
                                               xccDim,
                                               std::cref(cfg),
                                               std::ref(exeInfo.resources[i])));
      }
      for (auto& asyncTransfer : asyncTransfers)
        ERR_CHECK(asyncTransfer.get());
    } else {
      // Combine all the Transfers into a single kernel launch
      int numSubExecs = exeInfo.totalSubExecs;
4181
4182
      int gridY = CalculateGridY(cfg.gfx.seType, cfg.gfx.blockSize, numSubExecs);
      dim3 const gridSize(xccDim, gridY, 1);
4183
4184
4185
      dim3 const blockSize(cfg.gfx.blockSize, 1);
      hipStream_t stream = exeInfo.streams[0];

gilbertlee-amd's avatar
gilbertlee-amd committed
4186
4187
4188
      int wordSizeIdx = cfg.gfx.wordSize == 1 ? 0 :
                        cfg.gfx.wordSize == 2 ? 1 :
                                                2;
4189
4190
4191
4192
4193
#ifdef SINGLE_KERNEL
      auto gpuKernel = GpuReduceKernel<float4, 256, 1, 0>;
#else
      auto gpuKernel = GpuKernelTable[(cfg.gfx.blockSize+255)/256 - 1][cfg.gfx.unrollFactor - 1][wordSizeIdx][cfg.gfx.temporalMode];
#endif
gilbertlee-amd's avatar
gilbertlee-amd committed
4194

4195
4196
4197
#if defined(__NVCC__)
      if (cfg.gfx.useHipEvents)
        ERR_CHECK(hipEventRecord(exeInfo.startEvents[0], stream));
4198
      gpuKernel<<<gridSize, blockSize, 0 , stream>>>(exeInfo.subExecParamGpu, cfg.gfx.seType, cfg.gfx.waveOrder, cfg.general.numSubIterations);
4199
4200
4201
      if (cfg.gfx.useHipEvents)
        ERR_CHECK(hipEventRecord(exeInfo.stopEvents[0], stream));
#else
gilbertlee-amd's avatar
gilbertlee-amd committed
4202
      hipExtLaunchKernelGGL(gpuKernel, gridSize, blockSize, 0, stream,
4203
4204
                            cfg.gfx.useHipEvents ? exeInfo.startEvents[0] : NULL,
                            cfg.gfx.useHipEvents ? exeInfo.stopEvents[0] : NULL, 0,
4205
                            exeInfo.subExecParamGpu, cfg.gfx.seType, cfg.gfx.waveOrder, cfg.general.numSubIterations);
4206
4207
4208
4209
#endif
      ERR_CHECK(hipStreamSynchronize(stream));
    }
    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
4210
4211
    double cpuDeltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0
      / cfg.general.numSubIterations;
4212
4213

    if (iteration >= 0) {
4214
      if (cfg.gfx.useHipEvents && !cfg.gfx.useMultiStream) {
4215
4216
        float gpuDeltaMsec;
        ERR_CHECK(hipEventElapsedTime(&gpuDeltaMsec, exeInfo.startEvents[0], exeInfo.stopEvents[0]));
gilbertlee-amd's avatar
gilbertlee-amd committed
4217
        gpuDeltaMsec /= cfg.general.numSubIterations;
4218
4219
4220
4221
4222
4223
        exeInfo.totalDurationMsec += gpuDeltaMsec;
      } else {
        exeInfo.totalDurationMsec += cpuDeltaMsec;
      }

      // Determine timing for each of the individual transfers that were part of this launch
4224
4225
      if (!cfg.gfx.useMultiStream) {
        for (int i = 0; i < exeInfo.resources.size(); i++) {
gilbertlee-amd's avatar
gilbertlee-amd committed
4226
          TransferResources& rss = exeInfo.resources[i];
4227
4228
4229
4230
          long long minStartCycle = std::numeric_limits<long long>::max();
          long long maxStopCycle  = std::numeric_limits<long long>::min();
          std::set<std::pair<int, int>> CUs;

gilbertlee-amd's avatar
gilbertlee-amd committed
4231
          for (auto subExecIdx : rss.subExecIdx) {
4232
4233
4234
4235
4236
4237
            minStartCycle = std::min(minStartCycle, exeInfo.subExecParamGpu[subExecIdx].startCycle);
            maxStopCycle  = std::max(maxStopCycle,  exeInfo.subExecParamGpu[subExecIdx].stopCycle);
            if (cfg.general.recordPerIteration) {
              CUs.insert(std::make_pair(exeInfo.subExecParamGpu[subExecIdx].xccId,
                                        GetId(exeInfo.subExecParamGpu[subExecIdx].hwId)));
            }
4238
          }
4239
          double deltaMsec = (maxStopCycle - minStartCycle) / (double)(exeInfo.wallClockRate);
gilbertlee-amd's avatar
gilbertlee-amd committed
4240
          deltaMsec /= cfg.general.numSubIterations;
gilbertlee-amd's avatar
gilbertlee-amd committed
4241
          rss.totalDurationMsec += deltaMsec;
4242
          if (cfg.general.recordPerIteration) {
gilbertlee-amd's avatar
gilbertlee-amd committed
4243
4244
            rss.perIterMsec.push_back(deltaMsec);
            rss.perIterCUs.push_back(CUs);
4245
          }
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
        }
      }
    }
    return ERR_NONE;
  }

// DMA Executor-related functions
//========================================================================================

  // Execute a single DMA Transfer
  static ErrResult ExecuteDmaTransfer(int           const  iteration,
                                      bool          const  useSubIndices,
                                      hipStream_t   const  stream,
                                      hipEvent_t    const  startEvent,
                                      hipEvent_t    const  stopEvent,
                                      ConfigOptions const& cfg,
                                      TransferResources&   resources)
  {
    auto cpuStart = std::chrono::high_resolution_clock::now();

    int subIterations = 0;
    if (!useSubIndices && !cfg.dma.useHsaCopy) {
      if (cfg.dma.useHipEvents)
        ERR_CHECK(hipEventRecord(startEvent, stream));

      // Use hipMemcpy
      do {
        ERR_CHECK(hipMemcpyAsync(resources.dstMem[0], resources.srcMem[0], resources.numBytes,
                                 hipMemcpyDefault, stream));
      } while (++subIterations != cfg.general.numSubIterations);

      if (cfg.dma.useHipEvents)
        ERR_CHECK(hipEventRecord(stopEvent, stream));
      ERR_CHECK(hipStreamSynchronize(stream));
    } else {
#if defined(__NVCC__)
      return {ERR_FATAL, "HSA copy not supported on NVIDIA hardware"};
#else
      // Use HSA async copy
      do {
        hsa_signal_store_screlease(resources.signal, 1);
4287
        if (!useSubIndices) {
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
          ERR_CHECK(hsa_amd_memory_async_copy(resources.dstMem[0], resources.dstAgent,
                                              resources.srcMem[0], resources.srcAgent,
                                              resources.numBytes, 0, NULL,
                                              resources.signal));
        } else {
          HSA_CALL(hsa_amd_memory_async_copy_on_engine(resources.dstMem[0], resources.dstAgent,
                                                       resources.srcMem[0], resources.srcAgent,
                                                       resources.numBytes, 0, NULL,
                                                       resources.signal,
                                                       resources.sdmaEngineId, true));
        }
        // Wait for SDMA transfer to complete
        while(hsa_signal_wait_scacquire(resources.signal,
                                        HSA_SIGNAL_CONDITION_LT, 1, UINT64_MAX,
                                        HSA_WAIT_STATE_ACTIVE) >= 1);
      } while (++subIterations != cfg.general.numSubIterations);
#endif
    }
    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
4307
    double cpuDeltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0 / cfg.general.numSubIterations;
4308
4309
4310
4311
4312
4313

    if (iteration >= 0) {
      double deltaMsec = cpuDeltaMsec;
      if (!useSubIndices && !cfg.dma.useHsaCopy && cfg.dma.useHipEvents) {
        float gpuDeltaMsec;
        ERR_CHECK(hipEventElapsedTime(&gpuDeltaMsec, startEvent, stopEvent));
gilbertlee-amd's avatar
gilbertlee-amd committed
4314
        deltaMsec = gpuDeltaMsec / cfg.general.numSubIterations;
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
      }
      resources.totalDurationMsec += deltaMsec;
      if (cfg.general.recordPerIteration)
        resources.perIterMsec.push_back(deltaMsec);
    }
    return ERR_NONE;
  }

  // Execute a single DMA executor
  static ErrResult RunDmaExecutor(int           const  iteration,
                                  ConfigOptions const& cfg,
                                  int           const  exeIndex,
                                  ExeInfo&             exeInfo)
  {
    auto cpuStart = std::chrono::high_resolution_clock::now();
    ERR_CHECK(hipSetDevice(exeIndex));

    vector<std::future<ErrResult>> asyncTransfers;
    for (int i = 0; i < exeInfo.resources.size(); i++) {
      asyncTransfers.emplace_back(std::async(std::launch::async,
                                             ExecuteDmaTransfer,
                                             iteration,
                                             exeInfo.useSubIndices,
                                             exeInfo.streams[i],
                                             cfg.dma.useHipEvents ? exeInfo.startEvents[i] : NULL,
                                             cfg.dma.useHipEvents ? exeInfo.stopEvents[i]  : NULL,
                                             std::cref(cfg),
                                             std::ref(exeInfo.resources[i])));
    }

    for (auto& asyncTransfer : asyncTransfers)
      ERR_CHECK(asyncTransfer.get());

    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
4349
    double deltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0 / cfg.general.numSubIterations;
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
    if (iteration >= 0)
      exeInfo.totalDurationMsec += deltaMsec;
    return ERR_NONE;
  }

// Executor-related functions
//========================================================================================
  static ErrResult RunExecutor(int           const  iteration,
                               ConfigOptions const& cfg,
                               ExeDevice     const& exeDevice,
                               ExeInfo&             exeInfo)
  {
    switch (exeDevice.exeType) {
    case EXE_CPU:     return RunCpuExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo);
    case EXE_GPU_GFX: return RunGpuExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo);
    case EXE_GPU_DMA: return RunDmaExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo);
gilbertlee-amd's avatar
gilbertlee-amd committed
4366
4367
4368
#ifdef NIC_EXEC_ENABLED
    case EXE_NIC:     return RunNicExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo);
#endif
4369
4370
4371
4372
4373
4374
    default:          return {ERR_FATAL, "Unsupported executor (%d)", exeDevice.exeType};
    }
  }

} // End of anonymous namespace
//========================================================================================
srawat's avatar
srawat committed
4375
/// @endcond
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431

  ErrResult::ErrResult(ErrType err) : errType(err), errMsg("") {};

  ErrResult::ErrResult(hipError_t err)
  {
    if (err == hipSuccess) {
      this->errType = ERR_NONE;
      this->errMsg  = "";
    } else {
      this->errType = ERR_FATAL;
      this->errMsg  = std::string("HIP Error: ") + hipGetErrorString(err);
    }
  }

#if !defined(__NVCC__)
  ErrResult::ErrResult(hsa_status_t err)
  {
    if (err == HSA_STATUS_SUCCESS) {
      this->errType = ERR_NONE;
      this->errMsg  = "";
    } else {
      const char *errString = NULL;
      hsa_status_string(err, &errString);
      this->errType = ERR_FATAL;
      this->errMsg  = std::string("HSA Error: ") + errString;
    }
  }
#endif

  ErrResult::ErrResult(ErrType errType, const char* format, ...)
  {
    this->errType = errType;
    va_list args, args_temp;
    va_start(args, format);
    va_copy(args_temp, args);

    int len = vsnprintf(nullptr, 0, format, args);
    if (len < 0) {
      va_end(args_temp);
      va_end(args);
    } else {
      this->errMsg.resize(len);
      vsnprintf(this->errMsg.data(), len+1, format, args_temp);
    }
    va_end(args_temp);
    va_end(args);
  }

  bool RunTransfers(ConfigOptions         const& cfg,
                    std::vector<Transfer> const& transfers,
                    TestResults&                 results)
  {
    // Clear all errors;
    auto& errResults = results.errResults;
    errResults.clear();

4432
4433
4434
4435
4436
    // Check for valid configuration and quit if any rank has fatal error
    if (System::Get().Any(ConfigOptionsHaveErrors(cfg, errResults))) {
      System::Get().AllGatherErrors(errResults);
      return false;
    }
4437

4438
4439
4440
4441
4442
    // Check for valid transfers and quit if any rank has fatal error
    if (System::Get().Any(TransfersHaveErrors(cfg, transfers, errResults))) {
      System::Get().AllGatherErrors(errResults);
      return false;
    }
4443
4444
4445
4446
4447
4448
4449
4450

    // Collect up transfers by executor
    int minNumSrcs = MAX_SRCS + 1;
    int maxNumSrcs = 0;
    size_t maxNumBytes = 0;
    std::map<ExeDevice, ExeInfo> executorMap;
    for (int i = 0; i < transfers.size(); i++) {
      Transfer const& t = transfers[i];
gilbertlee-amd's avatar
gilbertlee-amd committed
4451
      ExeDevice exeDevice;
4452
      ERR_APPEND(GetActualExecutor(t.exeDevice, exeDevice), errResults);
4453
4454
4455
4456

      TransferResources resource = {};
      resource.transferIdx = i;

gilbertlee-amd's avatar
gilbertlee-amd committed
4457
4458
4459
4460
4461
      ExeInfo& exeInfo = executorMap[exeDevice];
      exeInfo.totalBytes    += t.numBytes;
      exeInfo.totalSubExecs += t.numSubExecs;
      exeInfo.useSubIndices |= (t.exeSubIndex != -1 || (t.exeDevice.exeType == EXE_GPU_GFX && !cfg.gfx.prefXccTable.empty()));
      exeInfo.resources.push_back(resource);
4462
4463
4464
4465
4466
4467
4468
4469
      minNumSrcs  = std::min(minNumSrcs, (int)t.srcs.size());
      maxNumSrcs  = std::max(maxNumSrcs, (int)t.srcs.size());
      maxNumBytes = std::max(maxNumBytes, t.numBytes);
    }

    // Loop over each executor and prepare
    // - Allocates memory for each Transfer
    // - Set up work for subexecutors
4470
4471
    int const localRank = GetRank();
    vector<ExeDevice> localExecutors;
4472
4473
4474
4475
4476
4477
4478
4479
4480
    vector<TransferResources*> transferResources;
    for (auto& exeInfoPair : executorMap) {
      ExeDevice const& exeDevice = exeInfoPair.first;
      ExeInfo&         exeInfo   = exeInfoPair.second;
      ERR_APPEND(PrepareExecutor(cfg, transfers, exeDevice, exeInfo), errResults);

      for (auto& resource : exeInfo.resources) {
        transferResources.push_back(&resource);
      }
4481
4482
4483
4484
      // Track executors that are on this rank
      if (exeDevice.exeRank == localRank) {
        localExecutors.push_back(exeDevice);
      }
4485
4486
4487
4488
4489
4490
4491
    }

    // Prepare reference src/dst arrays - only once for largest size
    size_t maxN = maxNumBytes / sizeof(float);
    vector<float> outputBuffer(maxN);
    vector<vector<float>> dstReference(maxNumSrcs + 1, vector<float>(maxN));
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
4492
      size_t initOffset = cfg.data.byteOffset / sizeof(float);
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
      vector<vector<float>> srcReference(maxNumSrcs, vector<float>(maxN));
      memset(dstReference[0].data(), MEMSET_CHAR, maxNumBytes);

      for (int numSrcs = 0; numSrcs < maxNumSrcs; numSrcs++) {
        PrepareReference(cfg, srcReference[numSrcs], numSrcs);
        for (int i = 0; i < maxN; i++) {
          dstReference[numSrcs+1][i] = (numSrcs == 0 ? 0 : dstReference[numSrcs][i]) + srcReference[numSrcs][i];
        }
      }
      // Release un-used partial sums
      for (int numSrcs = 0; numSrcs < minNumSrcs; numSrcs++)
        dstReference[numSrcs].clear();

4506
      // Initialize all src memory buffers (if on local rank)
4507
      for (auto resource : transferResources) {
4508
        Transfer const& t = transfers[resource->transferIdx];
4509
        for (int srcIdx = 0; srcIdx < resource->srcMem.size(); srcIdx++) {
4510
4511
4512
4513
          if (t.srcs[srcIdx].memRank == localRank) {
            ERR_APPEND(hipMemcpy(resource->srcMem[srcIdx] + initOffset, srcReference[srcIdx].data(), resource->numBytes,
                                 hipMemcpyDefault), errResults);
          }
4514
4515
4516
4517
        }
      }
    }

4518
4519
    // Pause before starting when running in iteractive mode
    if (cfg.general.useInteractive) {
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
      if (localRank == 0) {
        printf("Memory prepared:\n");

        for (int i = 0; i < transfers.size(); i++) {
          printf("Transfer %03d:\n", i);
          for (int iSrc = 0; iSrc < transfers[i].srcs.size(); ++iSrc)
            printf("  SRC %0d: %p\n", iSrc, transferResources[i]->srcMem[iSrc]);
          for (int iDst = 0; iDst < transfers[i].dsts.size(); ++iDst)
            printf("  DST %0d: %p\n", iDst, transferResources[i]->dstMem[iDst]);
        }
        printf("Hit <Enter> to continue: ");
        fflush(stdout);
        if (scanf("%*c") != 0) {
          printf("[ERROR] Unexpected input\n");
          exit(1);
        }
        printf("\n");
4537
      }
4538
      System::Get().Barrier();
4539
4540
    }

4541
4542
4543
4544
4545
4546
4547
    // Perform iterations
    size_t numTimedIterations = 0;
    double totalCpuTimeSec = 0.0;
    for (int iteration = -cfg.general.numWarmups; ; iteration++) {
      // Stop if number of iterations/seconds has reached limit
      if (cfg.general.numIterations > 0 && iteration >= cfg.general.numIterations) break;

4548
4549
4550
4551
4552
4553
4554
      // NOTE: Time-based limit is based on first rank to avoid any skew issues
      bool shouldStop = (cfg.general.numIterations < 0 && totalCpuTimeSec > -cfg.general.numIterations);
      System::Get().Broadcast(0, sizeof(shouldStop), &shouldStop);
      if (shouldStop) break;

      // Wait for all ranks before starting any timing
      System::Get().Barrier();
4555
4556
4557
4558
4559
4560

      // Start CPU timing for this iteration
      auto cpuStart = std::chrono::high_resolution_clock::now();

      // Execute all Transfers in parallel
      std::vector<std::future<ErrResult>> asyncExecutors;
4561
      for (auto const& exeDevice : localExecutors) {
4562
4563
4564
        asyncExecutors.emplace_back(std::async(std::launch::async, RunExecutor,
                                               iteration,
                                               std::cref(cfg),
4565
4566
                                               std::cref(exeDevice),
                                               std::ref(executorMap[exeDevice])));
4567
4568
4569
4570
4571
4572
4573
      }

      // Wait for all threads to finish
      for (auto& asyncExecutor : asyncExecutors) {
        ERR_APPEND(asyncExecutor.get(), errResults);
      }

4574
4575
4576
4577
      // Wait for all ranks to finish
      System::Get().Barrier();

      // Stop CPU timing for this iteration
4578
      auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
gilbertlee-amd's avatar
gilbertlee-amd committed
4579
      double deltaSec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() / cfg.general.numSubIterations;
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593

      if (cfg.data.alwaysValidate) {
        ERR_APPEND(ValidateAllTransfers(cfg, transfers, transferResources, dstReference, outputBuffer),
                   errResults);
      }

      if (iteration >= 0) {
        ++numTimedIterations;
        totalCpuTimeSec += deltaSec;
      }
    }

    // Pause for interactive mode
    if (cfg.general.useInteractive) {
4594
4595
4596
4597
4598
4599
4600
4601
      if (localRank == 0) {
        printf("Transfers complete. Hit <Enter> to continue: ");
        if (scanf("%*c") != 0)  {
          printf("[ERROR] Unexpected input\n");
          exit(1);
        }
        printf("\n");
        fflush(stdout);
4602
      }
4603
      System::Get().Barrier();
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
    }

    // Validate results
    if (!cfg.data.alwaysValidate) {
      ERR_APPEND(ValidateAllTransfers(cfg, transfers, transferResources, dstReference, outputBuffer),
                 errResults);
    }

    // Prepare results
    results.exeResults.clear();
    results.tfrResults.clear();
    results.tfrResults.resize(transfers.size());
    results.numTimedIterations = numTimedIterations;
    results.totalBytesTransferred = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
4618
    results.avgTotalDurationMsec = (totalCpuTimeSec * 1000.0) / numTimedIterations;
gilbertlee-amd's avatar
gilbertlee-amd committed
4619
    results.overheadMsec = results.avgTotalDurationMsec;
4620
4621
4622
4623
4624
4625
    for (auto& exeInfoPair : executorMap) {
      ExeDevice const& exeDevice = exeInfoPair.first;
      ExeInfo&         exeInfo   = exeInfoPair.second;

      results.totalBytesTransferred += exeInfo.totalBytes;

4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
      // Copy over executor results
      ExeResult exeResult;
      if (exeDevice.exeRank == localRank) {
        // Local executor collects results
        exeResult.numBytes             = exeInfo.totalBytes;
        exeResult.avgDurationMsec      = exeInfo.totalDurationMsec / numTimedIterations;
        exeResult.avgBandwidthGbPerSec = (exeResult.numBytes / 1.0e6) /  exeResult.avgDurationMsec;
        exeResult.sumBandwidthGbPerSec = 0.0;
        exeResult.transferIdx.clear();

        // Copy over transfer results
        for (auto const& rss : exeInfo.resources) {
          int const transferIdx = rss.transferIdx;
          exeResult.transferIdx.push_back(transferIdx);

          TransferResult& tfrResult      = results.tfrResults[transferIdx];
          tfrResult.exeDevice            = exeDevice;
gilbertlee-amd's avatar
gilbertlee-amd committed
4643
#ifdef NIC_EXEC_ENABLED
4644
          tfrResult.exeDstDevice         = {exeDevice.exeType, rss.dstNicIndex};
gilbertlee-amd's avatar
gilbertlee-amd committed
4645
#else
4646
          tfrResult.exeDstDevice         = exeDevice;
gilbertlee-amd's avatar
gilbertlee-amd committed
4647
#endif
4648
4649
4650
4651
4652
4653
4654
4655
          tfrResult.numBytes             = rss.numBytes;
          tfrResult.avgDurationMsec      = rss.totalDurationMsec / numTimedIterations;
          tfrResult.avgBandwidthGbPerSec = (rss.numBytes / 1.0e6) / tfrResult.avgDurationMsec;
          if (cfg.general.recordPerIteration) {
            tfrResult.perIterMsec = rss.perIterMsec;
            tfrResult.perIterCUs  = rss.perIterCUs;
          }
          exeResult.sumBandwidthGbPerSec += tfrResult.avgBandwidthGbPerSec;
4656
4657
        }
      }
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667

      // Send executor and transfer result to all ranks
      System::Get().BroadcastExeResult(exeDevice.exeRank, exeResult);
      for (int const transferIdx : exeResult.transferIdx) {
        System::Get().BroadcastTfrResult(exeDevice.exeRank, results.tfrResults[transferIdx]);
      }

      results.exeResults[exeDevice] = exeResult;
      results.overheadMsec = std::min(results.overheadMsec, (results.avgTotalDurationMsec -
                                                             exeResult.avgDurationMsec));
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
    }
    results.avgTotalBandwidthGbPerSec = (results.totalBytesTransferred / 1.0e6) / results.avgTotalDurationMsec;

    // Teardown executors
    for (auto& exeInfoPair : executorMap) {
      ExeDevice const& exeDevice = exeInfoPair.first;
      ExeInfo&         exeInfo   = exeInfoPair.second;
      ERR_APPEND(TeardownExecutor(cfg, exeDevice, transfers, exeInfo), errResults);
    }

4678
4679
4680
4681
4682
    System::Get().AllGatherErrors(errResults);

    for (auto const& err : errResults) {
      if (err.errType == ERR_FATAL) return false;
    }
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
    return true;
  }

  int GetIntAttribute(IntAttribute attribute)
  {
    switch (attribute) {
    case ATR_GFX_MAX_BLOCKSIZE: return MAX_BLOCKSIZE;
    case ATR_GFX_MAX_UNROLL:    return MAX_UNROLL;
    default:                    return -1;
    }
  }

  std::string GetStrAttribute(StrAttribute attribute)
  {
    switch (attribute) {
    case ATR_SRC_PREP_DESCRIPTION:
      return "Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1)";
    default:
      return "";
    }
  }

4705
4706
4707
4708
4709
  bool RecursiveWildcardTransferExpansion(WildcardTransfer& wc,
                                          int const& baseRankIndex,
                                          size_t const& numBytes,
                                          int const& numSubExecs,
                                          std::vector<Transfer>& transfers)
4710
  {
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
    // Basic implementation idea:
    // - This recursive function procedes through each Transfer characteristic that has multiple possible values,
    //   selects one, then proceeds.
    // - At the "end", each characteristic will only have one option, which will then be used to specify the
    //   Transfer to be added to transfers
    bool result = false;

    // Resolve memory wildcards first
    for (int isDst = 0; isDst <= 1; isDst++) {
      for (int iMem = 0; iMem < wc.mem[isDst].size(); iMem++) {

        // Resolve mem rank wildcards first
        if (wc.mem[isDst][iMem].memRanks.size() == 0) {
          // Replace empty rank with baseRankIndex
          wc.mem[isDst][iMem].memRanks = {baseRankIndex};
          RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
          wc.mem[isDst][iMem].memRanks.clear();
          return true;
        } else if (wc.mem[isDst][iMem].memRanks.size() > 1) {
          // Loop over each possible rank and recurse
          std::vector<int> memRanks;
          memRanks.swap(wc.mem[isDst][iMem].memRanks);
          for (auto x : memRanks) {
            wc.mem[isDst][iMem].memRanks = {x};
            result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
          }
          wc.mem[isDst][iMem].memRanks.swap(memRanks);
          return result;
        }
        // At this point, there should be only 1 (valid) rank assigned to this SRC
        if (wc.mem[isDst][iMem].memRanks.size() != 1 || wc.mem[isDst][iMem].memRanks[0] < 0) {
          printf("[ERROR] Unexpected number of ranks / invalid number of ranks for %s %d\n", isDst ? "DST" : "SRC", iMem);
          exit(1);
        }
4745

4746
4747
4748
4749
4750
4751
        // Resolve mem index wildcards
        // Mem devices should have at least one index
        if (wc.mem[isDst][iMem].memIndices.size() == 0) {
          printf("[ERROR] MemIndex for %s %d cannot be empty\n", isDst ? "DST" : "SRC", iMem);
          exit(1);
        }
4752

4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
        // Loop over user provided list of device indices
        if (wc.mem[isDst][iMem].memIndices.size() > 1) {
          std::vector<int> memIndices;
          memIndices.swap(wc.mem[isDst][iMem].memIndices);
          for (auto x : memIndices) {
            wc.mem[isDst][iMem].memIndices = {x};
            result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
          }
          wc.mem[isDst][iMem].memIndices.swap(memIndices);
          return result;
        } else if (wc.mem[isDst][iMem].memIndices.size() == 1 && wc.mem[isDst][iMem].memIndices[0] == -1) {
          // Wildcard - loop over all possible device indices for this memory type
          int numExecutors = GetNumExecutors(wc.mem[isDst][iMem].memType, wc.mem[isDst][iMem].memRanks[0]);
          for (int x = 0; x < numExecutors; x++) {
            wc.mem[isDst][iMem].memIndices[0] = x;
            result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
          }
          wc.mem[isDst][iMem].memIndices[0] = -1;
          return result;
        }
4773
4774
4775
      }
    }

4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
    // Check for NIC wildcard (device index) first
    if (wc.exe.exeType == EXE_NIC_NEAREST &&
        wc.exe.exeRanks.size() == 0 &&
        wc.exe.exeIndices.size() == 0 &&
        wc.exe.exeSlots.size() == 0 &&
        wc.exe.exeSubIndices.size() == 0 &&
        wc.exe.exeSubSlots.size() == 0) {

      // Find (first) closest NIC to the SRC memory location
      std::vector<int> srcNicIndices;
      if (IsCpuMemType(wc.mem[0][0].memType)) {
        GetClosestNicsToCpu(srcNicIndices, wc.mem[0][0].memIndices[0], wc.mem[0][0].memRanks[0]);
4788
      } else {
4789
4790
4791
4792
4793
4794
4795
4796
        GetClosestNicsToGpu(srcNicIndices, wc.mem[0][0].memIndices[0], wc.mem[0][0].memRanks[0]);
      }
      // Find (first) closest NIC to the DST memory location
      std::vector<int> dstNicIndices;
      if (IsCpuMemType(wc.mem[1][0].memType)) {
        GetClosestNicsToCpu(dstNicIndices, wc.mem[1][0].memIndices[0], wc.mem[1][0].memRanks[0]);
      } else {
        GetClosestNicsToGpu(dstNicIndices, wc.mem[1][0].memIndices[0], wc.mem[1][0].memRanks[0]);
4797
4798
      }

4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
      // If valid, fill in all wildcards
      if (srcNicIndices.size() > 0 && dstNicIndices.size() > 0) {
        wc.exe.exeRanks      = {wc.mem[0][0].memRanks[0]};
        wc.exe.exeIndices    = {srcNicIndices[0]};
        wc.exe.exeSlots      = {0};
        wc.exe.exeSubIndices = {dstNicIndices[0]};
        wc.exe.exeSubSlots   = {0};

        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);

        wc.exe.exeRanks.clear();
        wc.exe.exeIndices.clear();
        wc.exe.exeSlots.clear();
        wc.exe.exeSubIndices.clear();
        wc.exe.exeSubSlots.clear();
        return result;
      } else {
        return false;
      }
4818
4819
    }

4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
    // Resolve EXE rank
    if (wc.exe.exeRanks.size() == 0)  {
      // No rank provided - Assign the current base rank index
      wc.exe.exeRanks = {baseRankIndex};
      RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      wc.exe.exeRanks.clear();
      return true;
    } else if (wc.exe.exeRanks.size() > 1) {
      // Loop over user provided ranks
      std::vector<int> exeRanks;
      exeRanks.swap(wc.exe.exeRanks);
      for (auto x : exeRanks) {
        wc.exe.exeRanks = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeRanks.swap(exeRanks);
      return result;
    } else if (wc.exe.exeRanks[0] == -1) {
      printf("[ERROR] Exe rank should not be -1\n");
      exit(1);
4840
    }
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864

    // Resolve EXE indices
    if (wc.exe.exeIndices.size() == 0) {
      printf("[ERROR] Exe index should never be empty\n");
      exit(1);
    } else if (wc.exe.exeIndices.size() > 1) {
      // Loop over user provided indices
      std::vector<int> exeIndices;
      exeIndices.swap(wc.exe.exeIndices);
      for (auto x : exeIndices) {
        wc.exe.exeIndices = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeIndices.swap(exeIndices);
      return result;
    } else if (wc.exe.exeIndices[0] == -1) {
      // Wildcard - loop over all possible executor indices
      int numExecutors = GetNumExecutors(wc.exe.exeType, wc.exe.exeRanks[0]);
      for (int x = 0; x < numExecutors; x++) {
        wc.exe.exeIndices[0] = x;
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeIndices[0] = -1;
      return result;
gilbertlee-amd's avatar
gilbertlee-amd committed
4865
    }
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004

    // Resolve EXE slots (only apples to EXE_NIC_NEAREST)
    if (wc.exe.exeSlots.size() == 0) {
      // Slot won't be used, so just assign 0
      wc.exe.exeSlots = {0};
      result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      wc.exe.exeSlots.clear();
      return result;
    } else if (wc.exe.exeSlots.size() > 1) {
      // Loop over user provided slots
      std::vector<int> exeSlots;
      exeSlots.swap(wc.exe.exeSlots);
      for (auto x : exeSlots) {
        wc.exe.exeSlots = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeSlots.swap(exeSlots);
      return result;
    } else if (wc.exe.exeSlots[0] == -1) {
      // Wildcard - Loop over all possible slots, based on SRC memory type
      std::vector<int> srcNicIndices;
      if (IsCpuMemType(wc.mem[0][0].memType)) {
        GetClosestNicsToCpu(srcNicIndices, wc.mem[0][0].memIndices[0], wc.mem[0][0].memRanks[0]);
      } else {
        GetClosestNicsToGpu(srcNicIndices, wc.mem[0][0].memIndices[0], wc.mem[0][0].memRanks[0]);
      }
      for (auto x : srcNicIndices) {
        wc.exe.exeSlots = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeSlots = {-1};
      return result;
    }

    // Resolve EXE subindex
    if (wc.exe.exeSubIndices.size() == 0) {
      if (IsCpuExeType(wc.exe.exeType) || IsGpuExeType(wc.exe.exeType)) {
        wc.exe.exeSubIndices = {-1};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
        wc.exe.exeSubIndices.clear();
        return result;
      } else if (wc.exe.exeType == EXE_NIC) {
        printf("[ERROR] NIC executor requires a subindex be specified\n");
        exit(1);
      } else if (wc.exe.exeType == EXE_NIC_NEAREST) {
        // Assign NIC closest to DST mem
        std::vector<int> dstNicIndices;
        if (IsCpuMemType(wc.mem[1][0].memType)) {
          GetClosestNicsToCpu(dstNicIndices, wc.mem[1][0].memIndices[0], wc.mem[1][0].memRanks[0]);
        } else {
          GetClosestNicsToGpu(dstNicIndices, wc.mem[1][0].memIndices[0], wc.mem[1][0].memRanks[0]);
        }
        if (dstNicIndices.size() > 0) {
          wc.exe.exeSubIndices = {dstNicIndices[0]};
          result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
          wc.exe.exeSubIndices.clear();
        }
        return result;
      }
    } else if (wc.exe.exeSubIndices.size() > 1) {
      // Loop over all user provided subindices
      std::vector<int> exeSubIndices;
      exeSubIndices.swap(wc.exe.exeSubIndices);
      for (auto x : exeSubIndices) {
        wc.exe.exeSubIndices = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeSubIndices.swap(exeSubIndices);
      return result;
    } else if (wc.exe.exeSubIndices[0] == -2) {
      switch (wc.exe.exeType) {
      case EXE_CPU:
        wc.exe.exeSubIndices[0] = -1;
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
        wc.exe.exeSubIndices[0] = -2;
        return result;
      case EXE_GPU_GFX: case EXE_GPU_DMA:
      {
        // Iterate over all available subindices
        ExeDevice exeDevice = {wc.exe.exeType, wc.exe.exeIndices[0], wc.exe.exeRanks[0], 0};
        int numSubIndices = GetNumExecutorSubIndices(exeDevice);
        for (int x = 0; x < numSubIndices; x++) {
          wc.exe.exeSubIndices = {x};
          result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
        }
        wc.exe.exeSubIndices = {-1};
        return result;
      }
      case EXE_NIC: case EXE_NIC_NEAREST:
      {
        // Iterates over total number of DST NICs
        int numIndices = 0;
        if (wc.exe.exeType == EXE_NIC) {
          numIndices = GetNumExecutors(EXE_NIC, wc.mem[1][0].memRanks[0]);
        } else {
          numIndices = GetNumExecutors(EXE_GPU_GFX, wc.mem[1][0].memRanks[0]);
        }
        for (int x = 0; x < numIndices; x++) {
          wc.exe.exeSubIndices = {x};
          result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
        }
        wc.exe.exeSubIndices = {-1};
        return result;
      }
      }
      return result;
    }

    // Resolve EXE subslots (only apples to EXE_NIC_NEAREST)
    if (wc.exe.exeSubSlots.size() == 0) {
      // Subslot won't be used, so just assign 0
      wc.exe.exeSubSlots = {0};
      result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      wc.exe.exeSubSlots.clear();
      return result;
    } else if (wc.exe.exeSubSlots.size() > 1) {
      // Loop over user provided slots
      std::vector<int> exeSubSlots;
      exeSubSlots.swap(wc.exe.exeSubSlots);
      for (auto x : exeSubSlots) {
        wc.exe.exeSubSlots = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeSubSlots.swap(exeSubSlots);
      return result;
    } else if (wc.exe.exeSubSlots[0] == -1) {
      // Wildcard - Loop over all possible slots, based on DST memory type
      std::vector<int> dstNicIndices;
      if (IsCpuMemType(wc.mem[1][0].memType)) {
        GetClosestNicsToCpu(dstNicIndices, wc.mem[1][0].memIndices[0], wc.mem[1][0].memRanks[0]);
      } else {
        GetClosestNicsToGpu(dstNicIndices, wc.mem[1][0].memIndices[0], wc.mem[1][0].memRanks[0]);
      }
      for (auto x : dstNicIndices) {
        wc.exe.exeSubSlots = {x};
        result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers);
      }
      wc.exe.exeSubSlots = {-1};
      return result;
5005
    }
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026

    // Only reach here when each candidate has been narrowed down to 1 option
    // Create Transfer and add to list
    Transfer t;
    t.numBytes    = numBytes;
    t.numSubExecs = numSubExecs;

    for (int iSrc = 0; iSrc < wc.mem[0].size(); iSrc++)
      t.srcs.push_back({wc.mem[0][iSrc].memType, wc.mem[0][iSrc].memIndices[0], wc.mem[0][iSrc].memRanks[0]});
    for (int iDst = 0; iDst < wc.mem[1].size(); iDst++)
      t.dsts.push_back({wc.mem[1][iDst].memType, wc.mem[1][iDst].memIndices[0], wc.mem[1][iDst].memRanks[0]});
    t.exeDevice.exeType  = wc.exe.exeType;
    t.exeDevice.exeIndex = wc.exe.exeIndices[0];
    t.exeDevice.exeRank  = wc.exe.exeRanks[0];
    t.exeDevice.exeSlot  = wc.exe.exeSlots[0];
    t.exeSubIndex        = wc.exe.exeSubIndices[0];
    t.exeSubSlot         = wc.exe.exeSubSlots[0];

    transfers.push_back(t);

    return false;
5027
5028
  }

5029
5030
  ErrResult ParseTransfers(std::string            line,
                           std::vector<Transfer>& transfers)
5031
  {
5032
5033
5034
    // Replace any round brackets or '->' with spaces,
    for (int i = 1; line[i]; i++)
      if (line[i] == '(' || line[i] == ')' || line[i] == '-'  || line[i] == ':' || line[i] == '>' ) line[i] = ' ';
5035

5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
    transfers.clear();

    // Read in number of transfers descriptions
    // NOTE: Transfers descriptions with wildcards get expanded to multiple transfers
    int numTransfers = 0;
    std::istringstream iss(line);
    iss >> numTransfers;
    if (iss.fail()) return ERR_NONE;

    // If numTransfers < 0, read 5-tuple (srcMem, exeMem, dstMem, #CUs, #Bytes)
    // otherwise read triples (srcMem, exeMem, dstMem)
    bool const advancedMode = (numTransfers < 0);
    numTransfers = abs(numTransfers);

    int numSubExecs;
    std::string srcStr, exeStr, dstStr, numBytesToken;

    if (!advancedMode) {
      iss >> numSubExecs;
      if (numSubExecs < 0 || iss.fail()) {
        return {ERR_FATAL,
                "Parsing error: Number of blocks to use (%d) must be non-negative", numSubExecs};
      }
5059
    }
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099

    for (int i = 0; i < numTransfers; i++) {
      size_t numBytes;
      if (!advancedMode) {
        iss >> srcStr >> exeStr >> dstStr;
        if (iss.fail()) {
          return {ERR_FATAL,
            "Parsing error: Unable to read valid Transfer %d (SRC EXE DST) triplet", i+1};
        }
        numBytes = 0;
      } else {
        iss >> srcStr >> exeStr >> dstStr >> numSubExecs >> numBytesToken;
        if (iss.fail()) {
          return {ERR_FATAL,
            "Parsing error: Unable to read valid Transfer %d (SRC EXE DST $CU #Bytes) tuple", i+1};
        }
        if (sscanf(numBytesToken.c_str(), "%lu", &numBytes) != 1) {
          return {ERR_FATAL,
            "Parsing error: Unable to read valid Transfer %d (SRC EXE DST #CU #Bytes) tuple", i+1};
        }

        char units = numBytesToken.back();
        switch (toupper(units)) {
        case 'G': numBytes *= 1024;
        case 'M': numBytes *= 1024;
        case 'K': numBytes *= 1024;
        }
      }

      WildcardTransfer wct;
      ERR_CHECK(ParseMemType(srcStr, wct.mem[0]));
      ERR_CHECK(ParseMemType(dstStr, wct.mem[1]));
      ERR_CHECK(ParseExeType(exeStr, wct.exe));

      // Perform wildcard expansion
      int numRanks = GetNumRanks();
      for (int localRankIndex = 0; localRankIndex < numRanks; localRankIndex++) {
        bool localRankModified = RecursiveWildcardTransferExpansion(wct, localRankIndex, numBytes, numSubExecs, transfers);
        if (!localRankModified) break;
      }
5100
    }
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115

    return ERR_NONE;
  }

  // System related
  //========================================================================================
  System::System() :
    rank(0), numRanks(1), commMode(COMM_NONE)
  {
    verbose = getenv("TB_VERBOSE") ? atoi(getenv("TB_VERBOSE")) : 0;

    if (getenv("TB_PAUSE")) {
      printf("Pausing for debug attachment\n");
      volatile bool pause = true;
      while (pause);
5116
    }
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131

    // Priority 1: Socket communicator
    SetupSocketCommunicator();

    // Priority 2: MPI communicator
    if (commMode == COMM_NONE) {
      SetupMpiCommunicator();
    }

    if (verbose && commMode == COMM_NONE) {
      printf("[INFO] Running in single node mode\n");
    }

    // Collect topology and distribute across all ranks
    CollectTopology();
5132
5133
  }

5134
  System::~System()
5135
  {
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
#ifdef MPI_COMM_ENABLED
    if (commMode == COMM_MPI) {
      if (mpiInit == true)  {
        MPI_Finalize();
      }
    }
#endif
    if (commMode == COMM_SOCKET) {
      // Close all sockets
      for (auto& sock : sockets) {
        if (sock != -1) {
          close(sock);
          sock = -1;
        }
      }
5151

5152
5153
5154
5155
5156
5157
      if (listenSocket != -1) {
        close(listenSocket);
        listenSocket = -1;
      }
    }
  }
5158

5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
  void System::SetupSocketCommunicator()
  {
    char* rankStr       = getenv("TB_RANK");
    char* numRanksStr   = getenv("TB_NUM_RANKS");
    char* masterAddrStr = getenv("TB_MASTER_ADDR");
    char* masterPortStr = getenv("TB_MASTER_PORT");

    // Socket communicator requires rank / numRanks / masterAddr
    if (!rankStr || !numRanksStr || !masterAddrStr) {
      if (verbose) {
        printf("[INFO] SocketCommunicator skipped due to missing TB_RANK | TB_NUM_RANKS | TB_MASTER_ADDR\n");
      }
      return;
    }
5173

5174
5175
5176
5177
    rank       = atoi(rankStr);
    numRanks   = atoi(numRanksStr);
    masterAddr = masterAddrStr;
    masterPort = masterPortStr ? atoi(masterPortStr) : 29500;
5178

5179
5180
5181
    if (rank < 0 || rank >= numRanks) {
      printf("[ERROR] Invalid rank index.  Must be between 0 and %d (not %d)\n", numRanks - 1, rank);
      exit(1);
5182
    }
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302

    sockets.resize(numRanks, -1);

    // Rank 0 acts as server for others to connect to
    int opt = 1;
    if (rank == 0) {
      // Create listening socket
      listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      if (listenSocket == -1) {
        printf("[ERROR] Unable to create listener socket\n");
        exit(1);
      }

      // Allow address reuse
      setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

      // Bind to port
      sockaddr_in serverAddr;
      memset(&serverAddr, 0, sizeof(serverAddr));
      serverAddr.sin_family      = AF_INET;
      serverAddr.sin_addr.s_addr = INADDR_ANY;
      serverAddr.sin_port        = htons(masterPort);

      if (bind(listenSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
        printf("[ERROR] Failed to bind listen socket\n");
        exit(1);
      }

      if (listen(listenSocket, numRanks) == -1) {
        printf("[ERROR] Failed to listen on socket\n");
        exit(1);
      }
      // Accept connections from other ranks
      printf("Waiting for connections from %d other ranks [listening on TB_MASTER_ADDR=%s TB_MASTER_PORT=%d]\n",
             numRanks-1, masterAddr.c_str(), masterPort);

      for (int i = 1; i < numRanks; i++) {
        sockaddr_in clientAddr;
        socklen_t clientAddrLen = sizeof(clientAddr);

        auto clientSocket = accept(listenSocket, (sockaddr*)&clientAddr, &clientAddrLen);
        if (clientSocket == -1) {
          printf("[ERROR] Failed to accept connection from rank %d\n", i);
          exit(1);
        }

        // Receive rank ID from client
        int clientRank;
        recv(clientSocket, (char*)&clientRank, sizeof(clientRank), 0);

        if (clientRank < 0 || clientRank >= numRanks) {
          close(clientSocket);
          printf("[ERROR] Invalid rank received: %d\n", clientRank);
          exit(1);
        }
        if (verbose) {
          printf("[INFO] Rank 0 accepted connection from rank %d\n", clientRank);
        }
        sockets[clientRank] = clientSocket;
      }
    } else {
      // All other ranks connect to rank 0
      int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      if (sock == -1) {
        printf("[ERROR] Failed to create socket\n");
        exit(1);
      }

      sockaddr_in serverAddr;
      memset(&serverAddr, 0, sizeof(serverAddr));
      serverAddr.sin_family = AF_INET;
      serverAddr.sin_port = htons(masterPort);
      if (inet_pton(AF_INET, masterAddr.c_str(), &serverAddr.sin_addr) <= 0) {
        printf("[ERROR] Invalid master address: %s\n", masterAddr.c_str());
        exit(1);
      }

      // Retry connection with backoff
      if (verbose)
        printf("[INFO] Rank %d attempting to connect to %s:%d\n", rank, masterAddrStr, masterPort);
      int maxRetries = 50;
      for (int retry = 0; retry < maxRetries; retry++) {
        if (connect(sock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == 0) {
          break;
        }
        if (retry == maxRetries - 1) {
          printf("[ERROR] Failed to connect to master after %d retries\n", maxRetries);
        }
        sleep(1);
      }

      // Send local rank to the server
      send(sock, (char*)&rank, sizeof(rank), 0);
      sockets[0] = sock;
    }

    commMode = COMM_SOCKET;
  };

  void System::SetupMpiCommunicator()
  {
#ifdef MPI_COMM_ENABLED
    int flag;
    MPI_Initialized(&flag);
    if (!flag) {
      MPI_Init(NULL, NULL);
      mpiInit = true;
    }

    comm = MPI_COMM_WORLD;
    MPI_Comm_rank(comm, &rank);
    MPI_Comm_size(comm, &numRanks);
    if (numRanks > 1) {
      if (verbose) {
        printf("[INFO] Enabling MPI communicator (%d ranks found)\n", numRanks);
      }
      commMode = COMM_MPI;
    } else if (mpiInit) {
      // Drop out of MPI use for single node
      MPI_Finalize();
5303
5304
5305
5306
    }
#endif
  }

5307
  void System::Barrier()
5308
  {
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
#ifdef MPI_COMM_ENABLED
    if (commMode == COMM_MPI) {
      MPI_Barrier(comm);
      return;
    }
#endif
    if (commMode == COMM_SOCKET) {
      char dummy = 0;

      // Simple barrier using rank 0 to coordinate
      if (rank == 0) {
        // Wait for notification from all ranks
        for (int peerRank = 1; peerRank < numRanks; peerRank++)
          RecvData(peerRank, 1, &dummy);

        // Release all ranks
        for (int peerRank = 1; peerRank < numRanks; peerRank++)
          SendData(peerRank, 1, &dummy);
      } else {
        // Send notification to root
        SendData(0, 1, &dummy);

        // Wait for release from root
        RecvData(0, 1, &dummy);
5333
5334
      }
    }
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
  }

  void System::SendData(int dstRank, size_t const numBytes, const void* sendData) const
  {
#ifdef MPI_COMM_ENABLED
    if (commMode == COMM_MPI) {
      MPI_Send(sendData, numBytes, MPI_BYTE, dstRank, 1234, comm);
      return;
    }
#endif
    if (commMode == COMM_SOCKET) {
      if (rank != 0 && dstRank != 0) {
        printf("[ERROR] Socket communicator is limited to sending from/to rank 0\n");
        exit(1);
      }
      auto sock = sockets[dstRank];

      // Send data
      size_t totalSent = 0;
      while (totalSent < numBytes) {
        auto sent = send(sock, (char*)sendData + totalSent, numBytes - totalSent, 0);
        if (sent == -1) {
          printf("[ERROR] Send failed (rank %d to rank %d)\n", rank, dstRank);
          exit(1);
        }
        totalSent += sent;
      }
    }
  }

  void System::RecvData(int srcRank, size_t const numBytes, void* recvData) const
  {
#ifdef MPI_COMM_ENABLED
    if (commMode == COMM_MPI) {
      MPI_Status status;
      MPI_Recv(recvData, numBytes, MPI_BYTE, srcRank, 1234, comm, &status);
      return;
    }
5373
#endif
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
    if (commMode == COMM_SOCKET) {
      if (rank != 0 && srcRank != 0) {
        printf("[ERROR] Socket communicator is limited to receiving from/at rank 0\n");
        exit(1);
      }

      auto sock = sockets[srcRank];
      size_t totalRecv = 0;
      while (totalRecv < numBytes) {
        auto recvd = recv(sock, (char*)recvData + totalRecv, numBytes - totalRecv, 0);
        if (recvd == -1 || recvd == 0) {
          printf("[ERROR] Recv failed (rank %d from rank %d)\n", rank, srcRank);
          perror("recv");
          exit(1);
        }
        totalRecv += recvd;
      }
    }
5392
5393
  }

5394
  void System::Broadcast(int root, size_t const numBytes, void* data) const
gilbertlee-amd's avatar
gilbertlee-amd committed
5395
  {
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
    if (numBytes == 0) return;

#ifdef MPI_COMM_ENABLED
    if (commMode == COMM_MPI) {
      int err = MPI_Bcast(data, numBytes, MPI_CHAR, root, comm);
      if (err != MPI_SUCCESS) {
        printf("[ERROR] MPI_Bcast failed with error code %d\n", err);
      }
      return;
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
5406
#endif
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
    if (commMode == COMM_SOCKET) {
      // Relay through rank 0 first
      if (root != 0) {
        if (rank == root) {
          SendData(0, numBytes, data);
        } else if (rank == 0) {
          RecvData(root, numBytes, data);
        }
      }
      if (rank == 0) {
        for (int peer = 1; peer < numRanks; peer++) {
          SendData(peer, numBytes, data);
        }
      } else {
        RecvData(0, numBytes, data);
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
5424
5425
  }

5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
  bool System::Any(bool const flag) const
  {
    bool result = false;
    for (int i = 0; i < numRanks; i++) {
      bool flagToSend = flag;
      Broadcast(i, sizeof(flagToSend), &flagToSend);
      result |= flagToSend;
      if (result) break;
    }
    return result;
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
5437

5438
  std::string System::GetCpuName() const
gilbertlee-amd's avatar
gilbertlee-amd committed
5439
  {
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
    std::ifstream cpuInfo("/proc/cpuinfo");
    std::string line;

    if (cpuInfo.is_open()) {
      while (std::getline(cpuInfo, line)) {
        if (line.find("model name") != std::string::npos) {
          size_t colonIdx = line.find(":");
          if (colonIdx != std::string::npos) {
            return line.substr(colonIdx + 2);
          }
        }
      }
    }
    return "Unknown CPU";
  }

  void System::GetRankTopology(RankTopology& topo)
  {
    // Clear topology structure first
    topo.numExecutors.clear();
    topo.numExecutorSubIndices.clear();
    topo.numSubExecutors.clear();
    topo.closestCpuNumaToGpu.clear();
    topo.closestCpuNumaToNic.clear();
    topo.closestNicsToGpu.clear();

    memset(topo.hostname, 0, sizeof(topo.hostname));
    gethostname(topo.hostname, 32);
    char* firstDotPtr = std::strchr(topo.hostname, '.');
    if (firstDotPtr) *firstDotPtr = 0;

    // NOTE: Placeholder values
    strcpy(topo.ppodId, "N/A");
    topo.vpodId = -1;

    // CPU Executor
    int numCpus = numa_num_configured_nodes();
    topo.numExecutors[EXE_CPU] = numCpus;

    std::string cpuName = GetCpuName();

    for (int exeIndex = 0; exeIndex < numCpus; exeIndex++) {
      topo.numExecutorSubIndices[{EXE_CPU, exeIndex}] = 0;
      topo.executorName[{EXE_CPU, exeIndex}] = cpuName;
    }

    for (int cpuCore = 0; cpuCore < numa_num_configured_cpus(); cpuCore++) {
      topo.numSubExecutors[{EXE_CPU, numa_node_of_cpu(cpuCore)}]++;
    }

    if (verbose) {
      for (int exeIndex = 0; exeIndex < numCpus; exeIndex++) {
        printf("[INFO] Rank %03d: CPU [%02d/%02d] %03d cores (%s)\n", rank, exeIndex, numCpus,
               topo.numSubExecutors[{EXE_CPU, exeIndex}],
               topo.executorName[{EXE_CPU, exeIndex}].c_str());
      }
    }

    // GPU Executor
    int numGpus = 0;
    hipError_t status = hipGetDeviceCount(&numGpus);
    if (status != hipSuccess) numGpus = 0;
    topo.numExecutors[EXE_GPU_GFX] = numGpus;
    topo.numExecutors[EXE_GPU_DMA] = numGpus;

    for (int exeIndex = 0; exeIndex < numGpus; exeIndex++) {
      int numDeviceCUs  = 0;
      int numXccs       = 0;
      int numDmaEngines = 0;
      int closestNuma   = -1;

      if (hipDeviceGetAttribute(&numDeviceCUs, hipDeviceAttributeMultiprocessorCount, exeIndex) != hipSuccess) {
        numDeviceCUs = 0;
      }

      std::string gpuName = "Unknown GPU";
      hipDeviceProp_t props;
      if (hipGetDeviceProperties(&props, exeIndex) == hipSuccess) {
        gpuName = props.name;
      }
      topo.executorName[{EXE_GPU_GFX, exeIndex}] = gpuName;
      topo.executorName[{EXE_GPU_DMA, exeIndex}] = gpuName;

#if !defined(__NVCC__)
      hsa_agent_t gpuAgent = gpuAgents[exeIndex];
      if (hsa_agent_get_info(gpuAgent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_NUM_XCC, &numXccs) != HSA_STATUS_SUCCESS)
        numXccs = 1;

      int numEnginesA, numEnginesB;
      if (hsa_agent_get_info(gpuAgent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_NUM_SDMA_ENG, &numEnginesA)
          == HSA_STATUS_SUCCESS)
        numDmaEngines += numEnginesA;
      if (hsa_agent_get_info(gpuAgent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_NUM_SDMA_XGMI_ENG, &numEnginesB)
          == HSA_STATUS_SUCCESS)
        numDmaEngines += numEnginesB;

      hsa_agent_t closestCpuAgent;
      if (hsa_agent_get_info(gpuAgent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_NEAREST_CPU, &closestCpuAgent)
          == HSA_STATUS_SUCCESS) {
        for (int cpuIndex = 0; cpuIndex < numCpus; cpuIndex++) {
          hsa_agent_t cpuAgent = cpuAgents[cpuIndex];
          if (cpuAgent.handle == closestCpuAgent.handle) {
            closestNuma = cpuIndex;
            break;
          }
        }
      }
#endif
      topo.numExecutorSubIndices[{EXE_GPU_GFX, exeIndex}] = numXccs;
      topo.numExecutorSubIndices[{EXE_GPU_DMA, exeIndex}] = numDmaEngines;
      topo.numSubExecutors[{EXE_GPU_GFX, exeIndex}] = numDeviceCUs;
      topo.numSubExecutors[{EXE_GPU_DMA, exeIndex}] = 1;
      topo.closestCpuNumaToGpu[exeIndex] = closestNuma;
      topo.closestNicsToGpu[exeIndex] = {};
    }

    // NIC Executor
    int numNics = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
5558
#ifdef NIC_EXEC_ENABLED
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
    numNics = GetIbvDeviceList().size();
    for (int exeIndex = 0; exeIndex < numNics; exeIndex++) {
      topo.closestCpuNumaToNic[exeIndex] = GetIbvDeviceList()[exeIndex].numaNode;
      topo.executorName[{EXE_NIC, exeIndex}] = GetIbvDeviceList()[exeIndex].name;
      topo.nicIsActive[exeIndex] = GetIbvDeviceList()[exeIndex].hasActivePort;
      if (verbose) {
        printf("[INFO] Rank %03d: NIC [%02d/%02d] on CPU NUMA %d\n", rank, exeIndex, numNics, topo.closestCpuNumaToNic[exeIndex]);
      }
    }
#endif
    topo.numExecutors[EXE_NIC] = topo.numExecutors[EXE_NIC_NEAREST] = numNics;
gilbertlee-amd's avatar
gilbertlee-amd committed
5570

5571
5572
5573
5574
    for (int nicIndex = 0; nicIndex < numNics; nicIndex++) {
      topo.numSubExecutors[{EXE_NIC, nicIndex}] = 0;
      topo.numExecutorSubIndices[{EXE_NIC, nicIndex}] = 0;
      std::string gpuName = "Unknown GPU";
gilbertlee-amd's avatar
gilbertlee-amd committed
5575

5576
5577
5578
5579
5580
    }
    for (int gpuIndex = 0; gpuIndex < numGpus; gpuIndex++) {
      topo.numSubExecutors[{EXE_NIC_NEAREST, gpuIndex}] = 0;
      topo.numExecutorSubIndices[{EXE_NIC_NEAREST, gpuIndex}] = 0;
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
5581

5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
    // Figure out closest NICs to GPUs
#ifdef NIC_EXEC_ENABLED

    // Build up list of NIC bus addresses
    std::vector<std::string> ibvAddressList;
    auto const& ibvDeviceList = GetIbvDeviceList();
    for (auto const& ibvDevice : ibvDeviceList)
      ibvAddressList.push_back(ibvDevice.hasActivePort ? ibvDevice.busId : "");

    // Track how many times a device has been assigned as "closest"
    // This allows distributed work across devices using multiple ports (sharing the same busID)
    // NOTE: This isn't necessarily optimal, but likely to work in most cases involving multi-port
    // Counter example:
    //
    //  G0 prefers (N0,N1), picks N0
    //  G1 prefers (N1,N2), picks N1
    //  G2 prefers N0,      picks N0
    //
    //  instead of G0->N1, G1->N2, G2->N0

    std::vector<int> assignedCount(ibvDeviceList.size(), 0);

    // Loop over each GPU to find the closest NIC(s) based on PCIe address
    for (int gpuIndex = 0; gpuIndex < numGpus; gpuIndex++) {
      // Collect PCIe address for the GPU
      char hipPciBusId[64];
      hipError_t err = hipDeviceGetPCIBusId(hipPciBusId, sizeof(hipPciBusId), gpuIndex);
      if (err != hipSuccess) {
gilbertlee-amd's avatar
gilbertlee-amd committed
5610
#ifdef VERBS_DEBUG
5611
        printf("Failed to get PCI Bus ID for HIP device %d: %s\n", gpuIndex, hipGetErrorString(err));
gilbertlee-amd's avatar
gilbertlee-amd committed
5612
#endif
5613
5614
        continue;
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
5615

5616
5617
      // Find closest NICs
      std::set<int> closestNicIdxs = GetNearestDevicesInTree(hipPciBusId, ibvAddressList);
gilbertlee-amd's avatar
gilbertlee-amd committed
5618

5619
5620
5621
5622
5623
5624
      // Pick the least-used NIC to assign as closest
      int closestIdx = -1;
      for (auto idx : closestNicIdxs) {
        if (closestIdx == -1 || assignedCount[idx] < assignedCount[closestIdx])
          closestIdx = idx;
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
5625

5626
5627
5628
      // The following will only use distance between bus IDs
      // to determine the closest NIC to GPU if the PCIe tree approach fails
      if (closestIdx < 0) {
gilbertlee-amd's avatar
gilbertlee-amd committed
5629
#ifdef VERBS_DEBUG
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
        printf("[WARN] Falling back to PCIe bus ID distance to determine proximity\n");
#endif
        int minDistance = std::numeric_limits<int>::max();
        for (int nicIndex = 0; nicIndex < numNics; nicIndex++) {
          if (ibvDeviceList[nicIndex].busId != "") {
            int distance = GetBusIdDistance(hipPciBusId, ibvDeviceList[nicIndex].busId);
            if (distance < minDistance && distance >= 0) {
              minDistance = distance;
              closestIdx = nicIndex;
            }
          }
        }
      }
      if (closestIdx != -1) {
        topo.closestNicsToGpu[gpuIndex].push_back(closestIdx);
        assignedCount[closestIdx]++;
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
5648
5649
#endif

5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
    if (verbose) {
      for (int exeIndex = 0; exeIndex < numGpus; exeIndex++) {
        printf("[INFO] Rank %03d: GPU [%02d/%02d] %d XCCs %03d CUs on CPU NUMA %d Closests NICs:", rank, exeIndex, numGpus,
               topo.numExecutorSubIndices[{EXE_GPU_GFX, exeIndex}],
               topo.numSubExecutors[{EXE_GPU_GFX, exeIndex}],
               topo.closestCpuNumaToGpu[exeIndex]);
        if (topo.closestNicsToGpu[exeIndex].size() == 0) {
          printf(" none");
        } else {
          for (auto nicIndex : topo.closestNicsToGpu[exeIndex]) {
            printf(" %d", nicIndex);
          }
          printf("\n");
        }
      }
    }
  }

  template <typename KeyType, typename ValType>
  void System::SendMap(int peerRank, std::map<KeyType, std::vector<ValType>> const& mapToSend) const
  {
    size_t mapSize = mapToSend.size();
    SendData(peerRank, sizeof(mapSize), &mapSize);
    for (auto const& p : mapToSend) {
      SendData(peerRank, sizeof(p.first), &p.first);
      size_t vectorSize = p.second.size();
      SendData(peerRank, sizeof(vectorSize), &vectorSize);
      for (auto const& v : p.second) {
        SendData(peerRank, sizeof(v), &v);
      }
    }
    fflush(stdout);
  }

  template <typename KeyType, typename ValType>
  void System::SendMap(int peerRank, std::map<KeyType, ValType> const& mapToSend) const
  {
    size_t mapSize = mapToSend.size();
    SendData(peerRank, sizeof(mapSize), &mapSize);
    for (auto const p : mapToSend) {
      SendData(peerRank, sizeof(p), &p);
    }
  }

  template <typename KeyType>
  void System::SendMap(int peerRank, std::map<KeyType, std::string> const& mapToSend) const
  {
    size_t mapSize = mapToSend.size();
    SendData(peerRank, sizeof(mapSize), &mapSize);
    for (auto const p : mapToSend) {
      size_t strlen = p.second.size();
      SendData(peerRank, sizeof(p.first), &p.first);
      SendData(peerRank, sizeof(strlen), &strlen);
      if (strlen) SendData(peerRank, strlen, p.second.data());
    }
  }

  template <typename KeyType, typename ValType>
  void System::RecvMap(int peerRank, std::map<KeyType, std::vector<ValType>>& mapToRecv) const
  {
    mapToRecv.clear();
    size_t mapSize;
    RecvData(peerRank, sizeof(mapSize), &mapSize);
    for (size_t i = 0; i < mapSize; i++) {
      KeyType key;
      size_t vectorSize;
      std::vector<ValType> values;
      RecvData(peerRank, sizeof(key), &key);
      RecvData(peerRank, sizeof(vectorSize), &vectorSize);
      if (vectorSize) {
        values.resize(vectorSize);
        for (size_t j = 0; j < vectorSize; j++) {
          RecvData(peerRank, sizeof(ValType), &values[j]);
        }
      }
      mapToRecv[key] = values;
    }
  }

  template <typename KeyType>
  void System::RecvMap(int peerRank, std::map<KeyType, std::string>& mapToRecv) const
  {
    mapToRecv.clear();
    size_t mapSize;
    RecvData(peerRank, sizeof(mapSize), &mapSize);
    for (size_t i = 0; i < mapSize; i++) {
      KeyType key;
      size_t strlen;
      std::string value;
      RecvData(peerRank, sizeof(key), &key);
      RecvData(peerRank, sizeof(size_t), &strlen);
      if (strlen) {
        value.resize(strlen);
        RecvData(peerRank, strlen, value.data());
      }
      mapToRecv[key] = value;
    }
  }

  template <typename KeyType, typename ValType>
  void System::RecvMap(int peerRank, std::map<KeyType, ValType>& mapToRecv) const
  {
    mapToRecv.clear();
    size_t mapSize;
    RecvData(peerRank, sizeof(mapSize), &mapSize);
    for (size_t i = 0; i < mapSize; i++) {
      std::pair<KeyType, ValType> p;
      RecvData(peerRank, sizeof(p), &p);
      mapToRecv[p.first] = p.second;
    }
  }

  void System::SendRankTopo(int peerRank, RankTopology const& topo) const
  {
    SendData(peerRank, sizeof(topo.hostname), topo.hostname);
    SendData(peerRank, sizeof(topo.ppodId), &topo.ppodId);
    SendData(peerRank, sizeof(topo.vpodId), &topo.vpodId);
    SendMap(peerRank, topo.numExecutors);
    SendMap(peerRank, topo.numExecutorSubIndices);
    SendMap(peerRank, topo.numSubExecutors);
    SendMap(peerRank, topo.closestCpuNumaToGpu);
    SendMap(peerRank, topo.closestCpuNumaToNic);
    SendMap(peerRank, topo.nicIsActive);
    SendMap(peerRank, topo.closestNicsToGpu);
    SendMap(peerRank, topo.executorName);
  };

  void System::RecvRankTopo(int peerRank, RankTopology& topo) const
  {
    RecvData(peerRank, sizeof(topo.hostname), topo.hostname);
    RecvData(peerRank, sizeof(topo.ppodId), &topo.ppodId);
    RecvData(peerRank, sizeof(topo.vpodId), &topo.vpodId);
    RecvMap(peerRank, topo.numExecutors);
    RecvMap(peerRank, topo.numExecutorSubIndices);
    RecvMap(peerRank, topo.numSubExecutors);
    RecvMap(peerRank, topo.closestCpuNumaToGpu);
    RecvMap(peerRank, topo.closestCpuNumaToNic);
    RecvMap(peerRank, topo.nicIsActive);
    RecvMap(peerRank, topo.closestNicsToGpu);
    RecvMap(peerRank, topo.executorName);
  }

  template <typename T>
  void System::BroadcastVector(int root, vector<T>& data) const
  {
    // This assumes T is trivially copyable
    static_assert(std::is_trivially_copyable<T>::value);

    size_t len = data.size();
    Broadcast(root, sizeof(len), &len);
    data.resize(len);
    if (len) {
      Broadcast(root, sizeof(T) * len, data.data());
    }
  }

  void System::BroadcastString(int root, std::string& string) const
  {
    size_t len = string.size();
    Broadcast(root, sizeof(len), &len);
    string.resize(len);
    if (len) {
      Broadcast(root, len, string.data());
    }
  }

  void System::BroadcastExeResult(int root, ExeResult& exeResult) const
  {
    #define BROADCAST(X)  Broadcast(root, sizeof(X), &X)
    BROADCAST(exeResult.numBytes);
    BROADCAST(exeResult.avgDurationMsec);
    BROADCAST(exeResult.avgBandwidthGbPerSec);
    BROADCAST(exeResult.sumBandwidthGbPerSec);
    BroadcastVector(root, exeResult.transferIdx);
    #undef BROADCAST
  }

  void System::BroadcastTfrResult(int root, TransferResult& tfrResult) const
  {
    #define BROADCAST(X)  Broadcast(root, sizeof(X), &X)
    BROADCAST(tfrResult.numBytes);
    BROADCAST(tfrResult.avgDurationMsec);
    BROADCAST(tfrResult.avgBandwidthGbPerSec);
    BroadcastVector(root, tfrResult.perIterMsec);
    BROADCAST(tfrResult.exeDevice);
    BROADCAST(tfrResult.exeDstDevice);

    // Per-Iteration CU results need to be handled in a custom manner
    size_t perIterCuSize = tfrResult.perIterCUs.size();
    BROADCAST(perIterCuSize);

    if (perIterCuSize > 0) {
      tfrResult.perIterCUs.resize(perIterCuSize);
      for (size_t i = 0; i < perIterCuSize; i++) {
        size_t setSize;

        //vector<set<pair<int,int>>> perIterCUs;      ///< GFX-Executor only. XCC:CU used per iteration

        if (GetRank() == root) {
          setSize = tfrResult.perIterCUs[i].size();
          BROADCAST(setSize);
          if (setSize > 0) {
            for (pair<int,int> const& x : tfrResult.perIterCUs[i]) {
              pair<int, int> p = x;
              BROADCAST(p);
gilbertlee-amd's avatar
gilbertlee-amd committed
5855
5856
            }
          }
5857
5858
5859
5860
5861
5862
5863
5864
        } else {
          BROADCAST(setSize);
          tfrResult.perIterCUs[i].clear();
          if (setSize > 0) {
            pair<int, int> p;
            BROADCAST(p);
            tfrResult.perIterCUs[i].insert(p);
          }
gilbertlee-amd's avatar
gilbertlee-amd committed
5865
5866
        }
      }
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
    } else {
      tfrResult.perIterCUs.clear();
    }
    #undef BROADCAST
  };

  void System::AllGatherErrors(vector<ErrResult>& errResults) const
  {
    if (commMode == COMM_NONE) return;

    vector<ErrResult> tempResults = std::move(errResults);

    for (int i = 0; i < numRanks; i++) {
      size_t errListSize = tempResults.size();
      Broadcast(i, sizeof(errListSize), &errListSize);
      for (size_t j = 0; j < errListSize; j++) {
        ErrResult errResult;
        if (rank == i) errResult = tempResults[j];
        Broadcast(i, sizeof(errResult.errType), &errResult.errType);
        BroadcastString(i, errResult.errMsg);
        errResult.errMsg += " (Rank " + std::to_string(i) + ")";
        errResults.push_back(errResult);
      }
    }
  }

#if !defined(__NVCC__)
  // Get the hsa_agent_t associated with a ExeDevice
  ErrResult System::GetHsaAgent(ExeDevice const& exeDevice, hsa_agent_t& agent) const
  {
    int numCpus = static_cast<int>(cpuAgents.size());
    int numGpus = static_cast<int>(gpuAgents.size());
    int exeIndex = exeDevice.exeIndex;

    switch (exeDevice.exeType) {
    case EXE_CPU:
      if (exeIndex < 0 || exeIndex >= numCpus)
        return {ERR_FATAL, "CPU index must be between 0 and %d inclusively", numCpus - 1};
      agent = cpuAgents[exeDevice.exeIndex];
      break;
    case EXE_GPU_GFX: case EXE_GPU_DMA:
      if (exeIndex < 0 || exeIndex >= numGpus)
        return {ERR_FATAL, "GPU index must be between 0 and %d inclusively", numGpus - 1};
      agent = gpuAgents[exeIndex];
      break;
    default:
      return {ERR_FATAL,
              "Attempting to get HSA agent of unknown or unsupported executor type (%d)",
              exeDevice.exeType};
    }
    return ERR_NONE;
  }

  // Get the hsa_agent_t associated with a MemDevice
  ErrResult System::GetHsaAgent(MemDevice const& memDevice, hsa_agent_t& agent) const
  {
    if (memDevice.memType == MEM_CPU_CLOSEST)
      return GetHsaAgent({EXE_CPU, GetClosestCpuNumaToGpu(memDevice.memIndex)}, agent);
    if (IsCpuMemType(memDevice.memType)) return GetHsaAgent({EXE_CPU, memDevice.memIndex}, agent);
    if (IsGpuMemType(memDevice.memType)) return GetHsaAgent({EXE_GPU_GFX, memDevice.memIndex}, agent);
    return {ERR_FATAL,
            "Unable to get HSA agent for memDevice (%d,%d)",
            memDevice.memType, memDevice.memIndex};
  }
#endif

  void System::CollectTopology()
  {
    // Cache the HSA agents for each device
#if !defined(__NVCC__)
    {
      hsa_amd_pointer_info_t info;
      info.size = sizeof(info);

      ErrResult err;
      int32_t* tempBuffer;

      // Index CPU agents
      cpuAgents.clear();
      int numCpus = numa_num_configured_nodes();
      for (int i = 0; i < numCpus; i++) {
        AllocateMemory({MEM_CPU, i}, 1024, (void**)&tempBuffer);
        hsa_amd_pointer_info(tempBuffer, &info, NULL, NULL, NULL);
        cpuAgents.push_back(info.agentOwner);
        DeallocateMemory(MEM_CPU, tempBuffer, 1024);
      }

      // Index GPU agents
      int numGpus = 0;
      hipError_t status = hipGetDeviceCount(&numGpus);
      if (status != hipSuccess) numGpus = 0;
      gpuAgents.clear();
      for (int i = 0; i < numGpus; i++) {
        AllocateMemory({MEM_GPU, i}, 1024, (void**)&tempBuffer);
        hsa_amd_pointer_info(tempBuffer, &info, NULL, NULL, NULL);
        gpuAgents.push_back(info.agentOwner);
        DeallocateMemory(MEM_GPU, tempBuffer, 1024);
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
5965
5966
    }
#endif
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185

    // Collect the topology of the local node
    RankTopology localTopo;
    GetRankTopology(localTopo);

    // Distribute amongst all ranks
    rankInfo.resize(numRanks);

    if (rank == 0) {
      // Receive topology info from each rank
      rankInfo[0] = localTopo;
      for (int peerRank = 1; peerRank < numRanks; peerRank++) {
        if (verbose) {
          printf("[INFO] Rank 0 receives topology from Rank %d\n", peerRank);
        }
        RecvRankTopo(peerRank, rankInfo[peerRank]);
      }

      // Send out full set of info to each rank
      for (int peerRank = 1; peerRank < numRanks; peerRank++) {
        for (int i = 0; i < numRanks; i++) {
          if (verbose) {
            printf("[INFO] Rank 0 sends topology %d to Rank %d\n", i, peerRank);
          }
          SendRankTopo(peerRank, rankInfo[i]);
        }
      }
    } else {
      // Send local topology info back to root
      if (verbose) {
        printf("[INF0] Rank %d sends topology from Rank 0\n", rank);
      }
      SendRankTopo(0, localTopo);

      for (int i = 0; i < numRanks; i++) {
        RecvRankTopo(0, rankInfo[i]);
        if (verbose) {
          printf("[INF0] Rank %d receives topology %d from Rank 0\n", rank, i);
        }
      }
    }
  }

  int System::GetNumExecutors(ExeType exeType, int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (rankInfo[targetRank].numExecutors.count(exeType) == 0) return 0;
    return rankInfo[targetRank].numExecutors.at(exeType);
  }

  int System::GetNumExecutorSubIndices(ExeDevice exeDevice) const
  {
    int targetRank = exeDevice.exeRank;
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (rankInfo[targetRank].numExecutorSubIndices.count({exeDevice.exeType, exeDevice.exeIndex}) == 0)
      return 0;
    return rankInfo[targetRank].numExecutorSubIndices.at({exeDevice.exeType, exeDevice.exeIndex});
  }

  int System::GetNumSubExecutors(ExeDevice exeDevice) const
  {
    int targetRank = exeDevice.exeRank;
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (rankInfo[targetRank].numSubExecutors.count({exeDevice.exeType, exeDevice.exeIndex}) == 0)
      return 0;
    return rankInfo[targetRank].numSubExecutors.at({exeDevice.exeType, exeDevice.exeIndex});
  }

  int System::GetClosestCpuNumaToGpu(int gpuIndex, int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (gpuIndex < 0 || gpuIndex >= GetNumExecutors(EXE_GPU_GFX, targetRank)) return 0;
    return rankInfo[targetRank].closestCpuNumaToGpu.at(gpuIndex);
  }

  int System::GetClosestCpuNumaToNic(int nicIndex, int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (nicIndex < 0 || nicIndex >= GetNumExecutors(EXE_NIC, targetRank)) return 0;
    return rankInfo[targetRank].closestCpuNumaToNic.at(nicIndex);
  }

  void System::GetClosestNicsToGpu(std::vector<int>& nicIndices, int gpuIndex, int targetRank) const
  {
    nicIndices.clear();
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (gpuIndex < 0 || gpuIndex >= GetNumExecutors(EXE_GPU_GFX, targetRank)) return;
    nicIndices = rankInfo[targetRank].closestNicsToGpu.at(gpuIndex);
  }

  std::string System::GetHostname(int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    return rankInfo[targetRank].hostname;
  }

  std::string System::GetPpodId(int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    return rankInfo[targetRank].ppodId;
  }

  int System::GetVpodId(int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    return rankInfo[targetRank].vpodId;
  }

  std::string System::GetExecutorName(ExeDevice exeDevice) const
  {
    int targetRank = exeDevice.exeRank;
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;

    if (rankInfo[targetRank].executorName.count({exeDevice.exeType, exeDevice.exeIndex}) == 0)
      return "Unknown device";
    return rankInfo[targetRank].executorName.at({exeDevice.exeType, exeDevice.exeIndex});
  }

  int System::NicIsActive(int nicIndex, int targetRank) const
  {
    if (targetRank < 0 || targetRank >= numRanks) targetRank = rank;
    if (rankInfo[targetRank].nicIsActive.count(nicIndex) == 0) return 0;
    return rankInfo[targetRank].nicIsActive.at(nicIndex);
  }

  int GetNumExecutors(ExeType exeType, int targetRank)
  {
    return System::Get().GetNumExecutors(exeType, targetRank);
  }

  int GetNumExecutors(MemType memType, int targetRank)
  {
    if (IsCpuMemType(memType)) return GetNumExecutors(EXE_CPU,     targetRank);
    if (IsGpuMemType(memType)) return GetNumExecutors(EXE_GPU_GFX, targetRank);
    return 0;
  }

  int GetNumSubExecutors(ExeDevice exeDevice)
  {
    return System::Get().GetNumSubExecutors(exeDevice);
  }

  int GetNumExecutorSubIndices(ExeDevice exeDevice)
  {
    return System::Get().GetNumExecutorSubIndices(exeDevice);
  }

  int GetClosestCpuNumaToGpu(int gpuIndex, int targetRank)
  {
    return System::Get().GetClosestCpuNumaToGpu(gpuIndex, targetRank);
  }

  int GetClosestCpuNumaToNic(int nicIndex, int targetRank)
  {
    return System::Get().GetClosestCpuNumaToNic(nicIndex, targetRank);
  }

  int GetClosestNicToGpu(int gpuIndex, int targetRank)
  {
    std::vector<int> nicIndices;
    System::Get().GetClosestNicsToGpu(nicIndices, gpuIndex, targetRank);
    if (nicIndices.size() == 0) return -1;
    return nicIndices[0];
  }

  void GetClosestNicsToGpu(std::vector<int>& nicIndices, int gpuIndex, int targetRank)
  {
    System::Get().GetClosestNicsToGpu(nicIndices, gpuIndex, targetRank);
  }

  void GetClosestNicsToCpu(std::vector<int>& nicIndices, int cpuIndex, int targetRank)
  {
    int numNics = GetNumExecutors(EXE_NIC, targetRank);
    nicIndices.clear();
    for (int nicIndex = 0; nicIndex < numNics; nicIndex++) {
      if (GetClosestCpuNumaToNic(nicIndex, targetRank) == cpuIndex) {
        nicIndices.push_back(nicIndex);
      }
    }
  }

  int GetRank()
  {
    return System::Get().GetRank();
  }

  int GetNumRanks()
  {
    return System::Get().GetNumRanks();
  }

  int GetCommMode()
  {
    return System::Get().GetCommMode();
  }

  std::string GetHostname(int targetRank)
  {
    return System::Get().GetHostname(targetRank);
  }

  std::string GetPpodId(int targetRank)
  {
    return System::Get().GetPpodId(targetRank);
  }

  int GetVpodId(int targetRank)
  {
    return System::Get().GetVpodId(targetRank);
  }

  std::string GetExecutorName(ExeDevice exeDevice)
  {
    return System::Get().GetExecutorName(exeDevice);
  }

  int NicIsActive(int nicIndex, int targetRank)
  {
    return System::Get().NicIsActive(nicIndex, targetRank);
gilbertlee-amd's avatar
gilbertlee-amd committed
6186
6187
  }

6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
// Undefine CUDA compatibility macros
#if defined(__NVCC__)

// ROCm specific
#undef wall_clock64
#undef gcnArchName

// Datatypes
#undef hipDeviceProp_t
#undef hipError_t
#undef hipEvent_t
#undef hipStream_t

// Enumerations
#undef hipDeviceAttributeClockRate
#undef hipDeviceAttributeMaxSharedMemoryPerMultiprocessor
#undef hipDeviceAttributeMultiprocessorCount
6205
#undef hipDeviceAttributeWarpSize
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
#undef hipErrorPeerAccessAlreadyEnabled
#undef hipFuncCachePreferShared
#undef hipMemcpyDefault
#undef hipMemcpyDeviceToHost
#undef hipMemcpyHostToDevice
#undef hipSuccess

// Functions
#undef hipDeviceCanAccessPeer
#undef hipDeviceEnablePeerAccess
#undef hipDeviceGetAttribute
#undef hipDeviceGetPCIBusId
#undef hipDeviceSetCacheConfig
#undef hipDeviceSynchronize
#undef hipEventCreate
#undef hipEventDestroy
#undef hipEventElapsedTime
#undef hipEventRecord
#undef hipFree
#undef hipGetDeviceCount
#undef hipGetDeviceProperties
#undef hipGetErrorString
#undef hipHostFree
#undef hipHostMalloc
#undef hipMalloc
#undef hipMallocManaged
#undef hipMemcpy
#undef hipMemcpyAsync
#undef hipMemset
#undef hipMemsetAsync
#undef hipSetDevice
#undef hipStreamCreate
#undef hipStreamDestroy
#undef hipStreamSynchronize
#endif

// Kernel macros
#undef GetHwId
#undef GetXccId

// Undefine helper macros
#undef ERR_CHECK
#undef ERR_APPEND
}