TransferBench.cpp 114 KB
Newer Older
Gilbert Lee's avatar
Gilbert Lee committed
1
/*
2
Copyright (c) 2019-2024 Advanced Micro Devices, Inc. All rights reserved.
Gilbert Lee's avatar
Gilbert Lee committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

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

// This program measures simultaneous copy performance across multiple GPUs
// on the same node
25
26
#include <numa.h>     // If not found, try installing libnuma-dev (e.g apt-get install libnuma-dev)
#include <cmath>      // If not found, try installing g++-12      (e.g apt-get install g++-12)
Gilbert Lee's avatar
Gilbert Lee committed
27
#include <numaif.h>
Gilbert Lee's avatar
Gilbert Lee committed
28
#include <random>
Gilbert Lee's avatar
Gilbert Lee committed
29
30
31
32
33
34
35
36
#include <stack>
#include <thread>

#include "TransferBench.hpp"
#include "GetClosestNumaNode.hpp"

int main(int argc, char **argv)
{
Gilbert Lee's avatar
Gilbert Lee committed
37
38
39
40
41
42
43
  // Check for NUMA library support
  if (numa_available() == -1)
  {
    printf("[ERROR] NUMA library not supported. Check to see if libnuma has been installed on this system\n");
    exit(1);
  }

Gilbert Lee's avatar
Gilbert Lee committed
44
45
46
47
48
49
50
51
52
53
54
55
  // Display usage instructions and detected topology
  if (argc <= 1)
  {
    int const outputToCsv = EnvVars::GetEnvVar("OUTPUT_TO_CSV", 0);
    if (!outputToCsv) DisplayUsage(argv[0]);
    DisplayTopology(outputToCsv);
    exit(0);
  }

  // Collect environment variables / display current run configuration
  EnvVars ev;

Gilbert Lee's avatar
Gilbert Lee committed
56
57
  // Determine number of bytes to run per Transfer
  size_t numBytesPerTransfer = argc > 2 ? atoll(argv[2]) : DEFAULT_BYTES_PER_TRANSFER;
Gilbert Lee's avatar
Gilbert Lee committed
58
59
60
61
62
63
  if (argc > 2)
  {
    // Adjust bytes if unit specified
    char units = argv[2][strlen(argv[2])-1];
    switch (units)
    {
Gilbert Lee's avatar
Gilbert Lee committed
64
65
66
    case 'K': case 'k': numBytesPerTransfer *= 1024; break;
    case 'M': case 'm': numBytesPerTransfer *= 1024*1024; break;
    case 'G': case 'g': numBytesPerTransfer *= 1024*1024*1024; break;
Gilbert Lee's avatar
Gilbert Lee committed
67
68
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
69
70
71
72
73
  if (numBytesPerTransfer % 4)
  {
    printf("[ERROR] numBytesPerTransfer (%lu) must be a multiple of 4\n", numBytesPerTransfer);
    exit(1);
  }
Gilbert Lee's avatar
Gilbert Lee committed
74

Gilbert Lee's avatar
Gilbert Lee committed
75
76
77
78
  // Check for preset tests
  // - Tests that sweep across possible sets of Transfers
  if (!strcmp(argv[1], "sweep") || !strcmp(argv[1], "rsweep"))
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
79
80
    int numGpuSubExecs = (argc > 3 ? atoi(argv[3]) : 4);
    int numCpuSubExecs = (argc > 4 ? atoi(argv[4]) : 4);
gilbertlee-amd's avatar
gilbertlee-amd committed
81

82
    ev.configMode = CFG_SWEEP;
gilbertlee-amd's avatar
gilbertlee-amd committed
83
    RunSweepPreset(ev, numBytesPerTransfer, numGpuSubExecs, numCpuSubExecs, !strcmp(argv[1], "rsweep"));
Gilbert Lee's avatar
Gilbert Lee committed
84
85
86
    exit(0);
  }
  // - Tests that benchmark peer-to-peer performance
gilbertlee-amd's avatar
gilbertlee-amd committed
87
  else if (!strcmp(argv[1], "p2p"))
Gilbert Lee's avatar
Gilbert Lee committed
88
  {
89
    ev.configMode = CFG_P2P;
gilbertlee-amd's avatar
gilbertlee-amd committed
90
    RunPeerToPeerBenchmarks(ev, numBytesPerTransfer / sizeof(float));
Gilbert Lee's avatar
Gilbert Lee committed
91
92
    exit(0);
  }
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
  // - Test SubExecutor scaling
  else if (!strcmp(argv[1], "scaling"))
  {
    int maxSubExecs = (argc > 3 ? atoi(argv[3]) : 32);
    int exeIndex    = (argc > 4 ? atoi(argv[4]) : 0);

    if (exeIndex >= ev.numGpuDevices)
    {
      printf("[ERROR] Cannot execute scaling test with GPU device %d\n", exeIndex);
      exit(1);
    }
    ev.configMode = CFG_SCALE;
    RunScalingBenchmark(ev, numBytesPerTransfer / sizeof(float), exeIndex, maxSubExecs);
    exit(0);
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
108
109
110
111
112
113
114
115
116
117
118
  // - Test all2all benchmark
  else if (!strcmp(argv[1], "a2a"))
  {
    int numSubExecs = (argc > 3 ? atoi(argv[3]) : 4);

    // Force single-stream mode for all-to-all benchmark
    ev.useSingleStream = 1;
    ev.configMode = CFG_A2A;
    RunAllToAllBenchmark(ev, numBytesPerTransfer, numSubExecs);
    exit(0);
  }
119
120
121
122
123
  // Health check
  else if (!strcmp(argv[1], "healthcheck")) {
    RunHealthCheck(ev);
    exit(0);
  }
124
125
126
127
128
129
130
131
132
133
134
135
  // - Test schmoo benchmark
  else if (!strcmp(argv[1], "schmoo"))
  {
    if (ev.numGpuDevices < 2)
    {
      printf("[ERROR] Schmoo benchmark requires at least 2 GPUs\n");
      exit(1);
    }
    ev.configMode = CFG_SCHMOO;

    int localIdx    = (argc > 3 ? atoi(argv[3]) : 0);
    int remoteIdx   = (argc > 4 ? atoi(argv[4]) : 1);
136
    int maxSubExecs = (argc > 5 ? atoi(argv[5]) : 32);
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

    if (localIdx >= ev.numGpuDevices || remoteIdx >= ev.numGpuDevices)
    {
      printf("[ERROR] Cannot execute schmoo test with local GPU device %d, remote GPU device %d\n", localIdx, remoteIdx);
      exit(1);
    }
    ev.DisplaySchmooEnvVars();

    for (int N = 256; N <= (1<<27); N *= 2)
    {
      int delta = std::max(1, N / ev.samplingFactor);
      int curr = (numBytesPerTransfer == 0) ? N : numBytesPerTransfer / sizeof(float);
      do
      {
        RunSchmooBenchmark(ev, curr * sizeof(float), localIdx, remoteIdx, maxSubExecs);
        if (numBytesPerTransfer != 0) exit(0);
        curr += delta;
      } while (curr < N * 2);
    }
  }
157
158
159
160
161
162
163
164
165
  else if (!strcmp(argv[1], "rwrite"))
  {
    if (ev.numGpuDevices < 2)
    {
      printf("[ERROR] Remote write benchmark requires at least 2 GPUs\n");
      exit(1);
    }
    ev.DisplayRemoteWriteEnvVars();

gilbertlee-amd's avatar
gilbertlee-amd committed
166
    int numSubExecs = (argc > 3 ? atoi(argv[3]) : 4);
167
168
    int srcIdx      = (argc > 4 ? atoi(argv[4]) : 0);
    int minGpus     = (argc > 5 ? atoi(argv[5]) : 1);
169
    int maxGpus     = (argc > 6 ? atoi(argv[6]) : ev.numGpuDevices - 1);
170
171
172
173
174
175
176
177
178
179
180
181
182

    for (int N = 256; N <= (1<<27); N *= 2)
    {
      int delta = std::max(1, N / ev.samplingFactor);
      int curr = (numBytesPerTransfer == 0) ? N : numBytesPerTransfer / sizeof(float);
      do
      {
        RunRemoteWriteBenchmark(ev, curr * sizeof(float), numSubExecs, srcIdx, minGpus, maxGpus);
        if (numBytesPerTransfer != 0) exit(0);
        curr += delta;
      } while (curr < N * 2);
    }
  }
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
  else if (!strcmp(argv[1], "pcopy"))
  {
    if (ev.numGpuDevices < 2)
    {
      printf("[ERROR] Parallel copy benchmark requires at least 2 GPUs\n");
      exit(1);
    }
    ev.DisplayParallelCopyEnvVars();

    int numSubExecs = (argc > 3 ? atoi(argv[3]) : 8);
    int srcIdx      = (argc > 4 ? atoi(argv[4]) : 0);
    int minGpus     = (argc > 5 ? atoi(argv[5]) : 1);
    int maxGpus     = (argc > 6 ? atoi(argv[6]) : ev.numGpuDevices - 1);

    if (maxGpus > ev.gpuMaxHwQueues && ev.useDmaCopy)
    {
      printf("[ERROR] DMA executor %d attempting %d parallel transfers, however GPU_MAX_HW_QUEUES only set to %d\n",
             srcIdx, maxGpus, ev.gpuMaxHwQueues);
      printf("[ERROR] Aborting to avoid misleading results due to potential serialization of Transfers\n");
      exit(1);
    }

    for (int N = 256; N <= (1<<27); N *= 2)
    {
      int delta = std::max(1, N / ev.samplingFactor);
      int curr = (numBytesPerTransfer == 0) ? N : numBytesPerTransfer / sizeof(float);
      do
      {
        RunParallelCopyBenchmark(ev, curr * sizeof(float), numSubExecs, srcIdx, minGpus, maxGpus);
        if (numBytesPerTransfer != 0) exit(0);
        curr += delta;
      } while (curr < N * 2);
    }
  }
217
218
  else if (!strcmp(argv[1], "cmdline"))
  {
219
    // Print environment variables
220
221
222
223
224
225
226
    ev.DisplayEnvVars();

    // Read Transfer from command line
    std::string cmdlineTransfer;
    for (int i = 3; i < argc; i++)
      cmdlineTransfer += std::string(argv[i]) + " ";

227
    char line[MAX_LINE_LEN];
228
229
    sprintf(line, "%s", cmdlineTransfer.c_str());
    std::vector<Transfer> transfers;
230
    ParseTransfers(ev, line, transfers);
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    if (transfers.empty()) exit(0);

    // If the number of bytes is specified, use it
    if (numBytesPerTransfer != 0)
    {
      size_t N = numBytesPerTransfer / sizeof(float);
      ExecuteTransfers(ev, 1, N, transfers);
    }
    else
    {
      // Otherwise generate a range of values
      for (int N = 256; N <= (1<<27); N *= 2)
      {
        int delta = std::max(1, N / ev.samplingFactor);
        int curr = N;
        while (curr < N * 2)
        {
          ExecuteTransfers(ev, 1, curr, transfers);
          curr += delta;
        }
      }
    }
    exit(0);
  }
Gilbert Lee's avatar
Gilbert Lee committed
255

Gilbert Lee's avatar
Gilbert Lee committed
256
  // Check that Transfer configuration file can be opened
257
  ev.configMode = CFG_FILE;
Gilbert Lee's avatar
Gilbert Lee committed
258
259
260
  FILE* fp = fopen(argv[1], "r");
  if (!fp)
  {
Gilbert Lee's avatar
Gilbert Lee committed
261
    printf("[ERROR] Unable to open transfer configuration file: [%s]\n", argv[1]);
Gilbert Lee's avatar
Gilbert Lee committed
262
263
264
    exit(1);
  }

Gilbert Lee's avatar
Gilbert Lee committed
265
  // Print environment variables and CSV header
Gilbert Lee's avatar
Gilbert Lee committed
266
267
268
  ev.DisplayEnvVars();

  int testNum = 0;
269
270
  char line[MAX_LINE_LEN];
  while(fgets(line, MAX_LINE_LEN, fp))
Gilbert Lee's avatar
Gilbert Lee committed
271
272
273
274
  {
    // Check if line is a comment to be echoed to output (starts with ##)
    if (!ev.outputToCsv && line[0] == '#' && line[1] == '#') printf("%s", line);

Gilbert Lee's avatar
Gilbert Lee committed
275
276
    // Parse set of parallel Transfers to execute
    std::vector<Transfer> transfers;
277
    ParseTransfers(ev, line, transfers);
Gilbert Lee's avatar
Gilbert Lee committed
278
    if (transfers.empty()) continue;
Gilbert Lee's avatar
Gilbert Lee committed
279

gilbertlee-amd's avatar
gilbertlee-amd committed
280
281
282
283
284
285
286
287
288
289
290
    // If the number of bytes is specified, use it
    if (numBytesPerTransfer != 0)
    {
      size_t N = numBytesPerTransfer / sizeof(float);
      ExecuteTransfers(ev, ++testNum, N, transfers);
    }
    else
    {
      // Otherwise generate a range of values
      for (int N = 256; N <= (1<<27); N *= 2)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
291
        int delta = std::max(1, N / ev.samplingFactor);
gilbertlee-amd's avatar
gilbertlee-amd committed
292
293
294
        int curr = N;
        while (curr < N * 2)
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
295
          ExecuteTransfers(ev, ++testNum, curr, transfers);
gilbertlee-amd's avatar
gilbertlee-amd committed
296
297
298
299
          curr += delta;
        }
      }
    }
Gilbert Lee's avatar
Gilbert Lee committed
300
301
  }
  fclose(fp);
Gilbert Lee's avatar
Gilbert Lee committed
302

Gilbert Lee's avatar
Gilbert Lee committed
303
304
  return 0;
}
Gilbert Lee's avatar
Gilbert Lee committed
305

Gilbert Lee's avatar
Gilbert Lee committed
306
void ExecuteTransfers(EnvVars const& ev,
gilbertlee-amd's avatar
gilbertlee-amd committed
307
308
309
                      int const testNum,
                      size_t const N,
                      std::vector<Transfer>& transfers,
gilbertlee-amd's avatar
gilbertlee-amd committed
310
311
                      bool verbose,
                      double* totalBandwidthCpu)
Gilbert Lee's avatar
Gilbert Lee committed
312
{
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  // Check for any Transfers using variable number of sub-executors
  std::vector<int> varTransfers;
  std::vector<int> numUsedSubExec(ev.numGpuDevices, 0);
  std::vector<int> numVarSubExec(ev.numGpuDevices, 0);

  for (int i = 0; i < transfers.size(); i++) {
    Transfer& t = transfers[i];
    t.transferIndex = i;
    t.numBytesActual = (t.numBytes ? t.numBytes : N * sizeof(float));

    if (t.exeType == EXE_GPU_GFX) {
      if (t.numSubExecs == 0) {
        varTransfers.push_back(i);
        numVarSubExec[t.exeIndex]++;
      } else {
        numUsedSubExec[t.exeIndex] += t.numSubExecs;
      }
    } else if (t.numSubExecs == 0) {
      printf("[ERROR] Variable subexecutor count is only supported for GFX executor\n");
      exit(1);
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
335

336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
  if (verbose && !ev.outputToCsv) printf("Test %d:\n", testNum);

  TestResults testResults;
  if (varTransfers.size() == 0) {
    testResults = ExecuteTransfersImpl(ev, transfers);
  } else {
    // Determine maximum number of subexecutors
    int maxNumSubExec = 0;
    if (ev.maxNumVarSubExec) {
      maxNumSubExec = ev.maxNumVarSubExec;
    } else {
      HIP_CALL(hipDeviceGetAttribute(&maxNumSubExec, hipDeviceAttributeMultiprocessorCount, 0));
      for (int device = 0; device < ev.numGpuDevices; device++) {
        int numSubExec = 0;
        HIP_CALL(hipDeviceGetAttribute(&numSubExec, hipDeviceAttributeMultiprocessorCount, device));
        int leftOverSubExec = numSubExec - numUsedSubExec[device];
        if (leftOverSubExec < numVarSubExec[device])
          maxNumSubExec = 1;
        else if (numVarSubExec[device] != 0) {
          maxNumSubExec = std::min(maxNumSubExec, leftOverSubExec / numVarSubExec[device]);
        }
      }
    }

    // Loop over subexecs
    std::vector<Transfer> bestTransfers;
    for (int numSubExec = ev.minNumVarSubExec; numSubExec <= maxNumSubExec; numSubExec++) {
      std::vector<Transfer> currTransfers = transfers;
      for (auto idx : varTransfers) {
        currTransfers[idx].numSubExecs = numSubExec;
      }
      TestResults tempResults = ExecuteTransfersImpl(ev, currTransfers);
      if (tempResults.totalBandwidthCpu > testResults.totalBandwidthCpu) {
        bestTransfers = currTransfers;
        testResults = tempResults;
      }
    }
    transfers = bestTransfers;
  }
  if (totalBandwidthCpu) *totalBandwidthCpu = testResults.totalBandwidthCpu;

  if (verbose) {
    ReportResults(ev, transfers, testResults);
  }
}

TestResults ExecuteTransfersImpl(EnvVars const& ev,
                                 std::vector<Transfer>& transfers)
{
Gilbert Lee's avatar
Gilbert Lee committed
385
386
  // Map transfers by executor
  TransferMap transferMap;
gilbertlee-amd's avatar
gilbertlee-amd committed
387
  for (int i = 0; i < transfers.size(); i++)
Gilbert Lee's avatar
Gilbert Lee committed
388
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
389
390
    Transfer& transfer = transfers[i];
    transfer.transferIndex = i;
gilbertlee-amd's avatar
gilbertlee-amd committed
391
    Executor executor(transfer.exeType, transfer.exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
392
    ExecutorInfo& executorInfo = transferMap[executor];
gilbertlee-amd's avatar
gilbertlee-amd committed
393
    executorInfo.transfers.push_back(&transfer);
Gilbert Lee's avatar
Gilbert Lee committed
394
  }
Gilbert Lee's avatar
Gilbert Lee committed
395

gilbertlee-amd's avatar
gilbertlee-amd committed
396
  // Loop over each executor and prepare sub-executors
gilbertlee-amd's avatar
gilbertlee-amd committed
397
  std::map<int, Transfer*> transferList;
Gilbert Lee's avatar
Gilbert Lee committed
398
399
400
  for (auto& exeInfoPair : transferMap)
  {
    Executor const& executor = exeInfoPair.first;
gilbertlee-amd's avatar
gilbertlee-amd committed
401
402
403
404
    ExecutorInfo& exeInfo    = exeInfoPair.second;
    ExeType const exeType    = executor.first;
    int     const exeIndex   = RemappedIndex(executor.second, IsCpuType(exeType));

Gilbert Lee's avatar
Gilbert Lee committed
405
    exeInfo.totalTime = 0.0;
gilbertlee-amd's avatar
gilbertlee-amd committed
406
    exeInfo.totalSubExecs = 0;
Gilbert Lee's avatar
Gilbert Lee committed
407
408

    // Loop over each transfer this executor is involved in
gilbertlee-amd's avatar
gilbertlee-amd committed
409
    for (Transfer* transfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
410
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
411
412
413
      // Allocate source memory
      transfer->srcMem.resize(transfer->numSrcs);
      for (int iSrc = 0; iSrc < transfer->numSrcs; ++iSrc)
Gilbert Lee's avatar
Gilbert Lee committed
414
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
415
        MemType const& srcType  = transfer->srcType[iSrc];
416
        int     const  srcIndex = RemappedIndex(transfer->srcIndex[iSrc], IsCpuType(srcType));
gilbertlee-amd's avatar
gilbertlee-amd committed
417

Gilbert Lee's avatar
Gilbert Lee committed
418
        // Ensure executing GPU can access source memory
419
        if (IsGpuType(exeType) && IsGpuType(srcType) && srcIndex != exeIndex)
Gilbert Lee's avatar
Gilbert Lee committed
420
          EnablePeerAccess(exeIndex, srcIndex);
Gilbert Lee's avatar
Gilbert Lee committed
421

gilbertlee-amd's avatar
gilbertlee-amd committed
422
423
424
425
426
427
428
429
        AllocateMemory(srcType, srcIndex, transfer->numBytesActual + ev.byteOffset, (void**)&transfer->srcMem[iSrc]);
      }

      // Allocate destination memory
      transfer->dstMem.resize(transfer->numDsts);
      for (int iDst = 0; iDst < transfer->numDsts; ++iDst)
      {
        MemType const& dstType  = transfer->dstType[iDst];
430
        int     const  dstIndex = RemappedIndex(transfer->dstIndex[iDst], IsCpuType(dstType));
gilbertlee-amd's avatar
gilbertlee-amd committed
431

Gilbert Lee's avatar
Gilbert Lee committed
432
        // Ensure executing GPU can access destination memory
433
        if (IsGpuType(exeType) && IsGpuType(dstType) && dstIndex != exeIndex)
Gilbert Lee's avatar
Gilbert Lee committed
434
435
          EnablePeerAccess(exeIndex, dstIndex);

gilbertlee-amd's avatar
gilbertlee-amd committed
436
437
        AllocateMemory(dstType, dstIndex, transfer->numBytesActual + ev.byteOffset, (void**)&transfer->dstMem[iDst]);
      }
Gilbert Lee's avatar
Gilbert Lee committed
438

gilbertlee-amd's avatar
gilbertlee-amd committed
439
      exeInfo.totalSubExecs += transfer->numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
440
      transferList[transfer->transferIndex] = transfer;
Gilbert Lee's avatar
Gilbert Lee committed
441
442
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
443
444
    // Prepare additional requirement for GPU-based executors
    if (IsGpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
445
    {
446
447
      HIP_CALL(hipSetDevice(exeIndex));

gilbertlee-amd's avatar
gilbertlee-amd committed
448
449
450
451
452
453
      // Single-stream is only supported for GFX-based executors
      int const numStreamsToUse = (exeType == EXE_GPU_DMA || !ev.useSingleStream) ? exeInfo.transfers.size() : 1;
      exeInfo.streams.resize(numStreamsToUse);
      exeInfo.startEvents.resize(numStreamsToUse);
      exeInfo.stopEvents.resize(numStreamsToUse);
      for (int i = 0; i < numStreamsToUse; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
454
      {
455
456
457
458
        if (ev.cuMask.size())
        {
#if !defined(__NVCC__)
          HIP_CALL(hipExtStreamCreateWithCUMask(&exeInfo.streams[i], ev.cuMask.size(), ev.cuMask.data()));
459
460
461
#else
          printf("[ERROR] CU Masking in not supported on NVIDIA hardware\n");
          exit(-1);
462
463
464
465
466
467
#endif
        }
        else
        {
          HIP_CALL(hipStreamCreate(&exeInfo.streams[i]));
        }
Gilbert Lee's avatar
Gilbert Lee committed
468
469
470
        HIP_CALL(hipEventCreate(&exeInfo.startEvents[i]));
        HIP_CALL(hipEventCreate(&exeInfo.stopEvents[i]));
      }
Gilbert Lee's avatar
Gilbert Lee committed
471

gilbertlee-amd's avatar
gilbertlee-amd committed
472
      if (exeType == EXE_GPU_GFX)
Gilbert Lee's avatar
Gilbert Lee committed
473
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
474
475
        // 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
476
#if !defined(__NVCC__)
gilbertlee-amd's avatar
gilbertlee-amd committed
477
478
        AllocateMemory(MEM_GPU, exeIndex, exeInfo.totalSubExecs * sizeof(SubExecParam),
                       (void**)&exeInfo.subExecParamGpu);
479
#else
480
        AllocateMemory(MEM_MANAGED, exeIndex, exeInfo.totalSubExecs * sizeof(SubExecParam),
481
482
                       (void**)&exeInfo.subExecParamGpu);
#endif
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

        // Check for sufficient subExecutors
        int numDeviceCUs = 0;
        HIP_CALL(hipDeviceGetAttribute(&numDeviceCUs, hipDeviceAttributeMultiprocessorCount, exeIndex));
        if (exeInfo.totalSubExecs > numDeviceCUs)
        {
          printf("[WARN] GFX executor %d requesting %d total subexecutors, however only has %d.  Some Transfers may be serialized\n",
                 exeIndex, exeInfo.totalSubExecs, numDeviceCUs);
        }
      }

      // Check for targeted DMA
      if (exeType == EXE_GPU_DMA)
      {
        bool useRandomDma = false;
        bool useTargetDma = false;

        // Check for sufficient hardware queues
#if !defined(__NVCC_)
        if (exeInfo.transfers.size() > ev.gpuMaxHwQueues)
        {
          printf("[WARN] DMA executor %d attempting %lu parallel transfers, however GPU_MAX_HW_QUEUES only set to %d\n",
                 exeIndex, exeInfo.transfers.size(), ev.gpuMaxHwQueues);
        }
#endif

        for (Transfer* transfer : exeInfo.transfers)
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
511
          if (transfer->exeSubIndex != -1 || ev.useHsaDma)
512
          {
gilbertlee-amd's avatar
gilbertlee-amd committed
513
            useTargetDma = (transfer->exeSubIndex != -1);
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

#if defined(__NVCC__)
            printf("[ERROR] DMA executor subindex not supported on NVIDIA hardware\n");
            exit(-1);
#else
            if (transfer->numSrcs != 1 || transfer->numDsts != 1)
            {
              printf("[ERROR] DMA Transfer must have at exactly one source and one destination");
              exit(1);
            }

            // Collect HSA agent information

            hsa_amd_pointer_info_t info;
            info.size = sizeof(info);

            HSA_CHECK(hsa_amd_pointer_info(transfer->dstMem[0], &info, NULL, NULL, NULL));
            transfer->dstAgent = info.agentOwner;

            HSA_CHECK(hsa_amd_pointer_info(transfer->srcMem[0], &info, NULL, NULL, NULL));
            transfer->srcAgent = info.agentOwner;

            // Create HSA completion signal
            HSA_CHECK(hsa_signal_create(1, 0, NULL, &transfer->signal));

            // Check for valid engine Id
            if (transfer->exeSubIndex < -1 || transfer->exeSubIndex >= 32)
            {
              printf("[ERROR] DMA executor subindex must be between 0 and 31\n");
              exit(1);
            }

            // Check that engine Id exists between agents
gilbertlee-amd's avatar
gilbertlee-amd committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
            if (useTargetDma) {
              uint32_t engineIdMask = 0;
              HSA_CHECK(hsa_amd_memory_copy_engine_status(transfer->dstAgent,
                                                          transfer->srcAgent,
                                                          &engineIdMask));
              transfer->sdmaEngineId = (hsa_amd_sdma_engine_id_t)(1U << transfer->exeSubIndex);
              if (!(transfer->sdmaEngineId & engineIdMask))
              {
                printf("[ERROR] DMA executor %d.%d does not exist or cannot copy between source %s to destination %s\n",
                       transfer->exeIndex, transfer->exeSubIndex,
                       transfer->SrcToStr().c_str(),
                       transfer->DstToStr().c_str());
                exit(1);
              }
561
562
563
564
565
566
567
568
569
570
571
572
573
            }
#endif
          }
          else
          {
            useRandomDma = true;
          }
        }
        if (useRandomDma && useTargetDma)
        {
          printf("[WARN] Mixing targeted and untargetted DMA execution on GPU %d may result in resource conflicts\n",
            exeIndex);
        }
Gilbert Lee's avatar
Gilbert Lee committed
574
575
576
      }
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
577

gilbertlee-amd's avatar
gilbertlee-amd committed
578
579

  // Prepare input memory and block parameters for current N
580
  bool isSrcCorrect = true;
gilbertlee-amd's avatar
gilbertlee-amd committed
581
  for (auto& exeInfoPair : transferMap)
Gilbert Lee's avatar
Gilbert Lee committed
582
  {
583
584
585
586
587
    Executor const& executor = exeInfoPair.first;
    ExecutorInfo& exeInfo    = exeInfoPair.second;
    ExeType const exeType    = executor.first;
    int     const exeIndex   = RemappedIndex(executor.second, IsCpuType(exeType));

gilbertlee-amd's avatar
gilbertlee-amd committed
588
589
    exeInfo.totalBytes = 0;
    for (int i = 0; i < exeInfo.transfers.size(); ++i)
Gilbert Lee's avatar
Gilbert Lee committed
590
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
591
592
      // Prepare subarrays each threadblock works on and fill src memory with patterned data
      Transfer* transfer = exeInfo.transfers[i];
gilbertlee-amd's avatar
gilbertlee-amd committed
593
      transfer->PrepareSubExecParams(ev);
594
      isSrcCorrect &= transfer->PrepareSrc(ev);
gilbertlee-amd's avatar
gilbertlee-amd committed
595
      exeInfo.totalBytes += transfer->numBytesActual;
596
597
598
599
600
601
    }

    // Copy block parameters to GPU for GPU executors
    if (exeType == EXE_GPU_GFX)
    {
      std::vector<SubExecParam> tempSubExecParam;
Gilbert Lee's avatar
Gilbert Lee committed
602

603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
      if (!ev.useSingleStream || (ev.blockOrder == ORDER_SEQUENTIAL))
      {
        // Assign Transfers to sequentual threadblocks
        int transferOffset = 0;
        for (Transfer* transfer : exeInfo.transfers)
        {
          transfer->subExecParamGpuPtr = exeInfo.subExecParamGpu + transferOffset;

          transfer->subExecIdx.clear();
          for (int subExecIdx = 0; subExecIdx < transfer->subExecParam.size(); subExecIdx++)
          {
            transfer->subExecIdx.push_back(transferOffset + subExecIdx);
            tempSubExecParam.push_back(transfer->subExecParam[subExecIdx]);
          }
          transferOffset += transfer->numSubExecs;
        }
      }
      else if (ev.blockOrder == ORDER_INTERLEAVED)
      {
        // Interleave threadblocks of different Transfers
        exeInfo.transfers[0]->subExecParamGpuPtr = exeInfo.subExecParamGpu;
        for (int subExecIdx = 0; tempSubExecParam.size() < exeInfo.totalSubExecs; ++subExecIdx)
        {
          for (Transfer* transfer : exeInfo.transfers)
          {
            if (subExecIdx < transfer->numSubExecs)
            {
              transfer->subExecIdx.push_back(tempSubExecParam.size());
              tempSubExecParam.push_back(transfer->subExecParam[subExecIdx]);
            }
          }
        }
      }
      else if (ev.blockOrder == ORDER_RANDOM)
Gilbert Lee's avatar
Gilbert Lee committed
637
      {
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
        std::vector<std::pair<int,int>> indices;
        exeInfo.transfers[0]->subExecParamGpuPtr = exeInfo.subExecParamGpu;

        // Build up a list of (transfer,subExecParam) indices, then randomly sort them
        for (int i = 0; i < exeInfo.transfers.size(); i++)
        {
          Transfer* transfer = exeInfo.transfers[i];
          for (int subExecIdx = 0; subExecIdx < transfer->numSubExecs; subExecIdx++)
            indices.push_back(std::make_pair(i, subExecIdx));
        }
        std::shuffle(indices.begin(), indices.end(), *ev.generator);

        // Build randomized threadblock list
        for (auto p : indices)
        {
          Transfer* transfer = exeInfo.transfers[p.first];
          transfer->subExecIdx.push_back(tempSubExecParam.size());
          tempSubExecParam.push_back(transfer->subExecParam[p.second]);
        }
Gilbert Lee's avatar
Gilbert Lee committed
657
      }
658
659
660
661
662
663
664

      HIP_CALL(hipSetDevice(exeIndex));
      HIP_CALL(hipMemcpy(exeInfo.subExecParamGpu,
                         tempSubExecParam.data(),
                         tempSubExecParam.size() * sizeof(SubExecParam),
                         hipMemcpyDefault));
      HIP_CALL(hipDeviceSynchronize());
Gilbert Lee's avatar
Gilbert Lee committed
665
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
666
  }
Gilbert Lee's avatar
Gilbert Lee committed
667

gilbertlee-amd's avatar
gilbertlee-amd committed
668
669
670
671
  // Launch kernels (warmup iterations are not counted)
  double totalCpuTime = 0;
  size_t numTimedIterations = 0;
  std::stack<std::thread> threads;
672
  for (int iteration = -ev.numWarmups; isSrcCorrect; iteration++)
gilbertlee-amd's avatar
gilbertlee-amd committed
673
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
674
    if (ev.numIterations > 0 && iteration    >= ev.numIterations) break;
gilbertlee-amd's avatar
gilbertlee-amd committed
675
    if (ev.numIterations < 0 && totalCpuTime > -ev.numIterations) break;
Gilbert Lee's avatar
Gilbert Lee committed
676

gilbertlee-amd's avatar
gilbertlee-amd committed
677
    // Pause before starting first timed iteration in interactive mode
678
    if (ev.useInteractive && iteration == 0)
Gilbert Lee's avatar
Gilbert Lee committed
679
    {
680
681
682
683
      printf("Memory prepared:\n");

      for (Transfer& transfer : transfers)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
684
685
686
687
688
        printf("Transfer %03d:\n", transfer.transferIndex);
        for (int iSrc = 0; iSrc < transfer.numSrcs; ++iSrc)
          printf("  SRC %0d: %p\n", iSrc, transfer.srcMem[iSrc]);
        for (int iDst = 0; iDst < transfer.numDsts; ++iDst)
          printf("  DST %0d: %p\n", iDst, transfer.dstMem[iDst]);
689
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
690
      printf("Hit <Enter> to continue: ");
691
692
693
694
695
      if (scanf("%*c") != 0)
      {
        printf("[ERROR] Unexpected input\n");
        exit(1);
      }
Gilbert Lee's avatar
Gilbert Lee committed
696
697
      printf("\n");
    }
Gilbert Lee's avatar
Gilbert Lee committed
698

gilbertlee-amd's avatar
gilbertlee-amd committed
699
700
701
702
703
    // Start CPU timing for this iteration
    auto cpuStart = std::chrono::high_resolution_clock::now();

    // Execute all Transfers in parallel
    for (auto& exeInfoPair : transferMap)
704
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
705
      ExecutorInfo& exeInfo = exeInfoPair.second;
gilbertlee-amd's avatar
gilbertlee-amd committed
706
707
708
      ExeType       exeType = exeInfoPair.first.first;
      int const numTransfersToRun = (exeType == EXE_GPU_GFX && ev.useSingleStream) ? 1 : exeInfo.transfers.size();

gilbertlee-amd's avatar
gilbertlee-amd committed
709
710
      for (int i = 0; i < numTransfersToRun; ++i)
        threads.push(std::thread(RunTransfer, std::ref(ev), iteration, std::ref(exeInfo), i));
711
    }
Gilbert Lee's avatar
Gilbert Lee committed
712

gilbertlee-amd's avatar
gilbertlee-amd committed
713
714
715
716
717
718
719
    // Wait for all threads to finish
    int const numTransfers = threads.size();
    for (int i = 0; i < numTransfers; i++)
    {
      threads.top().join();
      threads.pop();
    }
Gilbert Lee's avatar
Gilbert Lee committed
720

gilbertlee-amd's avatar
gilbertlee-amd committed
721
722
723
724
    // Stop CPU timing for this iteration
    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
    double deltaSec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count();

725
726
727
728
729
730
731
732
733
    if (ev.alwaysValidate)
    {
      for (auto transferPair : transferList)
      {
        Transfer* transfer = transferPair.second;
        transfer->ValidateDst(ev);
      }
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
734
    if (iteration >= 0)
Gilbert Lee's avatar
Gilbert Lee committed
735
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
736
737
738
739
      ++numTimedIterations;
      totalCpuTime += deltaSec;
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
740

gilbertlee-amd's avatar
gilbertlee-amd committed
741
  // Pause for interactive mode
742
  if (isSrcCorrect && ev.useInteractive)
gilbertlee-amd's avatar
gilbertlee-amd committed
743
744
  {
    printf("Transfers complete. Hit <Enter> to continue: ");
745
746
747
748
749
    if (scanf("%*c") != 0)
    {
      printf("[ERROR] Unexpected input\n");
      exit(1);
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
750
751
    printf("\n");
  }
Gilbert Lee's avatar
Gilbert Lee committed
752

gilbertlee-amd's avatar
gilbertlee-amd committed
753
754
755
756
757
758
  // Validate that each transfer has transferred correctly
  size_t totalBytesTransferred = 0;
  int const numTransfers = transferList.size();
  for (auto transferPair : transferList)
  {
    Transfer* transfer = transferPair.second;
gilbertlee-amd's avatar
gilbertlee-amd committed
759
760
    transfer->ValidateDst(ev);
    totalBytesTransferred += transfer->numBytesActual;
gilbertlee-amd's avatar
gilbertlee-amd committed
761
  }
Gilbert Lee's avatar
Gilbert Lee committed
762

763
764
765
766
767
768
  // Record results
  TestResults testResults;
  testResults.numTimedIterations = numTimedIterations;
  testResults.totalBytesTransferred = totalBytesTransferred;
  testResults.totalDurationMsec = totalCpuTime / (1.0 * numTimedIterations * ev.numSubIterations) * 1000;
  testResults.totalBandwidthCpu = (totalBytesTransferred / 1.0E6) / testResults.totalDurationMsec;
Gilbert Lee's avatar
Gilbert Lee committed
769

770
  double maxExeDurationMsec = 0.0;
771
  if (!isSrcCorrect) goto cleanup;
772

773
774
775
776
777
778
  for (auto& exeInfoPair : transferMap)
  {
    ExecutorInfo  exeInfo  = exeInfoPair.second;
    ExeType const exeType  = exeInfoPair.first.first;
    int     const exeIndex = exeInfoPair.first.second;
    ExeResult& exeResult   = testResults.exeResults[std::make_pair(exeType, exeIndex)];
gilbertlee-amd's avatar
gilbertlee-amd committed
779

780
781
782
783
    // Compute total time for non GPU executors
    if (exeType != EXE_GPU_GFX || ev.useSingleStream == 0)
    {
      exeInfo.totalTime = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
784
      for (auto const& transfer : exeInfo.transfers)
785
        exeInfo.totalTime = std::max(exeInfo.totalTime, transfer->transferTime);
Gilbert Lee's avatar
Gilbert Lee committed
786
    }
787

788
789
790
791
792
    exeResult.totalBytes      = exeInfo.totalBytes;
    exeResult.durationMsec    = exeInfo.totalTime / (1.0 * numTimedIterations * ev.numSubIterations);
    exeResult.bandwidthGbs    = (exeInfo.totalBytes / 1.0E9) / exeResult.durationMsec * 1000.0f;
    exeResult.sumBandwidthGbs = 0;
    maxExeDurationMsec        = std::max(maxExeDurationMsec, exeResult.durationMsec);
Gilbert Lee's avatar
Gilbert Lee committed
793

794
    for (auto& transfer: exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
795
    {
796
797
798
799
800
      exeResult.transferIdx.push_back(transfer->transferIndex);
      transfer->transferTime /= (1.0 * numTimedIterations * ev.numSubIterations);
      transfer->transferBandwidth = (transfer->numBytesActual / 1.0E9) / transfer->transferTime * 1000.0f;
      transfer->executorBandwidth = exeResult.bandwidthGbs;
      exeResult.sumBandwidthGbs += transfer->transferBandwidth;
Gilbert Lee's avatar
Gilbert Lee committed
801
802
    }
  }
803
  testResults.overheadMsec = testResults.totalDurationMsec - maxExeDurationMsec;
Gilbert Lee's avatar
Gilbert Lee committed
804

Gilbert Lee's avatar
Gilbert Lee committed
805
  // Release GPU memory
806
cleanup:
Gilbert Lee's avatar
Gilbert Lee committed
807
808
  for (auto exeInfoPair : transferMap)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
809
810
811
812
    ExecutorInfo& exeInfo  = exeInfoPair.second;
    ExeType const exeType  = exeInfoPair.first.first;
    int     const exeIndex = RemappedIndex(exeInfoPair.first.second, IsCpuType(exeType));

Gilbert Lee's avatar
Gilbert Lee committed
813
814
    for (auto& transfer : exeInfo.transfers)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
815
816
817
818
819
820
821
822
823
824
825
      for (int iSrc = 0; iSrc < transfer->numSrcs; ++iSrc)
      {
        MemType const& srcType = transfer->srcType[iSrc];
        DeallocateMemory(srcType, transfer->srcMem[iSrc], transfer->numBytesActual + ev.byteOffset);
      }
      for (int iDst = 0; iDst < transfer->numDsts; ++iDst)
      {
        MemType const& dstType = transfer->dstType[iDst];
        DeallocateMemory(dstType, transfer->dstMem[iDst], transfer->numBytesActual + ev.byteOffset);
      }
      transfer->subExecParam.clear();
826

gilbertlee-amd's avatar
gilbertlee-amd committed
827
      if (exeType == EXE_GPU_DMA && (transfer->exeSubIndex != -1 || ev.useHsaDma))
828
829
830
831
832
      {
#if !defined(__NVCC__)
        HSA_CHECK(hsa_signal_destroy(transfer->signal));
#endif
      }
Gilbert Lee's avatar
Gilbert Lee committed
833
834
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
835
    if (IsGpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
836
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
837
838
      int const numStreams = (int)exeInfo.streams.size();
      for (int i = 0; i < numStreams; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
839
      {
Gilbert Lee's avatar
Gilbert Lee committed
840
841
842
        HIP_CALL(hipEventDestroy(exeInfo.startEvents[i]));
        HIP_CALL(hipEventDestroy(exeInfo.stopEvents[i]));
        HIP_CALL(hipStreamDestroy(exeInfo.streams[i]));
Gilbert Lee's avatar
Gilbert Lee committed
843
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
844
845
846

      if (exeType == EXE_GPU_GFX)
      {
847
#if !defined(__NVCC__)
gilbertlee-amd's avatar
gilbertlee-amd committed
848
        DeallocateMemory(MEM_GPU, exeInfo.subExecParamGpu);
849
#else
850
        DeallocateMemory(MEM_MANAGED, exeInfo.subExecParamGpu);
851
#endif
gilbertlee-amd's avatar
gilbertlee-amd committed
852
      }
Gilbert Lee's avatar
Gilbert Lee committed
853
854
    }
  }
855
856

  return testResults;
Gilbert Lee's avatar
Gilbert Lee committed
857
858
859
860
}

void DisplayUsage(char const* cmdName)
{
Gilbert Lee's avatar
Gilbert Lee committed
861
  printf("TransferBench v%s\n", TB_VERSION);
Gilbert Lee's avatar
Gilbert Lee committed
862
863
864
865
866
867
868
869
870
871
872
873
874
  printf("========================================\n");

  if (numa_available() == -1)
  {
    printf("[ERROR] NUMA library not supported. Check to see if libnuma has been installed on this system\n");
    exit(1);
  }
  int numGpuDevices;
  HIP_CALL(hipGetDeviceCount(&numGpuDevices));
  int const numCpuDevices = numa_num_configured_nodes();

  printf("Usage: %s config <N>\n", cmdName);
  printf("  config: Either:\n");
Gilbert Lee's avatar
Gilbert Lee committed
875
  printf("          - Filename of configFile containing Transfers to execute (see example.cfg for format)\n");
gilbertlee-amd's avatar
gilbertlee-amd committed
876
  printf("          - Name of preset config:\n");
877
878
879
  printf("              a2a          - GPU All-To-All benchmark\n");
  printf("                             - 3rd optional arg: # of SubExecs to use\n");
  printf("              cmdline      - Read Transfers from command line arguments (after N)\n");
880
  printf("              healthcheck  - Simple bandwidth health check (MI300 series only)\n");
gilbertlee-amd's avatar
gilbertlee-amd committed
881
  printf("              p2p          - Peer-to-peer benchmark tests\n");
882
883
884
885
886
  printf("              rwrite/pcopy - Parallel writes/copies from single GPU to other GPUs\n");
  printf("                             - 3rd optional arg: # GPU SubExecs per Transfer\n");
  printf("                             - 4th optional arg: Root GPU index\n");
  printf("                             - 5th optional arg: Min number of other GPUs to transfer to\n");
  printf("                             - 6th optional arg: Max number of other GPUs to transfer to\n");
gilbertlee-amd's avatar
gilbertlee-amd committed
887
  printf("              sweep/rsweep - Sweep/random sweep across possible sets of Transfers\n");
888
889
  printf("                             - 3rd optional arg: # GPU SubExecs per Transfer\n");
  printf("                             - 4th optional arg: # CPU SubExecs per Transfer\n");
890
  printf("              scaling      - GPU GFX SubExec scaling copy test\n");
891
892
  printf("                             - 3th optional arg: Max # of SubExecs to use\n");
  printf("                             - 4rd optional arg: GPU index to use as executor\n");
893
  printf("              schmoo       - Local/RemoteRead/Write/Copy between two GPUs\n");
Gilbert Lee's avatar
Gilbert Lee committed
894
  printf("  N     : (Optional) Number of bytes to copy per Transfer.\n");
Gilbert Lee's avatar
Gilbert Lee committed
895
  printf("          If not specified, defaults to %lu bytes. Must be a multiple of 4 bytes\n",
Gilbert Lee's avatar
Gilbert Lee committed
896
         DEFAULT_BYTES_PER_TRANSFER);
Gilbert Lee's avatar
Gilbert Lee committed
897
898
899
900
901
902
903
  printf("          If 0 is specified, a range of Ns will be benchmarked\n");
  printf("          May append a suffix ('K', 'M', 'G') for kilobytes / megabytes / gigabytes\n");
  printf("\n");

  EnvVars::DisplayUsage();
}

gilbertlee-amd's avatar
gilbertlee-amd committed
904
int RemappedIndex(int const origIdx, bool const isCpuType)
Gilbert Lee's avatar
Gilbert Lee committed
905
{
906
907
  static std::vector<int> remappingCpu;
  static std::vector<int> remappingGpu;
Gilbert Lee's avatar
Gilbert Lee committed
908

909
910
911
912
913
914
915
916
  // Build CPU remapping on first use
  // Skip numa nodes that are not configured
  if (remappingCpu.empty())
  {
    for (int node = 0; node <= numa_max_node(); node++)
      if (numa_bitmask_isbitset(numa_get_mems_allowed(), node))
        remappingCpu.push_back(node);
  }
Gilbert Lee's avatar
Gilbert Lee committed
917

918
919
  // Build remappingGpu on first use
  if (remappingGpu.empty())
Gilbert Lee's avatar
Gilbert Lee committed
920
921
922
  {
    int numGpuDevices;
    HIP_CALL(hipGetDeviceCount(&numGpuDevices));
923
    remappingGpu.resize(numGpuDevices);
Gilbert Lee's avatar
Gilbert Lee committed
924
925
926
927

    int const usePcieIndexing = getenv("USE_PCIE_INDEX") ? atoi(getenv("USE_PCIE_INDEX")) : 0;
    if (!usePcieIndexing)
    {
928
      // For HIP-based indexing no remappingGpu is necessary
Gilbert Lee's avatar
Gilbert Lee committed
929
      for (int i = 0; i < numGpuDevices; ++i)
930
        remappingGpu[i] = i;
Gilbert Lee's avatar
Gilbert Lee committed
931
932
933
934
935
936
937
938
939
940
941
942
943
944
    }
    else
    {
      // Collect PCIe address for each GPU
      std::vector<std::pair<std::string, int>> mapping;
      char pciBusId[20];
      for (int i = 0; i < numGpuDevices; ++i)
      {
        HIP_CALL(hipDeviceGetPCIBusId(pciBusId, 20, i));
        mapping.push_back(std::make_pair(pciBusId, i));
      }
      // Sort GPUs by PCIe address then use that as mapping
      std::sort(mapping.begin(), mapping.end());
      for (int i = 0; i < numGpuDevices; ++i)
945
        remappingGpu[i] = mapping[i].second;
Gilbert Lee's avatar
Gilbert Lee committed
946
947
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
948
  return isCpuType ? remappingCpu[origIdx] : remappingGpu[origIdx];
Gilbert Lee's avatar
Gilbert Lee committed
949
950
951
952
}

void DisplayTopology(bool const outputToCsv)
{
953

954
  int numCpuDevices = numa_num_configured_nodes();
Gilbert Lee's avatar
Gilbert Lee committed
955
956
957
958
959
  int numGpuDevices;
  HIP_CALL(hipGetDeviceCount(&numGpuDevices));

  if (outputToCsv)
  {
960
    printf("NumCpus,%d\n", numCpuDevices);
Gilbert Lee's avatar
Gilbert Lee committed
961
    printf("NumGpus,%d\n", numGpuDevices);
962
963
964
  }
  else
  {
965
966
    printf("\nDetected topology: %d configured CPU NUMA node(s) [%d total]   %d GPU device(s)\n",
           numa_num_configured_nodes(), numa_max_node() + 1, numGpuDevices);
967
968
969
970
971
972
973
974
  }

  // Print out detected CPU topology
  if (outputToCsv)
  {
    printf("NUMA");
    for (int j = 0; j < numCpuDevices; j++)
      printf(",NUMA%02d", j);
975
    printf(",# CPUs,ClosestGPUs,ActualNode\n");
976
977
978
  }
  else
  {
979
    printf("            |");
980
    for (int j = 0; j < numCpuDevices; j++)
981
982
983
984
      printf("NUMA %02d|", j);
    printf(" #Cpus | Closest GPU(s)\n");

    printf("------------+");
985
    for (int j = 0; j <= numCpuDevices; j++)
986
987
      printf("-------+");
    printf("---------------\n");
988
989
990
991
  }

  for (int i = 0; i < numCpuDevices; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
992
    int nodeI = RemappedIndex(i, true);
993
    printf("NUMA %02d (%02d)%s", i, nodeI, outputToCsv ? "," : "|");
994
995
    for (int j = 0; j < numCpuDevices; j++)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
996
      int nodeJ = RemappedIndex(j, true);
997
      int numaDist = numa_distance(nodeI, nodeJ);
998
      if (outputToCsv)
gilbertlee-amd's avatar
gilbertlee-amd committed
999
        printf("%d,", numaDist);
1000
      else
1001
        printf(" %5d |", numaDist);
1002
1003
1004
1005
    }

    int numCpus = 0;
    for (int j = 0; j < numa_num_configured_cpus(); j++)
1006
      if (numa_node_of_cpu(j) == nodeI) numCpus++;
1007
1008
1009
    if (outputToCsv)
      printf("%d,", numCpus);
    else
1010
      printf(" %5d | ", numCpus);
1011

1012
#if !defined(__NVCC__)
1013
1014
1015
    bool isFirst = true;
    for (int j = 0; j < numGpuDevices; j++)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
1016
      if (GetClosestNumaNode(RemappedIndex(j, false)) == i)
1017
1018
      {
        if (isFirst) isFirst = false;
gilbertlee-amd's avatar
gilbertlee-amd committed
1019
1020
        else printf(",");
        printf("%d", j);
1021
1022
      }
    }
1023
#endif
1024
1025
1026
1027
    printf("\n");
  }
  printf("\n");

1028
#if defined(__NVCC__)
1029
1030
1031
1032
1033
1034
1035
1036

  for (int i = 0; i < numGpuDevices; i++)
  {
    hipDeviceProp_t prop;
    HIP_CALL(hipGetDeviceProperties(&prop, i));
    printf(" GPU %02d | %s\n", i, prop.name);
  }

1037
1038
  // No further topology detection done for NVIDIA platforms
  return;
1039
1040
1041
1042
#else
    // Figure out DMA engines per GPU
  std::vector<std::set<int>> dmaEngineIdsPerDevice(numGpuDevices);
  {
1043
1044
    std::vector<hsa_agent_t> gpuAgentList;
    std::vector<hsa_agent_t> allAgentList;
1045
1046
    hsa_amd_pointer_info_t info;
    info.size = sizeof(info);
1047

1048
1049
1050
    for (int deviceId = 0; deviceId < numGpuDevices; deviceId++)
    {
      HIP_CALL(hipSetDevice(deviceId));
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
      int32_t* tempGpuBuffer;
      HIP_CALL(hipMalloc((void**)&tempGpuBuffer, 1024));
      HSA_CHECK(hsa_amd_pointer_info(tempGpuBuffer, &info, NULL, NULL, NULL));
      gpuAgentList.push_back(info.agentOwner);
      allAgentList.push_back(info.agentOwner);
      HIP_CALL(hipFree(tempGpuBuffer));
    }
    for (int deviceId = 0; deviceId < numCpuDevices; deviceId++)
    {
      int32_t* tempCpuBuffer;
      AllocateMemory(MEM_CPU, deviceId, 1024, (void**)&tempCpuBuffer);
      HSA_CHECK(hsa_amd_pointer_info(tempCpuBuffer, &info, NULL, NULL, NULL));
      allAgentList.push_back(info.agentOwner);
      DeallocateMemory(MEM_CPU, tempCpuBuffer, 1024);
1065
1066
1067
1068
1069
    }

    for (int srcDevice = 0; srcDevice < numGpuDevices; srcDevice++)
    {
      dmaEngineIdsPerDevice[srcDevice].clear();
1070
      for (int dstDevice = 0; dstDevice < allAgentList.size(); dstDevice++)
1071
1072
1073
      {
        if (srcDevice == dstDevice) continue;
        uint32_t engineIdMask = 0;
1074
1075
        if (hsa_amd_memory_copy_engine_status(allAgentList[dstDevice],
                                              gpuAgentList[srcDevice],
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
                                              &engineIdMask) != HSA_STATUS_SUCCESS)
          continue;
        for (int engineId = 0; engineId < 32; engineId++)
        {
          if (engineIdMask & (1U << engineId))
            dmaEngineIdsPerDevice[srcDevice].insert(engineId);
        }
      }
    }
  }
1086

1087
1088
1089
  // Print out detected GPU topology
  if (outputToCsv)
  {
Gilbert Lee's avatar
Gilbert Lee committed
1090
1091
1092
    printf("GPU");
    for (int j = 0; j < numGpuDevices; j++)
      printf(",GPU %02d", j);
1093
    printf(",PCIe Bus ID,ClosestNUMA,DMA engines\n");
Gilbert Lee's avatar
Gilbert Lee committed
1094
1095
1096
  }
  else
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
    printf("        |");
    for (int j = 0; j < numGpuDevices; j++)
    {
      hipDeviceProp_t prop;
      HIP_CALL(hipGetDeviceProperties(&prop, j));
      std::string fullName = prop.gcnArchName;
      std::string archName = fullName.substr(0, fullName.find(':'));
      printf(" %6s |", archName.c_str());
    }
    printf("\n");
Gilbert Lee's avatar
Gilbert Lee committed
1107
1108
1109
    printf("        |");
    for (int j = 0; j < numGpuDevices; j++)
      printf(" GPU %02d |", j);
1110
    printf(" PCIe Bus ID  | #CUs | Closest NUMA | DMA engines\n");
Gilbert Lee's avatar
Gilbert Lee committed
1111
1112
    for (int j = 0; j <= numGpuDevices; j++)
      printf("--------+");
1113
    printf("--------------+------+-------------+------------\n");
Gilbert Lee's avatar
Gilbert Lee committed
1114
1115
1116
1117
1118
  }

  char pciBusId[20];
  for (int i = 0; i < numGpuDevices; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1119
    int const deviceIdx = RemappedIndex(i, false);
Gilbert Lee's avatar
Gilbert Lee committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
    printf("%sGPU %02d%s", outputToCsv ? "" : " ", i, outputToCsv ? "," : " |");
    for (int j = 0; j < numGpuDevices; j++)
    {
      if (i == j)
      {
        if (outputToCsv)
          printf("-,");
        else
          printf("    -   |");
      }
      else
      {
        uint32_t linkType, hopCount;
gilbertlee-amd's avatar
gilbertlee-amd committed
1133
1134
        HIP_CALL(hipExtGetLinkTypeAndHopCount(deviceIdx,
                                              RemappedIndex(j, false),
Gilbert Lee's avatar
Gilbert Lee committed
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
                                              &linkType, &hopCount));
        printf("%s%s-%d%s",
               outputToCsv ? "" : " ",
               linkType == HSA_AMD_LINK_INFO_TYPE_HYPERTRANSPORT ? "  HT" :
               linkType == HSA_AMD_LINK_INFO_TYPE_QPI            ? " QPI" :
               linkType == HSA_AMD_LINK_INFO_TYPE_PCIE           ? "PCIE" :
               linkType == HSA_AMD_LINK_INFO_TYPE_INFINBAND      ? "INFB" :
               linkType == HSA_AMD_LINK_INFO_TYPE_XGMI           ? "XGMI" : "????",
               hopCount, outputToCsv ? "," : " |");
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1146
1147
1148
1149
1150
    HIP_CALL(hipDeviceGetPCIBusId(pciBusId, 20, deviceIdx));

    int numDeviceCUs = 0;
    HIP_CALL(hipDeviceGetAttribute(&numDeviceCUs, hipDeviceAttributeMultiprocessorCount, deviceIdx));

Gilbert Lee's avatar
Gilbert Lee committed
1151
    if (outputToCsv)
1152
      printf("%s,%d,%d,", pciBusId, numDeviceCUs, GetClosestNumaNode(deviceIdx));
Gilbert Lee's avatar
Gilbert Lee committed
1153
    else
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
    {
      printf(" %11s | %4d | %-12d |", pciBusId, numDeviceCUs, GetClosestNumaNode(deviceIdx));

      bool isFirst = true;
      for (auto x : dmaEngineIdsPerDevice[deviceIdx])
      {
        if (isFirst) isFirst = false; else printf(",");
        printf("%d", x);
      }
      printf("\n");
    }
Gilbert Lee's avatar
Gilbert Lee committed
1165
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1166
1167
1168
1169
1170
1171
1172
1173
1174

  // Check that large BAR is enabled on all GPUs
  for (int i = 0; i < numGpuDevices; i++) {
    int const deviceIdx = RemappedIndex(i, false);
    int isLargeBar = 0;
    HIP_CALL(hipDeviceGetAttribute(&isLargeBar, hipDeviceAttributeIsLargeBar, deviceIdx));
    if (!isLargeBar)
      printf("[WARN] Large BAR is not enabled for GPU %d in BIOS.  This may result in segfaults\n", i);
  }
1175
#endif
Gilbert Lee's avatar
Gilbert Lee committed
1176
1177
}

1178
void ParseMemType(EnvVars const& ev, std::string const& token,
gilbertlee-amd's avatar
gilbertlee-amd committed
1179
                  std::vector<MemType>& memTypes, std::vector<int>& memIndices)
Gilbert Lee's avatar
Gilbert Lee committed
1180
1181
{
  char typeChar;
gilbertlee-amd's avatar
gilbertlee-amd committed
1182
1183
  int offset = 0, devIndex, inc;
  bool found = false;
Gilbert Lee's avatar
Gilbert Lee committed
1184

gilbertlee-amd's avatar
gilbertlee-amd committed
1185
1186
1187
  memTypes.clear();
  memIndices.clear();
  while (sscanf(token.c_str() + offset, " %c %d%n", &typeChar, &devIndex, &inc) == 2)
Gilbert Lee's avatar
Gilbert Lee committed
1188
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1189
1190
1191
    offset += inc;
    MemType memType = CharToMemType(typeChar);

1192
    if (IsCpuType(memType) && (devIndex < 0 || devIndex >= ev.numCpuDevices))
Gilbert Lee's avatar
Gilbert Lee committed
1193
    {
1194
      printf("[ERROR] CPU index must be between 0 and %d (instead of %d)\n", ev.numCpuDevices-1, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1195
1196
      exit(1);
    }
1197
    if (IsGpuType(memType) && (devIndex < 0 || devIndex >= ev.numGpuDevices))
Gilbert Lee's avatar
Gilbert Lee committed
1198
    {
1199
      printf("[ERROR] GPU index must be between 0 and %d (instead of %d)\n", ev.numGpuDevices-1, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1200
1201
      exit(1);
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217

    found = true;
    if (memType != MEM_NULL)
    {
      memTypes.push_back(memType);
      memIndices.push_back(devIndex);
    }
  }
  if (!found)
  {
    printf("[ERROR] Unable to parse memory type token %s.  Expected one of %s followed by an index\n",
           token.c_str(), MemTypeStr);
    exit(1);
  }
}

1218
1219
void ParseExeType(EnvVars const& ev, std::string const& token,
                  ExeType &exeType, int& exeIndex, int& exeSubIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
1220
1221
{
  char typeChar;
1222
1223
1224
  exeSubIndex = -1;
  int numTokensParsed = sscanf(token.c_str(), " %c%d.%d", &typeChar, &exeIndex, &exeSubIndex);
  if (numTokensParsed < 2)
gilbertlee-amd's avatar
gilbertlee-amd committed
1225
1226
1227
1228
1229
1230
1231
  {
    printf("[ERROR] Unable to parse valid executor token (%s).  Exepected one of %s followed by an index\n",
           token.c_str(), ExeTypeStr);
    exit(1);
  }
  exeType = CharToExeType(typeChar);

1232
  if (IsCpuType(exeType) && (exeIndex < 0 || exeIndex >= ev.numCpuDevices))
gilbertlee-amd's avatar
gilbertlee-amd committed
1233
  {
1234
    printf("[ERROR] CPU index must be between 0 and %d (instead of %d)\n", ev.numCpuDevices-1, exeIndex);
gilbertlee-amd's avatar
gilbertlee-amd committed
1235
1236
    exit(1);
  }
1237
  if (IsGpuType(exeType) && (exeIndex < 0 || exeIndex >= ev.numGpuDevices))
gilbertlee-amd's avatar
gilbertlee-amd committed
1238
  {
1239
    printf("[ERROR] GPU index must be between 0 and %d (instead of %d)\n", ev.numGpuDevices-1, exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1240
1241
    exit(1);
  }
1242
1243
1244
1245
1246
1247
1248
1249
1250
  if (exeType == EXE_GPU_GFX && exeSubIndex != -1)
  {
    int const idx = RemappedIndex(exeIndex, false);
    if (ev.xccIdsPerDevice[idx].count(exeSubIndex) == 0)
    {
      printf("[ERROR] GPU %d does not have subIndex %d\n", exeIndex, exeSubIndex);
      exit(1);
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
1251
1252
}

Gilbert Lee's avatar
Gilbert Lee committed
1253
// Helper function to parse a list of Transfer definitions
1254
void ParseTransfers(EnvVars const& ev, char* line, std::vector<Transfer>& transfers)
Gilbert Lee's avatar
Gilbert Lee committed
1255
1256
1257
1258
1259
{
  // 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] = ' ';

Gilbert Lee's avatar
Gilbert Lee committed
1260
  transfers.clear();
Gilbert Lee's avatar
Gilbert Lee committed
1261

Gilbert Lee's avatar
Gilbert Lee committed
1262
  int numTransfers = 0;
Gilbert Lee's avatar
Gilbert Lee committed
1263
  std::istringstream iss(line);
Gilbert Lee's avatar
Gilbert Lee committed
1264
  iss >> numTransfers;
Gilbert Lee's avatar
Gilbert Lee committed
1265
1266
1267
1268
1269
  if (iss.fail()) return;

  std::string exeMem;
  std::string srcMem;
  std::string dstMem;
Gilbert Lee's avatar
Gilbert Lee committed
1270

gilbertlee-amd's avatar
gilbertlee-amd committed
1271
  // If numTransfers < 0, read 5-tuple (srcMem, exeMem, dstMem, #CUs, #Bytes)
Gilbert Lee's avatar
Gilbert Lee committed
1272
  // otherwise read triples (srcMem, exeMem, dstMem)
gilbertlee-amd's avatar
gilbertlee-amd committed
1273
  bool const advancedMode = (numTransfers < 0);
Gilbert Lee's avatar
Gilbert Lee committed
1274
1275
  numTransfers = abs(numTransfers);

gilbertlee-amd's avatar
gilbertlee-amd committed
1276
  int numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
1277
  if (!advancedMode)
Gilbert Lee's avatar
Gilbert Lee committed
1278
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1279
    iss >> numSubExecs;
1280
    if (numSubExecs < 0 || iss.fail())
Gilbert Lee's avatar
Gilbert Lee committed
1281
    {
1282
      printf("Parsing error: Number of blocks to use (%d) must be non-negative\n", numSubExecs);
Gilbert Lee's avatar
Gilbert Lee committed
1283
1284
1285
1286
      exit(1);
    }
  }

gilbertlee-amd's avatar
gilbertlee-amd committed
1287
  size_t numBytes = 0;
Gilbert Lee's avatar
Gilbert Lee committed
1288
1289
1290
  for (int i = 0; i < numTransfers; i++)
  {
    Transfer transfer;
gilbertlee-amd's avatar
gilbertlee-amd committed
1291
    transfer.numBytes = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
1292
    transfer.numBytesActual = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
1293
    if (!advancedMode)
Gilbert Lee's avatar
Gilbert Lee committed
1294
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
      iss >> srcMem >> exeMem >> dstMem;
      if (iss.fail())
      {
        printf("Parsing error: Unable to read valid Transfer %d (SRC EXE DST) triplet\n", i+1);
        exit(1);
      }
    }
    else
    {
      std::string numBytesToken;
gilbertlee-amd's avatar
gilbertlee-amd committed
1305
      iss >> srcMem >> exeMem >> dstMem >> numSubExecs >> numBytesToken;
gilbertlee-amd's avatar
gilbertlee-amd committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
      if (iss.fail())
      {
        printf("Parsing error: Unable to read valid Transfer %d (SRC EXE DST #CU #Bytes) tuple\n", i+1);
        exit(1);
      }
      if (sscanf(numBytesToken.c_str(), "%lu", &numBytes) != 1)
      {
        printf("Parsing error: '%s' is not a valid expression of numBytes for Transfer %d\n", numBytesToken.c_str(), i+1);
        exit(1);
      }
      char units = numBytesToken.back();
gilbertlee-amd's avatar
gilbertlee-amd committed
1317
      switch (toupper(units))
gilbertlee-amd's avatar
gilbertlee-amd committed
1318
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1319
1320
1321
      case 'K': numBytes *= 1024; break;
      case 'M': numBytes *= 1024*1024; break;
      case 'G': numBytes *= 1024*1024*1024; break;
gilbertlee-amd's avatar
gilbertlee-amd committed
1322
      }
Gilbert Lee's avatar
Gilbert Lee committed
1323
    }
Gilbert Lee's avatar
Gilbert Lee committed
1324

1325
1326
1327
    ParseMemType(ev, srcMem, transfer.srcType, transfer.srcIndex);
    ParseMemType(ev, dstMem, transfer.dstType, transfer.dstIndex);
    ParseExeType(ev, exeMem, transfer.exeType, transfer.exeIndex, transfer.exeSubIndex);
gilbertlee-amd's avatar
gilbertlee-amd committed
1328
1329
1330
1331
1332
1333
1334
1335
1336

    transfer.numSrcs = (int)transfer.srcType.size();
    transfer.numDsts = (int)transfer.dstType.size();
    if (transfer.numSrcs == 0 && transfer.numDsts == 0)
    {
      printf("[ERROR] Transfer must have at least one src or dst\n");
      exit(1);
    }

1337
    if (transfer.exeType == EXE_GPU_DMA && (transfer.numSrcs != 1 || transfer.numDsts != 1))
gilbertlee-amd's avatar
gilbertlee-amd committed
1338
    {
1339
      printf("[ERROR] GPU DMA executor can only be used for single source + single dst copies\n");
gilbertlee-amd's avatar
gilbertlee-amd committed
1340
1341
1342
1343
      exit(1);
    }

    transfer.numSubExecs = numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
1344
    transfer.numBytes = numBytes;
Gilbert Lee's avatar
Gilbert Lee committed
1345
    transfers.push_back(transfer);
Gilbert Lee's avatar
Gilbert Lee committed
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
  }
}

void EnablePeerAccess(int const deviceId, int const peerDeviceId)
{
  int canAccess;
  HIP_CALL(hipDeviceCanAccessPeer(&canAccess, deviceId, peerDeviceId));
  if (!canAccess)
  {
    printf("[ERROR] Unable to enable peer access from GPU devices %d to %d\n", peerDeviceId, deviceId);
    exit(1);
  }
  HIP_CALL(hipSetDevice(deviceId));
Gilbert Lee's avatar
Gilbert Lee committed
1359
1360
1361
1362
1363
1364
1365
  hipError_t error = hipDeviceEnablePeerAccess(peerDeviceId, 0);
  if (error != hipSuccess && error != hipErrorPeerAccessAlreadyEnabled)
  {
    printf("[ERROR] Unable to enable peer to peer access from %d to %d (%s)\n",
           deviceId, peerDeviceId, hipGetErrorString(error));
    exit(1);
  }
Gilbert Lee's avatar
Gilbert Lee committed
1366
1367
1368
1369
1370
1371
1372
1373
1374
}

void AllocateMemory(MemType memType, int devIndex, size_t numBytes, void** memPtr)
{
  if (numBytes == 0)
  {
    printf("[ERROR] Unable to allocate 0 bytes\n");
    exit(1);
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1375
  *memPtr = nullptr;
gilbertlee-amd's avatar
gilbertlee-amd committed
1376
  if (IsCpuType(memType))
Gilbert Lee's avatar
Gilbert Lee committed
1377
1378
  {
    // Set numa policy prior to call to hipHostMalloc
1379
    numa_set_preferred(devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1380
1381
1382
1383

    // Allocate host-pinned memory (should respect NUMA mem policy)
    if (memType == MEM_CPU_FINE)
    {
1384
1385
1386
1387
#if defined (__NVCC__)
      printf("[ERROR] Fine-grained CPU memory not supported on NVIDIA platform\n");
      exit(1);
#else
Gilbert Lee's avatar
Gilbert Lee committed
1388
      HIP_CALL(hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser));
1389
#endif
Gilbert Lee's avatar
Gilbert Lee committed
1390
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1391
    else if (memType == MEM_CPU)
Gilbert Lee's avatar
Gilbert Lee committed
1392
    {
1393
1394
1395
#if defined (__NVCC__)
      if (hipHostMalloc((void **)memPtr, numBytes, 0) != hipSuccess)
#else
1396
      if (hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser | hipHostMallocNonCoherent) != hipSuccess)
1397
#endif
1398
1399
1400
1401
      {
        printf("[ERROR] Unable to allocate non-coherent host memory on NUMA node %d\n", devIndex);
        exit(1);
      }
Gilbert Lee's avatar
Gilbert Lee committed
1402
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1403
1404
1405
1406
    else if (memType == MEM_CPU_UNPINNED)
    {
      *memPtr = numa_alloc_onnode(numBytes, devIndex);
    }
Gilbert Lee's avatar
Gilbert Lee committed
1407
1408

    // Check that the allocated pages are actually on the correct NUMA node
gilbertlee-amd's avatar
gilbertlee-amd committed
1409
    memset(*memPtr, 0, numBytes);
1410

gilbertlee-amd's avatar
gilbertlee-amd committed
1411
    CheckPages((char*)*memPtr, numBytes, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1412
1413

    // Reset to default numa mem policy
1414
    numa_set_preferred(-1);
Gilbert Lee's avatar
Gilbert Lee committed
1415
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1416
  else if (IsGpuType(memType))
Gilbert Lee's avatar
Gilbert Lee committed
1417
  {
1418
1419
1420
1421
1422
1423
1424
1425
    if (memType == MEM_GPU)
    {
      // Allocate GPU memory on appropriate device
      HIP_CALL(hipSetDevice(devIndex));
      HIP_CALL(hipMalloc((void**)memPtr, numBytes));
    }
    else if (memType == MEM_GPU_FINE)
    {
1426
#if defined (__NVCC__)
1427
1428
      printf("[ERROR] Fine-grained GPU memory not supported on NVIDIA platform\n");
      exit(1);
1429
#else
1430
      HIP_CALL(hipSetDevice(devIndex));
1431
      int flag = hipDeviceMallocUncached;
gilbertlee-amd's avatar
gilbertlee-amd committed
1432
      HIP_CALL(hipExtMallocWithFlags((void**)memPtr, numBytes, flag));
1433
#endif
1434
    }
1435
1436
1437
1438
1439
    else if (memType == MEM_MANAGED)
    {
      HIP_CALL(hipSetDevice(devIndex));
      HIP_CALL(hipMallocManaged((void**)memPtr, numBytes));
    }
1440
    HIP_CALL(hipMemset(*memPtr, 0, numBytes));
gilbertlee-amd's avatar
gilbertlee-amd committed
1441
    HIP_CALL(hipDeviceSynchronize());
Gilbert Lee's avatar
Gilbert Lee committed
1442
1443
1444
1445
1446
1447
1448
1449
  }
  else
  {
    printf("[ERROR] Unsupported memory type %d\n", memType);
    exit(1);
  }
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1450
void DeallocateMemory(MemType memType, void* memPtr, size_t const bytes)
Gilbert Lee's avatar
Gilbert Lee committed
1451
1452
1453
{
  if (memType == MEM_CPU || memType == MEM_CPU_FINE)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1454
1455
1456
1457
1458
    if (memPtr == nullptr)
    {
      printf("[ERROR] Attempting to free null CPU pointer for %lu bytes.  Skipping hipHostFree\n", bytes);
      return;
    }
Gilbert Lee's avatar
Gilbert Lee committed
1459
1460
    HIP_CALL(hipHostFree(memPtr));
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1461
1462
  else if (memType == MEM_CPU_UNPINNED)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1463
1464
1465
1466
1467
    if (memPtr == nullptr)
    {
      printf("[ERROR] Attempting to free null unpinned CPU pointer for %lu bytes.  Skipping numa_free\n", bytes);
      return;
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1468
1469
    numa_free(memPtr, bytes);
  }
Gilbert Lee's avatar
Gilbert Lee committed
1470
1471
  else if (memType == MEM_GPU || memType == MEM_GPU_FINE)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1472
1473
1474
1475
1476
    if (memPtr == nullptr)
    {
      printf("[ERROR] Attempting to free null GPU pointer for %lu bytes. Skipping hipFree\n", bytes);
      return;
    }
Gilbert Lee's avatar
Gilbert Lee committed
1477
1478
    HIP_CALL(hipFree(memPtr));
  }
1479
1480
1481
1482
1483
1484
1485
1486
1487
  else if (memType == MEM_MANAGED)
  {
    if (memPtr == nullptr)
    {
      printf("[ERROR] Attempting to free null managed pointer for %lu bytes. Skipping hipMFree\n", bytes);
      return;
    }
    HIP_CALL(hipFree(memPtr));
  }
Gilbert Lee's avatar
Gilbert Lee committed
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
}

void CheckPages(char* array, size_t numBytes, int targetId)
{
  unsigned long const pageSize = getpagesize();
  unsigned long 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)
  {
    printf("[ERROR] Unable to collect page info\n");
    exit(1);
  }

  size_t mistakeCount = 0;
  for (int i = 0; i < numPages; i++)
  {
    if (status[i] < 0)
    {
      printf("[ERROR] Unexpected page status %d for page %d\n", status[i], i);
      exit(1);
    }
    if (status[i] != targetId) mistakeCount++;
  }
  if (mistakeCount > 0)
  {
    printf("[ERROR] %lu out of %lu pages for memory allocation were not on NUMA node %d\n", mistakeCount, numPages, targetId);
    exit(1);
  }
}

1528
1529
uint32_t GetId(uint32_t hwId)
{
1530
1531
1532
#if defined(__NVCC_)
  return hwId;
#else
1533
  // Based on instinct-mi200-cdna2-instruction-set-architecture.pdf
1534
1535
1536
  int const shId = (hwId >> 12) &  1;
  int const cuId = (hwId >>  8) & 15;
  int const seId = (hwId >> 13) &  3;
1537
  return (shId << 5) + (cuId << 2) + seId;
1538
#endif
1539
1540
}

1541
void RunTransfer(EnvVars const& ev, int const iteration,
Gilbert Lee's avatar
Gilbert Lee committed
1542
                 ExecutorInfo& exeInfo, int const transferIdx)
Gilbert Lee's avatar
Gilbert Lee committed
1543
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1544
  Transfer* transfer = exeInfo.transfers[transferIdx];
Gilbert Lee's avatar
Gilbert Lee committed
1545

gilbertlee-amd's avatar
gilbertlee-amd committed
1546
  if (transfer->exeType == EXE_GPU_GFX)
Gilbert Lee's avatar
Gilbert Lee committed
1547
1548
  {
    // Switch to executing GPU
gilbertlee-amd's avatar
gilbertlee-amd committed
1549
    int const exeIndex = RemappedIndex(transfer->exeIndex, false);
Gilbert Lee's avatar
Gilbert Lee committed
1550
1551
    HIP_CALL(hipSetDevice(exeIndex));

Gilbert Lee's avatar
Gilbert Lee committed
1552
1553
1554
    hipStream_t& stream     = exeInfo.streams[transferIdx];
    hipEvent_t&  startEvent = exeInfo.startEvents[transferIdx];
    hipEvent_t&  stopEvent  = exeInfo.stopEvents[transferIdx];
Gilbert Lee's avatar
Gilbert Lee committed
1555

gilbertlee-amd's avatar
gilbertlee-amd committed
1556
1557
1558
1559
    // Figure out how many threadblocks to use.
    // In single stream mode, all the threadblocks for this GPU are launched
    // Otherwise, just launch the threadblocks associated with this single Transfer
    int const numBlocksToRun = ev.useSingleStream ? exeInfo.totalSubExecs : transfer->numSubExecs;
1560
    int const numXCCs = (ev.useXccFilter ? ev.xccIdsPerDevice[exeIndex].size() : 1);
1561
1562
    dim3 const gridSize(numXCCs, numBlocksToRun, 1);
    dim3 const blockSize(ev.gfxBlockSize, 1, 1);
1563

1564
1565
#if defined(__NVCC__)
    HIP_CALL(hipEventRecord(startEvent, stream));
1566
    GpuKernelTable[ev.gfxBlockSize/64 - 1][ev.gfxUnroll - 1]
1567
      <<<gridSize, blockSize, ev.sharedMemBytes, stream>>>(transfer->subExecParamGpuPtr, ev.gfxWaveOrder, ev.numSubIterations);
1568
1569
    HIP_CALL(hipEventRecord(stopEvent, stream));
#else
1570
1571
    hipExtLaunchKernelGGL(GpuKernelTable[ev.gfxBlockSize/64 - 1][ev.gfxUnroll - 1],
                          gridSize, blockSize,
gilbertlee-amd's avatar
gilbertlee-amd committed
1572
1573
                          ev.sharedMemBytes, stream,
                          startEvent, stopEvent,
1574
                          0, transfer->subExecParamGpuPtr, ev.gfxWaveOrder, ev.numSubIterations);
1575
#endif
Gilbert Lee's avatar
Gilbert Lee committed
1576
1577
    // Synchronize per iteration, unless in single sync mode, in which case
    // synchronize during last warmup / last actual iteration
Gilbert Lee's avatar
Gilbert Lee committed
1578
    HIP_CALL(hipStreamSynchronize(stream));
Gilbert Lee's avatar
Gilbert Lee committed
1579
1580
1581
1582

    if (iteration >= 0)
    {
      // Record GPU timing
Gilbert Lee's avatar
Gilbert Lee committed
1583
1584
      float gpuDeltaMsec;
      HIP_CALL(hipEventElapsedTime(&gpuDeltaMsec, startEvent, stopEvent));
Gilbert Lee's avatar
Gilbert Lee committed
1585

Gilbert Lee's avatar
Gilbert Lee committed
1586
1587
      if (ev.useSingleStream)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1588
        // Figure out individual timings for Transfers that were all launched together
gilbertlee-amd's avatar
gilbertlee-amd committed
1589
        for (Transfer* currTransfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
1590
        {
1591
1592
1593
          long long minStartCycle = std::numeric_limits<long long>::max();
          long long maxStopCycle  = std::numeric_limits<long long>::min();

gilbertlee-amd's avatar
gilbertlee-amd committed
1594
          std::set<std::pair<int,int>> CUs;
1595
          for (auto subExecIdx : currTransfer->subExecIdx)
Gilbert Lee's avatar
Gilbert Lee committed
1596
          {
1597
1598
1599
            minStartCycle = std::min(minStartCycle, exeInfo.subExecParamGpu[subExecIdx].startCycle);
            maxStopCycle  = std::max(maxStopCycle,  exeInfo.subExecParamGpu[subExecIdx].stopCycle);
            if (ev.showIterations)
gilbertlee-amd's avatar
gilbertlee-amd committed
1600
1601
              CUs.insert(std::make_pair(exeInfo.subExecParamGpu[subExecIdx].xccId,
                                        GetId(exeInfo.subExecParamGpu[subExecIdx].hwId)));
Gilbert Lee's avatar
Gilbert Lee committed
1602
          }
1603
          int const wallClockRate = ev.wallClockPerDeviceMhz[exeIndex];
Gilbert Lee's avatar
Gilbert Lee committed
1604
          double iterationTimeMs = (maxStopCycle - minStartCycle) / (double)(wallClockRate);
gilbertlee-amd's avatar
gilbertlee-amd committed
1605
          currTransfer->transferTime += iterationTimeMs;
1606
          if (ev.showIterations)
1607
          {
1608
            currTransfer->perIterationTime.push_back(iterationTimeMs);
1609
1610
            currTransfer->perIterationCUs.push_back(CUs);
          }
Gilbert Lee's avatar
Gilbert Lee committed
1611
        }
Gilbert Lee's avatar
Gilbert Lee committed
1612
1613
1614
1615
        exeInfo.totalTime += gpuDeltaMsec;
      }
      else
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1616
        transfer->transferTime += gpuDeltaMsec;
1617
        if (ev.showIterations)
1618
        {
1619
          transfer->perIterationTime.push_back(gpuDeltaMsec);
gilbertlee-amd's avatar
gilbertlee-amd committed
1620
          std::set<std::pair<int,int>> CUs;
1621
          for (int i = 0; i < transfer->numSubExecs; i++)
gilbertlee-amd's avatar
gilbertlee-amd committed
1622
1623
            CUs.insert(std::make_pair(transfer->subExecParamGpuPtr[i].xccId,
                                      GetId(transfer->subExecParamGpuPtr[i].hwId)));
1624
1625
          transfer->perIterationCUs.push_back(CUs);
        }
Gilbert Lee's avatar
Gilbert Lee committed
1626
1627
1628
      }
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1629
1630
1631
1632
  else if (transfer->exeType == EXE_GPU_DMA)
  {
    int const exeIndex = RemappedIndex(transfer->exeIndex, false);

gilbertlee-amd's avatar
gilbertlee-amd committed
1633
1634
    int subIterations = 0;
    if (transfer->exeSubIndex == -1 && !ev.useHsaDma) {
1635
1636
1637
1638
1639
      // Switch to executing GPU
      HIP_CALL(hipSetDevice(exeIndex));
      hipStream_t& stream     = exeInfo.streams[transferIdx];
      hipEvent_t&  startEvent = exeInfo.startEvents[transferIdx];
      hipEvent_t&  stopEvent  = exeInfo.stopEvents[transferIdx];
gilbertlee-amd's avatar
gilbertlee-amd committed
1640

1641
      HIP_CALL(hipEventRecord(startEvent, stream));
1642
      do {
1643
1644
1645
        HIP_CALL(hipMemcpyAsync(transfer->dstMem[0], transfer->srcMem[0],
                                transfer->numBytesActual, hipMemcpyDefault,
                                stream));
gilbertlee-amd's avatar
gilbertlee-amd committed
1646
      } while (++subIterations != ev.numSubIterations);
1647
1648
1649
      HIP_CALL(hipEventRecord(stopEvent, stream));
      HIP_CALL(hipStreamSynchronize(stream));

gilbertlee-amd's avatar
gilbertlee-amd committed
1650
1651
      // Record time based on HIP events
      if (iteration >= 0) {
1652
1653
1654
1655
1656
1657
        float gpuDeltaMsec;
        HIP_CALL(hipEventElapsedTime(&gpuDeltaMsec, startEvent, stopEvent));
        transfer->transferTime += gpuDeltaMsec;
        if (ev.showIterations)
          transfer->perIterationTime.push_back(gpuDeltaMsec);
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
1658
    } else {
1659
1660
1661
1662
#if defined(__NVCC__)
      printf("[ERROR] CUDA does not support targeting specific DMA engines\n");
      exit(1);
#else
gilbertlee-amd's avatar
gilbertlee-amd committed
1663
      // Use hsa_amd_memory copy (either targeted or untargeted)
1664
      auto cpuStart = std::chrono::high_resolution_clock::now();
1665

1666
1667
1668
      do {
        // Atomically set signal to 1
        HSA_CALL(hsa_signal_store_screlease(transfer->signal, 1));
gilbertlee-amd's avatar
gilbertlee-amd committed
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
        if (ev.useHsaDma) {
          HSA_CALL(hsa_amd_memory_async_copy(transfer->dstMem[0], transfer->dstAgent,
                                             transfer->srcMem[0], transfer->srcAgent,
                                             transfer->numBytesActual, 0, NULL,
                                             transfer->signal));
        } else {
          HSA_CALL(hsa_amd_memory_async_copy_on_engine(transfer->dstMem[0], transfer->dstAgent,
                                                       transfer->srcMem[0], transfer->srcAgent,
                                                       transfer->numBytesActual, 0, NULL,
                                                       transfer->signal,
                                                       transfer->sdmaEngineId, true));
        }
1681
1682
1683
1684
1685
        // Wait for SDMA transfer to complete
        while(hsa_signal_wait_scacquire(transfer->signal,
                                        HSA_SIGNAL_CONDITION_LT, 1, UINT64_MAX,
                                        HSA_WAIT_STATE_ACTIVE) >= 1);
      } while (++subIterations < ev.numSubIterations);
1686

gilbertlee-amd's avatar
gilbertlee-amd committed
1687
      if (iteration >= 0) {
1688
1689
1690
1691
1692
1693
1694
1695
        // Record GPU timing
        auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
        double deltaMsec = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0;
        transfer->transferTime += deltaMsec;
        if (ev.showIterations)
          transfer->perIterationTime.push_back(deltaMsec);
      }
#endif
gilbertlee-amd's avatar
gilbertlee-amd committed
1696
1697
1698
    }
  }
  else if (transfer->exeType == EXE_CPU) // CPU execution agent
Gilbert Lee's avatar
Gilbert Lee committed
1699
1700
  {
    // Force this thread and all child threads onto correct NUMA node
gilbertlee-amd's avatar
gilbertlee-amd committed
1701
    int const exeIndex = RemappedIndex(transfer->exeIndex, true);
1702
    if (numa_run_on_node(exeIndex))
Gilbert Lee's avatar
Gilbert Lee committed
1703
    {
1704
      printf("[ERROR] Unable to set CPU to NUMA node %d\n", exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1705
1706
1707
1708
1709
      exit(1);
    }

    std::vector<std::thread> childThreads;

1710
    int subIteration = 0;
Gilbert Lee's avatar
Gilbert Lee committed
1711
    auto cpuStart = std::chrono::high_resolution_clock::now();
1712
1713
1714
1715
    do {
      // Launch each subExecutor in child-threads to perform memcopies
      for (int i = 0; i < transfer->numSubExecs; ++i)
        childThreads.push_back(std::thread(CpuReduceKernel, std::ref(transfer->subExecParam[i])));
Gilbert Lee's avatar
Gilbert Lee committed
1716

1717
1718
1719
1720
1721
      // Wait for child-threads to finish
      for (int i = 0; i < transfer->numSubExecs; ++i)
        childThreads[i].join();
      childThreads.clear();
    } while (++subIteration != ev.numSubIterations);
Gilbert Lee's avatar
Gilbert Lee committed
1722
1723
1724
1725
1726

    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;

    // Record time if not a warmup iteration
    if (iteration >= 0)
1727
1728
1729
1730
1731
1732
    {
      double const delta = (std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0);
      transfer->transferTime += delta;
      if (ev.showIterations)
        transfer->perIterationTime.push_back(delta);
    }
Gilbert Lee's avatar
Gilbert Lee committed
1733
1734
1735
  }
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1736
void RunPeerToPeerBenchmarks(EnvVars const& ev, size_t N)
Gilbert Lee's avatar
Gilbert Lee committed
1737
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1738
1739
  ev.DisplayP2PBenchmarkEnvVars();

1740
1741
1742
  char const separator = ev.outputToCsv ? ',' : ' ';
  printf("Bytes Per Direction%c%lu\n", separator, N * sizeof(float));

Gilbert Lee's avatar
Gilbert Lee committed
1743
  // Collect the number of available CPUs/GPUs on this machine
gilbertlee-amd's avatar
gilbertlee-amd committed
1744
1745
  int const numCpus    = ev.numCpuDevices;
  int const numGpus    = ev.numGpuDevices;
Gilbert Lee's avatar
Gilbert Lee committed
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
  int const numDevices = numCpus + numGpus;

  // Enable peer to peer for each GPU
  for (int i = 0; i < numGpus; i++)
    for (int j = 0; j < numGpus; j++)
      if (i != j) EnablePeerAccess(i, j);

  // Perform unidirectional / bidirectional
  for (int isBidirectional = 0; isBidirectional <= 1; isBidirectional++)
  {
1756
1757
1758
    if (ev.p2pMode == 1 && isBidirectional == 1 ||
        ev.p2pMode == 2 && isBidirectional == 0) continue;

1759
1760
1761
1762
1763
    printf("%sdirectional copy peak bandwidth GB/s [%s read / %s write] (GPU-Executor: %s)\n", isBidirectional ? "Bi" : "Uni",
           ev.useRemoteRead ? "Remote" : "Local",
           ev.useRemoteRead ? "Local" : "Remote",
           ev.useDmaCopy    ? "DMA"   : "GFX");

Gilbert Lee's avatar
Gilbert Lee committed
1764
    // Print header
1765
    if (isBidirectional)
Gilbert Lee's avatar
Gilbert Lee committed
1766
    {
1767
1768
1769
1770
1771
1772
      printf("%12s", "SRC\\DST");
    }
    else
    {
      if (ev.useRemoteRead)
        printf("%12s", "SRC\\EXE+DST");
1773
      else
1774
1775
1776
1777
1778
1779
1780
1781
        printf("%12s", "SRC+EXE\\DST");
    }
    if (ev.outputToCsv) printf(",");
    for (int i = 0; i < numCpus; i++)
    {
      printf("%7s %02d", "CPU", i);
      if (ev.outputToCsv) printf(",");
    }
1782
    if (numCpus > 0) printf("   ");
1783
1784
1785
1786
    for (int i = 0; i < numGpus; i++)
    {
      printf("%7s %02d", "GPU", i);
      if (ev.outputToCsv) printf(",");
Gilbert Lee's avatar
Gilbert Lee committed
1787
    }
1788
1789
    printf("\n");

1790
1791
1792
    double avgBwSum[2][2] = {};
    int    avgCount[2][2] = {};

1793
    ExeType const gpuExeType = ev.useDmaCopy ? EXE_GPU_DMA : EXE_GPU_GFX;
Gilbert Lee's avatar
Gilbert Lee committed
1794
1795
1796
    // Loop over all possible src/dst pairs
    for (int src = 0; src < numDevices; src++)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
1797
1798
      MemType const srcType  = (src < numCpus ? MEM_CPU : MEM_GPU);
      int     const srcIndex = (srcType == MEM_CPU ? src : src - numCpus);
1799
1800
1801
      MemType const srcTypeActual = ((ev.useFineGrain && srcType == MEM_CPU) ? MEM_CPU_FINE :
                                     (ev.useFineGrain && srcType == MEM_GPU) ? MEM_GPU_FINE :
                                                                               srcType);
1802
1803
1804
1805
      std::vector<std::vector<double>> avgBandwidth(isBidirectional + 1);
      std::vector<std::vector<double>> minBandwidth(isBidirectional + 1);
      std::vector<std::vector<double>> maxBandwidth(isBidirectional + 1);
      std::vector<std::vector<double>> stdDev(isBidirectional + 1);
gilbertlee-amd's avatar
gilbertlee-amd committed
1806

1807
      if (src == numCpus && src != 0) printf("\n");
Gilbert Lee's avatar
Gilbert Lee committed
1808
1809
      for (int dst = 0; dst < numDevices; dst++)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1810
1811
        MemType const dstType  = (dst < numCpus ? MEM_CPU : MEM_GPU);
        int     const dstIndex = (dstType == MEM_CPU ? dst : dst - numCpus);
1812
1813
1814
        MemType const dstTypeActual = ((ev.useFineGrain && dstType == MEM_CPU) ? MEM_CPU_FINE :
                                       (ev.useFineGrain && dstType == MEM_GPU) ? MEM_GPU_FINE :
                                                                                 dstType);
1815
1816
1817
1818
1819
        // Prepare Transfers
        std::vector<Transfer> transfers(isBidirectional + 1);

        // SRC -> DST
        transfers[0].numBytes = N * sizeof(float);
1820
1821
        transfers[0].srcType.push_back(srcTypeActual);
        transfers[0].dstType.push_back(dstTypeActual);
1822
1823
1824
1825
1826
        transfers[0].srcIndex.push_back(srcIndex);
        transfers[0].dstIndex.push_back(dstIndex);
        transfers[0].numSrcs = transfers[0].numDsts = 1;
        transfers[0].exeType = IsGpuType(ev.useRemoteRead ? dstType : srcType) ? gpuExeType : EXE_CPU;
        transfers[0].exeIndex = (ev.useRemoteRead ? dstIndex : srcIndex);
1827
        transfers[0].exeSubIndex = -1;
1828
1829
1830
1831
1832
1833
1834
        transfers[0].numSubExecs = IsGpuType(transfers[0].exeType) ? ev.numGpuSubExecs : ev.numCpuSubExecs;

        // DST -> SRC
        if (isBidirectional)
        {
          transfers[1].numBytes = N * sizeof(float);
          transfers[1].numSrcs = transfers[1].numDsts = 1;
1835
1836
          transfers[1].srcType.push_back(dstTypeActual);
          transfers[1].dstType.push_back(srcTypeActual);
1837
1838
1839
1840
          transfers[1].srcIndex.push_back(dstIndex);
          transfers[1].dstIndex.push_back(srcIndex);
          transfers[1].exeType = IsGpuType(ev.useRemoteRead ? srcType : dstType) ? gpuExeType : EXE_CPU;
          transfers[1].exeIndex = (ev.useRemoteRead ? srcIndex : dstIndex);
1841
          transfers[1].exeSubIndex = -1;
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
          transfers[1].numSubExecs = IsGpuType(transfers[1].exeType) ? ev.numGpuSubExecs : ev.numCpuSubExecs;
        }

        bool skipTest = false;

        // Abort if executing on NUMA node with no CPUs
        for (int i = 0; i <= isBidirectional; i++)
        {
          if (transfers[i].exeType == EXE_CPU && ev.numCpusPerNuma[transfers[i].exeIndex] == 0)
          {
            skipTest = true;
            break;
          }

#if defined(__NVCC__)
          // NVIDIA platform cannot access GPU memory directly from CPU executors
          if (transfers[i].exeType == EXE_CPU && (IsGpuType(srcType) || IsGpuType(dstType)))
          {
            skipTest = true;
            break;
          }
#endif
        }

        if (isBidirectional && srcType == dstType && srcIndex == dstIndex) skipTest = true;

        if (!skipTest)
        {
          ExecuteTransfers(ev, 0, N, transfers, false);

          for (int dir = 0; dir <= isBidirectional; dir++)
          {
1874
            double const avgTime = transfers[dir].transferTime;
1875
1876
1877
            double const avgBw   = (transfers[dir].numBytesActual / 1.0E9) / avgTime * 1000.0f;
            avgBandwidth[dir].push_back(avgBw);

1878
1879
1880
1881
1882
1883
            if (!(srcType == dstType && srcIndex == dstIndex))
            {
              avgBwSum[srcType][dstType] += avgBw;
              avgCount[srcType][dstType]++;
            }

1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
            if (ev.showIterations)
            {
              double minTime = transfers[dir].perIterationTime[0];
              double maxTime = transfers[dir].perIterationTime[0];
              double varSum  = 0;
              for (int i = 0; i < transfers[dir].perIterationTime.size(); i++)
              {
                minTime = std::min(minTime, transfers[dir].perIterationTime[i]);
                maxTime = std::max(maxTime, transfers[dir].perIterationTime[i]);
                double const bw  = (transfers[dir].numBytesActual / 1.0E9) / transfers[dir].perIterationTime[i] * 1000.0f;
                double const delta = (avgBw - bw);
                varSum += delta * delta;
              }
              double const minBw = (transfers[dir].numBytesActual / 1.0E9) / maxTime * 1000.0f;
              double const maxBw = (transfers[dir].numBytesActual / 1.0E9) / minTime * 1000.0f;
              double const stdev = sqrt(varSum / transfers[dir].perIterationTime.size());
              minBandwidth[dir].push_back(minBw);
              maxBandwidth[dir].push_back(maxBw);
              stdDev[dir].push_back(stdev);
            }
          }
        }
        else
Gilbert Lee's avatar
Gilbert Lee committed
1907
        {
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
          for (int dir = 0; dir <= isBidirectional; dir++)
          {
            avgBandwidth[dir].push_back(0);
            minBandwidth[dir].push_back(0);
            maxBandwidth[dir].push_back(0);
            stdDev[dir].push_back(-1.0);
          }
        }
      }

      for (int dir = 0; dir <= isBidirectional; dir++)
      {
        printf("%5s %02d %3s", (srcType == MEM_CPU) ? "CPU" : "GPU", srcIndex, dir ? "<- " : " ->");
        if (ev.outputToCsv) printf(",");

        for (int dst = 0; dst < numDevices; dst++)
        {
1925
          if (dst == numCpus && dst != 0) printf("   ");
1926
1927
1928
          double const avgBw = avgBandwidth[dir][dst];

          if (avgBw == 0.0)
Gilbert Lee's avatar
Gilbert Lee committed
1929
1930
            printf("%10s", "N/A");
          else
1931
1932
            printf("%10.2f", avgBw);
          if (ev.outputToCsv) printf(",");
Gilbert Lee's avatar
Gilbert Lee committed
1933
        }
1934
1935
1936
        printf("\n");

        if (ev.showIterations)
Gilbert Lee's avatar
Gilbert Lee committed
1937
        {
1938
1939
1940
1941
1942
1943
          // minBw
          printf("%5s %02d %3s", (srcType == MEM_CPU) ? "CPU" : "GPU", srcIndex, "min");
          if (ev.outputToCsv) printf(",");
          for (int i = 0; i < numDevices; i++)
          {
            double const minBw = minBandwidth[dir][i];
1944
            if (i == numCpus && i != 0) printf("   ");
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
            if (minBw == 0.0)
              printf("%10s", "N/A");
            else
              printf("%10.2f", minBw);
            if (ev.outputToCsv) printf(",");
          }
          printf("\n");

          // maxBw
          printf("%5s %02d %3s", (srcType == MEM_CPU) ? "CPU" : "GPU", srcIndex, "max");
          if (ev.outputToCsv) printf(",");
          for (int i = 0; i < numDevices; i++)
          {
            double const maxBw = maxBandwidth[dir][i];
1959
            if (i == numCpus && i != 0) printf("   ");
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
            if (maxBw == 0.0)
              printf("%10s", "N/A");
            else
              printf("%10.2f", maxBw);
            if (ev.outputToCsv) printf(",");
          }
          printf("\n");

          // stddev
          printf("%5s %02d %3s", (srcType == MEM_CPU) ? "CPU" : "GPU", srcIndex, " sd");
          if (ev.outputToCsv) printf(",");
          for (int i = 0; i < numDevices; i++)
          {
            double const sd = stdDev[dir][i];
1974
            if (i == numCpus && i != 0) printf("   ");
1975
1976
1977
1978
1979
1980
1981
            if (sd == -1.0)
              printf("%10s", "N/A");
            else
              printf("%10.2f", sd);
            if (ev.outputToCsv) printf(",");
          }
          printf("\n");
Gilbert Lee's avatar
Gilbert Lee committed
1982
1983
1984
        }
        fflush(stdout);
      }
1985
1986
1987
1988
1989
1990
1991
1992

      if (isBidirectional)
      {
        printf("%5s %02d %3s", (srcType == MEM_CPU) ? "CPU" : "GPU", srcIndex, "<->");
        if (ev.outputToCsv) printf(",");
        for (int dst = 0; dst < numDevices; dst++)
        {
          double const sumBw = avgBandwidth[0][dst] + avgBandwidth[1][dst];
1993
          if (dst == numCpus && dst != 0) printf("   ");
1994
1995
1996
1997
1998
1999
          if (sumBw == 0.0)
            printf("%10s", "N/A");
          else
            printf("%10.2f", sumBw);
          if (ev.outputToCsv) printf(",");
        }
2000
2001
        printf("\n");
        if (src < numDevices - 1) printf("\n");
2002
      }
Gilbert Lee's avatar
Gilbert Lee committed
2003
    }
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023

    if (!ev.outputToCsv)
    {
      printf("                         ");
      for (int srcType : {MEM_CPU, MEM_GPU})
        for (int dstType : {MEM_CPU, MEM_GPU})
          printf("  %cPU->%cPU", srcType == MEM_CPU ? 'C' : 'G', dstType == MEM_CPU ? 'C' : 'G');
      printf("\n");

      printf("Averages (During %s):",  isBidirectional ? " BiDir" : "UniDir");
      for (int srcType : {MEM_CPU, MEM_GPU})
        for (int dstType : {MEM_CPU, MEM_GPU})
        {
          if (avgCount[srcType][dstType])
            printf("%10.2f", avgBwSum[srcType][dstType] / avgCount[srcType][dstType]);
          else
            printf("%10s", "N/A");
        }
      printf("\n\n");
    }
Gilbert Lee's avatar
Gilbert Lee committed
2024
2025
2026
  }
}

2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
void RunScalingBenchmark(EnvVars const& ev, size_t N, int const exeIndex, int const maxSubExecs)
{
  ev.DisplayEnvVars();

  // Collect the number of available CPUs/GPUs on this machine
  int const numCpus    = ev.numCpuDevices;
  int const numGpus    = ev.numGpuDevices;
  int const numDevices = numCpus + numGpus;

  // Enable peer to peer for each GPU
  for (int i = 0; i < numGpus; i++)
    for (int j = 0; j < numGpus; j++)
      if (i != j) EnablePeerAccess(i, j);

  char separator = (ev.outputToCsv ? ',' : ' ');

  std::vector<Transfer> transfers(1);
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
  Transfer& t = transfers[0];
  t.numBytes = N * sizeof(float);
  t.numSrcs  = 1;
  t.numDsts  = 1;
  t.exeType  = EXE_GPU_GFX;
  t.exeIndex = exeIndex;
  t.exeSubIndex = -1;
  t.srcType.resize(1, MEM_GPU);
  t.dstType.resize(1, MEM_GPU);
  t.srcIndex.resize(1);
  t.dstIndex.resize(1);
2055
2056
2057

  printf("GPU-GFX Scaling benchmark:\n");
  printf("==========================\n");
2058
  printf("- Copying %lu bytes from GPU %d to other devices\n", t.numBytes, exeIndex);
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
  printf("- All numbers reported as GB/sec\n\n");

  printf("NumCUs");
  for (int i = 0; i < numDevices; i++)
    printf("%c  %s%02d     ", separator, i < numCpus ? "CPU" : "GPU", i < numCpus ? i : i - numCpus);
  printf("\n");

  std::vector<std::pair<double, int>> bestResult(numDevices);
  for (int numSubExec = 1; numSubExec <= maxSubExecs; numSubExec++)
  {
2069
    t.numSubExecs = numSubExec;
2070
2071
2072
2073
    printf("%4d  ", numSubExec);

    for (int i = 0; i < numDevices; i++)
    {
2074
2075
      t.dstType[0]  = i < numCpus ? MEM_CPU : MEM_GPU;
      t.dstIndex[0] = i < numCpus ? i : i - numCpus;
2076
2077

      ExecuteTransfers(ev, 0, N, transfers, false);
2078
      printf("%c%7.2f     ", separator, t.transferBandwidth);
2079

2080
      if (t.transferBandwidth > bestResult[i].first)
2081
      {
2082
        bestResult[i].first  = t.transferBandwidth;
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
        bestResult[i].second = numSubExec;
      }
    }
    printf("\n");
  }

  printf(" Best ");
  for (int i = 0; i < numDevices; i++)
  {
    printf("%c%7.2f(%3d)", separator, bestResult[i].first, bestResult[i].second);
  }
  printf("\n");
}

gilbertlee-amd's avatar
gilbertlee-amd committed
2097
2098
void RunAllToAllBenchmark(EnvVars const& ev, size_t const numBytesPerTransfer, int const numSubExecs)
{
2099
  ev.DisplayA2AEnvVars();
gilbertlee-amd's avatar
gilbertlee-amd committed
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113

  // Collect the number of GPU devices to use
  int const numGpus = ev.numGpuDevices;

  // Enable peer to peer for each GPU
  for (int i = 0; i < numGpus; i++)
    for (int j = 0; j < numGpus; j++)
      if (i != j) EnablePeerAccess(i, j);

  char separator = (ev.outputToCsv ? ',' : ' ');

  Transfer transfer;
  transfer.numBytes    = numBytesPerTransfer;
  transfer.numSubExecs = numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
2114
2115
  transfer.numSrcs     = ev.a2aMode == 2 ? 0 : 1;
  transfer.numDsts     = ev.a2aMode == 1 ? 0 : 1;
gilbertlee-amd's avatar
gilbertlee-amd committed
2116
  transfer.exeType     = (ev.useDmaCopy && transfer.numSrcs == 1 && transfer.numDsts == 1) ? EXE_GPU_DMA : EXE_GPU_GFX;
2117
  transfer.exeSubIndex = -1;
2118
2119
  transfer.srcType.resize(1, ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
  transfer.dstType.resize(1, ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
gilbertlee-amd's avatar
gilbertlee-amd committed
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
  transfer.srcIndex.resize(1);
  transfer.dstIndex.resize(1);

  std::vector<Transfer> transfers;
  for (int i = 0; i < numGpus; i++)
  {
    transfer.srcIndex[0] = i;
    for (int j = 0; j < numGpus; j++)
    {
      transfer.dstIndex[0] = j;
2130
2131
      transfer.exeIndex    = (ev.useRemoteRead ? j : i);

2132
2133
2134
2135
      if (ev.a2aDirect)
      {
        if (i == j) continue;

2136
#if !defined(__NVCC__)
2137
2138
2139
2140
2141
2142
2143
        uint32_t linkType, hopCount;
        HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(i, false),
                                              RemappedIndex(j, false),
                                              &linkType, &hopCount));
        if (hopCount != 1) continue;
#endif
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
2144
2145
2146
2147
2148
2149
      transfers.push_back(transfer);
    }
  }

  printf("GPU-GFX All-To-All benchmark:\n");
  printf("==========================\n");
2150
2151
2152
  printf("- Copying %lu bytes between %s pairs of GPUs using %d CUs (%lu Transfers)\n",
         numBytesPerTransfer, ev.a2aDirect ? "directly connected" : "all", numSubExecs, transfers.size());
  if (transfers.size() == 0) return;
gilbertlee-amd's avatar
gilbertlee-amd committed
2153
2154

  double totalBandwidthCpu = 0;
2155
  ExecuteTransfers(ev, 0, numBytesPerTransfer / sizeof(float), transfers, !ev.hideEnv, &totalBandwidthCpu);
gilbertlee-amd's avatar
gilbertlee-amd committed
2156
2157
2158

  printf("\nSummary:\n");
  printf("==========================================================\n");
2159
  printf("SRC\\DST ");
gilbertlee-amd's avatar
gilbertlee-amd committed
2160
  for (int dst = 0; dst < numGpus; dst++)
2161
2162
    printf("%cGPU %02d    ", separator, dst);
  printf("   %cSTotal     %cActual\n", separator, separator);
2163
2164
2165
2166
2167
2168
2169

  std::map<std::pair<int, int>, int> reIndex;
  for (int i = 0; i < transfers.size(); i++)
  {
    Transfer const& t = transfers[i];
    reIndex[std::make_pair(t.srcIndex[0], t.dstIndex[0])] = i;
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
2170

2171
  double totalBandwidthGpu = 0.0;
2172
2173
  double minExecutorBandwidth = std::numeric_limits<double>::max();
  double maxExecutorBandwidth = 0.0;
2174
  std::vector<double> colTotalBandwidth(numGpus+1, 0.0);
gilbertlee-amd's avatar
gilbertlee-amd committed
2175
2176
  for (int src = 0; src < numGpus; src++)
  {
2177
    double rowTotalBandwidth = 0;
2178
    double executorBandwidth = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
2179
2180
2181
    printf("GPU %02d", src);
    for (int dst = 0; dst < numGpus; dst++)
    {
2182
2183
2184
      if (reIndex.count(std::make_pair(src, dst)))
      {
        Transfer const& transfer = transfers[reIndex[std::make_pair(src,dst)]];
2185
2186
2187
2188
2189
        colTotalBandwidth[dst]  += transfer.transferBandwidth;
        rowTotalBandwidth       += transfer.transferBandwidth;
        totalBandwidthGpu       += transfer.transferBandwidth;
        executorBandwidth        = std::max(executorBandwidth, transfer.executorBandwidth);
        printf("%c%8.3f  ", separator, transfer.transferBandwidth);
2190
2191
2192
      }
      else
      {
2193
        printf("%c%8s  ", separator, "N/A");
2194
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
2195
    }
2196
2197
2198
    printf("   %c%8.3f   %c%8.3f\n", separator, rowTotalBandwidth, separator, executorBandwidth);
    minExecutorBandwidth = std::min(minExecutorBandwidth, executorBandwidth);
    maxExecutorBandwidth = std::max(maxExecutorBandwidth, executorBandwidth);
2199
    colTotalBandwidth[numGpus] += rowTotalBandwidth;
gilbertlee-amd's avatar
gilbertlee-amd committed
2200
  }
2201
2202
2203
  printf("\nRTotal");
  for (int dst = 0; dst < numGpus; dst++)
  {
2204
    printf("%c%8.3f  ", separator, colTotalBandwidth[dst]);
2205
  }
2206
2207
  printf("   %c%8.3f   %c%8.3f   %c%8.3f\n", separator, colTotalBandwidth[numGpus],
         separator, minExecutorBandwidth, separator, maxExecutorBandwidth);
2208
2209
  printf("\n");

2210
2211
2212
  printf("Average   bandwidth (GPU Timed): %8.3f GB/s\n", totalBandwidthGpu / transfers.size());
  printf("Aggregate bandwidth (GPU Timed): %8.3f GB/s\n", totalBandwidthGpu);
  printf("Aggregate bandwidth (CPU Timed): %8.3f GB/s\n", totalBandwidthCpu);
gilbertlee-amd's avatar
gilbertlee-amd committed
2213
2214
}

gilbertlee-amd's avatar
gilbertlee-amd committed
2215
void Transfer::PrepareSubExecParams(EnvVars const& ev)
Gilbert Lee's avatar
Gilbert Lee committed
2216
{
gilbertlee-amd's avatar
gilbertlee-amd committed
2217
2218
2219
2220
2221
2222
2223
  // 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 BLOCK_BYTES bytes,
  //   except the very last one, for alignment reasons
  size_t const N              = this->numBytesActual / sizeof(float);
  int    const initOffset     = ev.byteOffset / sizeof(float);
  int    const targetMultiple = ev.blockBytes / sizeof(float);
Gilbert Lee's avatar
Gilbert Lee committed
2224

gilbertlee-amd's avatar
gilbertlee-amd committed
2225
  // In some cases, there may not be enough data for all subExectors
2226
  int const maxSubExecToUse = std::min((size_t)(N + targetMultiple - 1) / targetMultiple, (size_t)this->numSubExecs);
gilbertlee-amd's avatar
gilbertlee-amd committed
2227
2228
  this->subExecParam.clear();
  this->subExecParam.resize(this->numSubExecs);
Gilbert Lee's avatar
Gilbert Lee committed
2229
2230

  size_t assigned = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
2231
2232
  for (int i = 0; i < this->numSubExecs; ++i)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2233
2234
2235
    SubExecParam& p  = this->subExecParam[i];
    p.numSrcs        = this->numSrcs;
    p.numDsts        = this->numDsts;
gilbertlee-amd's avatar
gilbertlee-amd committed
2236

gilbertlee-amd's avatar
gilbertlee-amd committed
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
    if (ev.gfxSingleTeam && this->exeType == EXE_GPU_GFX)
    {
      p.N           = N;
      p.teamSize    = this->numSubExecs;
      p.teamIdx     = i;
      for (int iSrc = 0; iSrc < this->numSrcs; ++iSrc) p.src[iSrc] = this->srcMem[iSrc] + initOffset;
      for (int iDst = 0; iDst < this->numDsts; ++iDst) p.dst[iDst] = this->dstMem[iDst] + initOffset;
    }
    else
    {
      int    const subExecLeft = std::max(0, maxSubExecToUse - i);
      size_t const leftover    = N - assigned;
      size_t const roundedN    = (leftover + targetMultiple - 1) / targetMultiple;
gilbertlee-amd's avatar
gilbertlee-amd committed
2250

gilbertlee-amd's avatar
gilbertlee-amd committed
2251
2252
2253
2254
2255
2256
2257
2258
      p.N           = subExecLeft ? std::min(leftover, ((roundedN / subExecLeft) * targetMultiple)) : 0;
      p.teamSize    = 1;
      p.teamIdx     = 0;
      for (int iSrc = 0; iSrc < this->numSrcs; ++iSrc) p.src[iSrc] = this->srcMem[iSrc] + initOffset + assigned;
      for (int iDst = 0; iDst < this->numDsts; ++iDst) p.dst[iDst] = this->dstMem[iDst] + initOffset + assigned;

      assigned += p.N;
    }
2259

gilbertlee-amd's avatar
gilbertlee-amd committed
2260
    p.preferredXccId = -1;
2261
    if (ev.useXccFilter && this->exeType == EXE_GPU_GFX)
2262
    {
2263
2264
2265
2266
2267
2268
2269
2270
      std::uniform_int_distribution<int> distribution(0, ev.xccIdsPerDevice[this->exeIndex].size() - 1);

      // Use this tranfer's executor subIndex if set
      if (this->exeSubIndex != -1)
      {
        p.preferredXccId = this->exeSubIndex;
      }
      else if (this->numDsts >= 1 && IsGpuType(this->dstType[0]))
2271
2272
2273
      {
        p.preferredXccId = ev.prefXccTable[this->exeIndex][this->dstIndex[0]];
      }
2274
2275
2276
2277
2278

      if (p.preferredXccId == -1)
      {
        p.preferredXccId = distribution(*ev.generator);
      }
2279
2280
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
2281
2282
2283
2284
2285
    if (ev.enableDebug)
    {
      printf("Transfer %02d SE:%02d: %10lu floats: %10lu to %10lu\n",
             this->transferIndex, i, p.N, assigned, assigned + p.N);
    }
Gilbert Lee's avatar
Gilbert Lee committed
2286

gilbertlee-amd's avatar
gilbertlee-amd committed
2287
2288
    p.startCycle = 0;
    p.stopCycle  = 0;
Gilbert Lee's avatar
Gilbert Lee committed
2289
2290
  }

Gilbert Lee's avatar
Gilbert Lee committed
2291
  this->transferTime = 0.0;
2292
  this->perIterationTime.clear();
Gilbert Lee's avatar
Gilbert Lee committed
2293
2294
}

gilbertlee-amd's avatar
gilbertlee-amd committed
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
void Transfer::PrepareReference(EnvVars const& ev, std::vector<float>& buffer, int bufferIdx)
{
  size_t N = buffer.size();
  if (bufferIdx >= 0)
  {
    size_t patternLen = ev.fillPattern.size();
    if (patternLen > 0)
    {
      for (size_t i = 0; i < N; ++i)
        buffer[i] = ev.fillPattern[i % patternLen];
    }
    else
    {
      for (size_t i = 0; i < N; ++i)
2309
        buffer[i] = PrepSrcValue(bufferIdx, i);
gilbertlee-amd's avatar
gilbertlee-amd committed
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
    }
  }
  else // Destination buffer
  {
    if (this->numSrcs == 0)
    {
      // Note: 0x75757575 = 13323083.0
      memset(buffer.data(), MEMSET_CHAR, N * sizeof(float));
    }
    else
    {
      PrepareReference(ev, buffer, 0);

      if (this->numSrcs > 1)
      {
        std::vector<float> temp(N);
        for (int srcIdx = 1; srcIdx < this->numSrcs; ++srcIdx)
        {
          PrepareReference(ev, temp, srcIdx);
          for (int i = 0; i < N; ++i)
          {
            buffer[i] += temp[i];
          }
        }
      }
    }
  }
}

2339
bool Transfer::PrepareSrc(EnvVars const& ev)
gilbertlee-amd's avatar
gilbertlee-amd committed
2340
{
2341
  if (this->numSrcs == 0) return true;
gilbertlee-amd's avatar
gilbertlee-amd committed
2342
2343
2344
2345
2346
2347
  size_t const N = this->numBytesActual / sizeof(float);
  int const initOffset = ev.byteOffset / sizeof(float);

  std::vector<float> reference(N);
  for (int srcIdx = 0; srcIdx < this->numSrcs; ++srcIdx)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2348
    float* srcPtr = this->srcMem[srcIdx] + initOffset;
2349
    PrepareReference(ev, reference, srcIdx);
gilbertlee-amd's avatar
gilbertlee-amd committed
2350
2351
2352

    // Initialize source memory array with reference pattern
    if (IsGpuType(this->srcType[srcIdx]))
2353
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
2354
2355
2356
      int const deviceIdx = RemappedIndex(this->srcIndex[srcIdx], false);
      HIP_CALL(hipSetDevice(deviceIdx));
      if (ev.usePrepSrcKernel)
gilbertlee-amd's avatar
gilbertlee-amd committed
2357
        PrepSrcDataKernel<<<32, ev.gfxBlockSize>>>(srcPtr, N, srcIdx);
gilbertlee-amd's avatar
gilbertlee-amd committed
2358
2359
      else
        HIP_CALL(hipMemcpy(srcPtr, reference.data(), this->numBytesActual, hipMemcpyDefault));
2360
2361
      HIP_CALL(hipDeviceSynchronize());
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2362
    else if (IsCpuType(this->srcType[srcIdx]))
2363
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
2364
      memcpy(srcPtr, reference.data(), this->numBytesActual);
2365
    }
2366
2367

    // Perform check just to make sure that data has been copied properly
gilbertlee-amd's avatar
gilbertlee-amd committed
2368
    float* srcCheckPtr = srcPtr;
2369
    std::vector<float> srcCopy(N);
gilbertlee-amd's avatar
gilbertlee-amd committed
2370
2371
2372
2373
2374
2375
2376
2377
2378
    if (IsGpuType(this->srcType[srcIdx]))
    {
      if (!ev.validateDirect)
      {
        HIP_CALL(hipMemcpy(srcCopy.data(), srcPtr, this->numBytesActual, hipMemcpyDefault));
        HIP_CALL(hipDeviceSynchronize());
        srcCheckPtr = srcCopy.data();
      }
    }
2379
2380
2381

    for (size_t i = 0; i < N; ++i)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
2382
      if (reference[i] != srcCheckPtr[i])
2383
2384
      {
        printf("\n[ERROR] Unexpected mismatch at index %lu of source array %d:\n", i, srcIdx);
2385
2386
2387
#if !defined(__NVCC__)
        float const val = this->srcMem[srcIdx][initOffset + i];
        printf("[ERROR] SRC %02d   value: %10.5f [%08X] Direct: %10.5f [%08X]\n",
gilbertlee-amd's avatar
gilbertlee-amd committed
2388
               srcIdx, srcCheckPtr[i], *(unsigned int*)&srcCheckPtr[i], val, *(unsigned int*)&val);
2389
#else
gilbertlee-amd's avatar
gilbertlee-amd committed
2390
        printf("[ERROR] SRC %02d   value: %10.5f [%08X]\n", srcIdx, srcCheckPtr[i], *(unsigned int*)&srcCheckPtr[i]);
2391
#endif
2392
2393
2394
2395
2396
2397
2398
        printf("[ERROR] EXPECTED value: %10.5f [%08X]\n", reference[i], *(unsigned int*)&reference[i]);
        printf("[ERROR] Failed Transfer details: #%d: %s -> [%c%d:%d] -> %s\n",
               this->transferIndex,
               this->SrcToStr().c_str(),
               ExeTypeStr[this->exeType], this->exeIndex,
               this->numSubExecs,
               this->DstToStr().c_str());
2399
2400
        printf("[ERROR] Possible cause is misconfigured IOMMU (AMD Instinct cards require amd_iommu=on and iommu=pt)\n");
        printf("[ERROR] Please see https://community.amd.com/t5/knowledge-base/iommu-advisory-for-amd-instinct/ta-p/484601 for more details\n");
2401
2402
        if (!ev.continueOnError)
          exit(1);
2403
        return false;
2404
2405
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2406
  }
2407
  return true;
gilbertlee-amd's avatar
gilbertlee-amd committed
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
}

void Transfer::ValidateDst(EnvVars const& ev)
{
  if (this->numDsts == 0) return;
  size_t const N = this->numBytesActual / sizeof(float);
  int const initOffset = ev.byteOffset / sizeof(float);

  std::vector<float> reference(N);
  PrepareReference(ev, reference, -1);

  std::vector<float> hostBuffer(N);
  for (int dstIdx = 0; dstIdx < this->numDsts; ++dstIdx)
  {
    float* output;
2423
    if (IsCpuType(this->dstType[dstIdx]) || ev.validateDirect)
gilbertlee-amd's avatar
gilbertlee-amd committed
2424
2425
2426
2427
2428
    {
      output = this->dstMem[dstIdx] + initOffset;
    }
    else
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
2429
2430
      int const deviceIdx = RemappedIndex(this->dstIndex[dstIdx], false);
      HIP_CALL(hipSetDevice(deviceIdx));
gilbertlee-amd's avatar
gilbertlee-amd committed
2431
      HIP_CALL(hipMemcpy(hostBuffer.data(), this->dstMem[dstIdx] + initOffset, this->numBytesActual, hipMemcpyDefault));
gilbertlee-amd's avatar
gilbertlee-amd committed
2432
      HIP_CALL(hipDeviceSynchronize());
gilbertlee-amd's avatar
gilbertlee-amd committed
2433
2434
2435
2436
2437
2438
2439
      output = hostBuffer.data();
    }

    for (size_t i = 0; i < N; ++i)
    {
      if (reference[i] != output[i])
      {
2440
2441
2442
2443
2444
        printf("\n[ERROR] Unexpected mismatch at index %lu of destination array %d:\n", i, dstIdx);
        for (int srcIdx = 0; srcIdx < this->numSrcs; ++srcIdx)
        {
          float srcVal;
          HIP_CALL(hipMemcpy(&srcVal, this->srcMem[srcIdx] + initOffset + i, sizeof(float), hipMemcpyDefault));
2445
2446
2447
2448
2449
#if !defined(__NVCC__)
          float val = this->srcMem[srcIdx][initOffset + i];
          printf("[ERROR] SRC %02dD  value: %10.5f [%08X] Direct: %10.5f [%08X]\n",
                 srcIdx, srcVal, *(unsigned int*)&srcVal, val, *(unsigned int*)&val);
#else
2450
          printf("[ERROR] SRC %02d   value: %10.5f [%08X]\n", srcIdx, srcVal, *(unsigned int*)&srcVal);
2451
#endif
2452
        }
2453
        printf("[ERROR] EXPECTED value: %10.5f [%08X]\n", reference[i], *(unsigned int*)&reference[i]);
2454
2455
2456
2457
2458
#if !defined(__NVCC__)
        float dstVal = this->dstMem[dstIdx][initOffset + i];
        printf("[ERROR] DST %02d   value: %10.5f [%08X] Direct: %10.5f [%08X]\n",
               dstIdx, output[i], *(unsigned int*)&output[i], dstVal, *(unsigned int*)&dstVal);
#else
2459
        printf("[ERROR] DST %02d   value: %10.5f [%08X]\n", dstIdx, output[i], *(unsigned int*)&output[i]);
2460
#endif
gilbertlee-amd's avatar
gilbertlee-amd committed
2461
2462
2463
2464
2465
2466
        printf("[ERROR] Failed Transfer details: #%d: %s -> [%c%d:%d] -> %s\n",
               this->transferIndex,
               this->SrcToStr().c_str(),
               ExeTypeStr[this->exeType], this->exeIndex,
               this->numSubExecs,
               this->DstToStr().c_str());
2467
2468
        if (!ev.continueOnError)
          exit(1);
2469
2470
        else
          break;
gilbertlee-amd's avatar
gilbertlee-amd committed
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
      }
    }
  }
}

std::string Transfer::SrcToStr() const
{
  if (numSrcs == 0) return "N";
  std::stringstream ss;
  for (int i = 0; i < numSrcs; ++i)
    ss << MemTypeStr[srcType[i]] << srcIndex[i];
  return ss.str();
}

std::string Transfer::DstToStr() const
{
  if (numDsts == 0) return "N";
  std::stringstream ss;
  for (int i = 0; i < numDsts; ++i)
    ss << MemTypeStr[dstType[i]] << dstIndex[i];
  return ss.str();
}

2494
2495
void RunSchmooBenchmark(EnvVars const& ev, size_t const numBytesPerTransfer, int const localIdx, int const remoteIdx, int const maxSubExecs)
{
2496
  char memType = ev.useFineGrain ? 'F' : 'G';
2497
  printf("Bytes to transfer: %lu Local GPU: %d Remote GPU: %d\n", numBytesPerTransfer, localIdx, remoteIdx);
2498
2499
  printf("       | Local Read  | Local Write | Local Copy  | Remote Read | Remote Write| Remote Copy |\n");
  printf("  #CUs |%c%02d->G%02d->N00|N00->G%02d->%c%02d|%c%02d->G%02d->%c%02d|%c%02d->G%02d->N00|N00->G%02d->%c%02d|%c%02d->G%02d->%c%02d|\n",
2500
2501
2502
2503
2504
2505
         memType, localIdx, localIdx,
         localIdx, memType, localIdx,
         memType, localIdx, localIdx, memType, localIdx,
         memType, remoteIdx, localIdx,
         localIdx, memType, remoteIdx,
         memType, localIdx, localIdx, memType, remoteIdx);
2506
  printf("|------|-------------|-------------|-------------|-------------|-------------|-------------|\n");
2507
2508
2509
2510
2511
2512
2513
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

  std::vector<Transfer> transfers(1);
  Transfer& t   = transfers[0];
  t.exeType     = EXE_GPU_GFX;
  t.exeIndex    = localIdx;
  t.exeSubIndex = -1;
  t.numBytes    = numBytesPerTransfer;

  for (int numCUs = 1; numCUs <= maxSubExecs; numCUs++)
  {
    t.numSubExecs = numCUs;

    // Local Read
    t.numSrcs = 1;
    t.numDsts = 0;
    t.srcType.resize(t.numSrcs);
    t.dstType.resize(t.numDsts);
    t.srcIndex.resize(t.numSrcs);
    t.dstIndex.resize(t.numDsts);
    t.srcType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.srcIndex[0] = localIdx;
    ExecuteTransfers(ev, 0, 0, transfers, false);
    double const localRead = (t.numBytesActual / 1.0E9) / t.transferTime * 1000.0f;

    // Local Write
    t.numSrcs = 0;
    t.numDsts = 1;
    t.srcType.resize(t.numSrcs);
    t.dstType.resize(t.numDsts);
    t.srcIndex.resize(t.numSrcs);
    t.dstIndex.resize(t.numDsts);
    t.dstType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.dstIndex[0] = localIdx;
    ExecuteTransfers(ev, 0, 0, transfers, false);
    double const localWrite = (t.numBytesActual / 1.0E9) / t.transferTime * 1000.0f;

    // Local Copy
    t.numSrcs = 1;
    t.numDsts = 1;
    t.srcType.resize(t.numSrcs);
    t.dstType.resize(t.numDsts);
    t.srcIndex.resize(t.numSrcs);
    t.dstIndex.resize(t.numDsts);
    t.srcType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.srcIndex[0] = localIdx;
    t.dstType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.dstIndex[0] = localIdx;
    ExecuteTransfers(ev, 0, 0, transfers, false);
    double const localCopy = (t.numBytesActual / 1.0E9) / t.transferTime * 1000.0f;

    // Remote Read
    t.numSrcs = 1;
    t.numDsts = 0;
    t.srcType.resize(t.numSrcs);
    t.dstType.resize(t.numDsts);
    t.srcIndex.resize(t.numSrcs);
    t.dstIndex.resize(t.numDsts);
    t.srcType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.srcIndex[0] = remoteIdx;
    ExecuteTransfers(ev, 0, 0, transfers, false);
    double const remoteRead = (t.numBytesActual / 1.0E9) / t.transferTime * 1000.0f;

    // Remote Write
    t.numSrcs = 0;
    t.numDsts = 1;
    t.srcType.resize(t.numSrcs);
    t.dstType.resize(t.numDsts);
    t.srcIndex.resize(t.numSrcs);
    t.dstIndex.resize(t.numDsts);
    t.dstType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.dstIndex[0] = remoteIdx;
    ExecuteTransfers(ev, 0, 0, transfers, false);
    double const remoteWrite = (t.numBytesActual / 1.0E9) / t.transferTime * 1000.0f;

    // Remote Copy
    t.numSrcs = 1;
    t.numDsts = 1;
    t.srcType.resize(t.numSrcs);
    t.dstType.resize(t.numDsts);
    t.srcIndex.resize(t.numSrcs);
    t.dstIndex.resize(t.numDsts);
    t.srcType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.srcIndex[0] = localIdx;
    t.dstType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
    t.dstIndex[0] = remoteIdx;
    ExecuteTransfers(ev, 0, 0, transfers, false);
    double const remoteCopy = (t.numBytesActual / 1.0E9) / t.transferTime * 1000.0f;

2595
    printf("   %3d   %11.3f   %11.3f   %11.3f   %11.3f   %11.3f   %11.3f  \n",
2596
2597
2598
2599
           numCUs, localRead, localWrite, localCopy, remoteRead, remoteWrite, remoteCopy);
  }
}

2600
2601
void RunRemoteWriteBenchmark(EnvVars const& ev, size_t const numBytesPerTransfer, int numSubExecs, int const srcIdx, int minGpus, int maxGpus)
{
2602
2603
  printf("Bytes to %s: %lu from GPU %d using %d CUs [Sweeping %d to %d parallel writes]\n",
         ev.useRemoteRead ? "read" : "write", numBytesPerTransfer, srcIdx, numSubExecs, minGpus, maxGpus);
2604

gilbertlee-amd's avatar
gilbertlee-amd committed
2605
2606
  char sep = (ev.outputToCsv ? ',' : ' ');

2607
2608
2609
  for (int i = 0; i < ev.numGpuDevices; i++)
  {
    if (i == srcIdx) continue;
gilbertlee-amd's avatar
gilbertlee-amd committed
2610
    printf("   GPU %-3d  %c", i, sep);
2611
2612
  }
  printf("\n");
gilbertlee-amd's avatar
gilbertlee-amd committed
2613
  if (!ev.outputToCsv)
2614
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2615
2616
2617
2618
2619
    for (int i = 0; i < ev.numGpuDevices-1; i++)
    {
      printf("-------------");
    }
    printf("\n");
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
  }

  for (int p = minGpus; p <= maxGpus; p++)
  {
    for (int bitmask = 0; bitmask < (1<<ev.numGpuDevices); bitmask++)
    {
      if (bitmask & (1<<srcIdx)) continue;
      if (__builtin_popcount(bitmask) == p)
      {
        std::vector<Transfer> transfers;
        for (int i = 0; i < ev.numGpuDevices; i++)
        {
          if (bitmask & (1<<i))
          {
            Transfer t;
            t.exeType     = EXE_GPU_GFX;
            t.exeSubIndex = -1;
            t.numSubExecs = numSubExecs;
            t.numBytes    = numBytesPerTransfer;
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659

            if (ev.useRemoteRead)
            {
              t.numSrcs  = 1;
              t.numDsts  = 0;
              t.exeIndex = i;
              t.srcType.resize(1);
              t.srcType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
              t.srcIndex.resize(1);
              t.srcIndex[0] = srcIdx;
            }
            else
            {
              t.numSrcs     = 0;
              t.numDsts     = 1;
              t.exeIndex    = srcIdx;
              t.dstType.resize(1);
              t.dstType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
              t.dstIndex.resize(1);
              t.dstIndex[0] = i;
            }
2660
2661
2662
2663
2664
2665
2666
2667
2668
            transfers.push_back(t);
          }
        }
        ExecuteTransfers(ev, 0, 0, transfers, false);

        int counter = 0;
        for (int i = 0; i < ev.numGpuDevices; i++)
        {
          if (bitmask & (1<<i))
gilbertlee-amd's avatar
gilbertlee-amd committed
2669
            printf("  %8.3f  %c", transfers[counter++].transferBandwidth, sep);
2670
          else if (i != srcIdx)
gilbertlee-amd's avatar
gilbertlee-amd committed
2671
            printf("            %c", sep);
2672
2673
        }

gilbertlee-amd's avatar
gilbertlee-amd committed
2674
        printf(" %d %d", p, numSubExecs);
2675
2676
        for (auto i = 0; i < transfers.size(); i++)
        {
2677
2678
          printf(" (%s %c%d %s)",
                 transfers[i].SrcToStr().c_str(),
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
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
                 ExeTypeStr[transfers[i].exeType], transfers[i].exeIndex,
                 transfers[i].DstToStr().c_str());
        }
        printf("\n");
      }
    }
  }
}

void RunParallelCopyBenchmark(EnvVars const& ev, size_t const numBytesPerTransfer, int numSubExecs, int const srcIdx, int minGpus, int maxGpus)
{
  if (ev.useDmaCopy)
    printf("Bytes to copy: %lu from GPU %d using DMA [Sweeping %d to %d parallel writes]\n",
           numBytesPerTransfer, srcIdx, minGpus, maxGpus);
  else
    printf("Bytes to copy: %lu from GPU %d using GFX (%d CUs) [Sweeping %d to %d parallel writes]\n",
           numBytesPerTransfer, srcIdx, numSubExecs, minGpus, maxGpus);

  char sep = (ev.outputToCsv ? ',' : ' ');

  for (int i = 0; i < ev.numGpuDevices; i++)
  {
    if (i == srcIdx) continue;
    printf("   GPU %-3d  %c", i, sep);
  }
  printf("\n");
  if (!ev.outputToCsv)
  {
    for (int i = 0; i < ev.numGpuDevices-1; i++)
    {
      printf("-------------");
    }
    printf("\n");
  }

  for (int p = minGpus; p <= maxGpus; p++)
  {
    for (int bitmask = 0; bitmask < (1<<ev.numGpuDevices); bitmask++)
    {
      if (bitmask & (1<<srcIdx)) continue;
      if (__builtin_popcount(bitmask) == p)
      {
        std::vector<Transfer> transfers;
        for (int i = 0; i < ev.numGpuDevices; i++)
        {
          if (bitmask & (1<<i))
          {
            Transfer t;
            t.exeType     = ev.useDmaCopy ? EXE_GPU_DMA : EXE_GPU_GFX;
            t.exeSubIndex = -1;
            t.numSubExecs = ev.useDmaCopy ? 1 : numSubExecs;
            t.numBytes    = numBytesPerTransfer;

            t.numSrcs     = 1;
            t.numDsts     = 1;
            t.exeIndex    = srcIdx;
            t.srcType.resize(1);
            t.srcType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
            t.srcIndex.resize(1);
            t.srcIndex[0] = srcIdx;
            t.dstType.resize(1);
            t.dstType[0]  = (ev.useFineGrain ? MEM_GPU_FINE : MEM_GPU);
            t.dstIndex.resize(1);
            t.dstIndex[0] = i;

            transfers.push_back(t);
          }
        }
        ExecuteTransfers(ev, 0, 0, transfers, false);

        int counter = 0;
        for (int i = 0; i < ev.numGpuDevices; i++)
        {
          if (bitmask & (1<<i))
            printf("  %8.3f  %c", transfers[counter++].transferBandwidth, sep);
          else if (i != srcIdx)
            printf("            %c", sep);
        }

        printf(" %d %d", p, numSubExecs);
        for (auto i = 0; i < transfers.size(); i++)
        {
          printf(" (%s %c%d %s)",
                 transfers[i].SrcToStr().c_str(),
                 ExeTypeStr[transfers[i].exeType], transfers[i].exeIndex,
2764
                 transfers[i].DstToStr().c_str());
2765
2766
2767
2768
2769
2770
        }
        printf("\n");
      }
    }
  }
}
2771

gilbertlee-amd's avatar
gilbertlee-amd committed
2772
void RunSweepPreset(EnvVars const& ev, size_t const numBytesPerTransfer, int const numGpuSubExecs, int const numCpuSubExecs, bool const isRandom)
Gilbert Lee's avatar
Gilbert Lee committed
2773
2774
2775
2776
{
  ev.DisplaySweepEnvVars();

  // Compute how many possible Transfers are permitted (unique SRC/EXE/DST triplets)
gilbertlee-amd's avatar
gilbertlee-amd committed
2777
  std::vector<std::pair<ExeType, int>> exeList;
Gilbert Lee's avatar
Gilbert Lee committed
2778
2779
  for (auto exe : ev.sweepExe)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2780
2781
    ExeType const exeType = CharToExeType(exe);
    if (IsGpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
2782
    {
2783
      for (int exeIndex = 0; exeIndex < ev.numGpuDevices; ++exeIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
2784
        exeList.push_back(std::make_pair(exeType, exeIndex));
Gilbert Lee's avatar
Gilbert Lee committed
2785
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
2786
    else if (IsCpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
2787
    {
2788
2789
2790
2791
      for (int exeIndex = 0; exeIndex < ev.numCpuDevices; ++exeIndex)
      {
        // Skip NUMA nodes that have no CPUs (e.g. CXL)
        if (ev.numCpusPerNuma[exeIndex] == 0) continue;
gilbertlee-amd's avatar
gilbertlee-amd committed
2792
        exeList.push_back(std::make_pair(exeType, exeIndex));
2793
      }
Gilbert Lee's avatar
Gilbert Lee committed
2794
2795
    }
  }
2796
  int numExes = exeList.size();
Gilbert Lee's avatar
Gilbert Lee committed
2797
2798
2799
2800

  std::vector<std::pair<MemType, int>> srcList;
  for (auto src : ev.sweepSrc)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2801
    MemType const srcType = CharToMemType(src);
2802
    int const numDevices = (srcType == MEM_NULL) ? 1 : IsGpuType(srcType) ? ev.numGpuDevices : ev.numCpuDevices;
2803

Gilbert Lee's avatar
Gilbert Lee committed
2804
    for (int srcIndex = 0; srcIndex < numDevices; ++srcIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
2805
      srcList.push_back(std::make_pair(srcType, srcIndex));
Gilbert Lee's avatar
Gilbert Lee committed
2806
2807
2808
2809
2810
2811
2812
  }
  int numSrcs = srcList.size();


  std::vector<std::pair<MemType, int>> dstList;
  for (auto dst : ev.sweepDst)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2813
    MemType const dstType = CharToMemType(dst);
2814
    int const numDevices = (dstType == MEM_NULL) ? 1 : IsGpuType(dstType) ? ev.numGpuDevices : ev.numCpuDevices;
Gilbert Lee's avatar
Gilbert Lee committed
2815
2816

    for (int dstIndex = 0; dstIndex < numDevices; ++dstIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
2817
      dstList.push_back(std::make_pair(dstType, dstIndex));
Gilbert Lee's avatar
Gilbert Lee committed
2818
2819
2820
  }
  int numDsts = dstList.size();

2821
2822
  // Build array of possibilities, respecting any additional restrictions (e.g. XGMI hop count)
  struct TransferInfo
Gilbert Lee's avatar
Gilbert Lee committed
2823
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
2824
2825
2826
    MemType srcType; int srcIndex;
    ExeType exeType; int exeIndex;
    MemType dstType; int dstIndex;
2827
2828
2829
2830
2831
2832
2833
2834
  };

  // If either XGMI minimum is non-zero, or XGMI maximum is specified and non-zero then both links must be XGMI
  bool const useXgmiOnly = (ev.sweepXgmiMin > 0 || ev.sweepXgmiMax > 0);

  std::vector<TransferInfo> possibleTransfers;
  TransferInfo tinfo;
  for (int i = 0; i < numExes; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
2835
  {
2836
2837
    // Skip CPU executors if XGMI link must be used
    if (useXgmiOnly && !IsGpuType(exeList[i].first)) continue;
gilbertlee-amd's avatar
gilbertlee-amd committed
2838
2839
    tinfo.exeType  = exeList[i].first;
    tinfo.exeIndex = exeList[i].second;
2840

gilbertlee-amd's avatar
gilbertlee-amd committed
2841
    bool isXgmiSrc  = false;
2842
2843
2844
2845
2846
2847
2848
    int  numHopsSrc = 0;
    for (int j = 0; j < numSrcs; ++j)
    {
      if (IsGpuType(exeList[i].first) && IsGpuType(srcList[j].first))
      {
        if (exeList[i].second != srcList[j].second)
        {
2849
2850
2851
#if defined(__NVCC__)
          isXgmiSrc = false;
#else
2852
          uint32_t exeToSrcLinkType, exeToSrcHopCount;
gilbertlee-amd's avatar
gilbertlee-amd committed
2853
2854
          HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(exeList[i].second, false),
                                                RemappedIndex(srcList[j].second, false),
2855
2856
2857
2858
                                                &exeToSrcLinkType,
                                                &exeToSrcHopCount));
          isXgmiSrc = (exeToSrcLinkType == HSA_AMD_LINK_INFO_TYPE_XGMI);
          if (isXgmiSrc) numHopsSrc = exeToSrcHopCount;
2859
#endif
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
        }
        else
        {
          isXgmiSrc = true;
          numHopsSrc = 0;
        }

        // Skip this SRC if it is not XGMI but only XGMI links may be used
        if (useXgmiOnly && !isXgmiSrc) continue;

        // Skip this SRC if XGMI distance is already past limit
        if (ev.sweepXgmiMax >= 0 && isXgmiSrc && numHopsSrc > ev.sweepXgmiMax) continue;
      }
2873
      else if (srcList[j].first != MEM_NULL && useXgmiOnly) continue;
2874

gilbertlee-amd's avatar
gilbertlee-amd committed
2875
2876
      tinfo.srcType  = srcList[j].first;
      tinfo.srcIndex = srcList[j].second;
2877
2878
2879
2880
2881
2882
2883
2884
2885

      bool isXgmiDst = false;
      int  numHopsDst = 0;
      for (int k = 0; k < numDsts; ++k)
      {
        if (IsGpuType(exeList[i].first) && IsGpuType(dstList[k].first))
        {
          if (exeList[i].second != dstList[k].second)
          {
2886
2887
2888
#if defined(__NVCC__)
            isXgmiSrc = false;
#else
2889
            uint32_t exeToDstLinkType, exeToDstHopCount;
gilbertlee-amd's avatar
gilbertlee-amd committed
2890
2891
            HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(exeList[i].second, false),
                                                  RemappedIndex(dstList[k].second, false),
2892
2893
2894
2895
                                                  &exeToDstLinkType,
                                                  &exeToDstHopCount));
            isXgmiDst = (exeToDstLinkType == HSA_AMD_LINK_INFO_TYPE_XGMI);
            if (isXgmiDst) numHopsDst = exeToDstHopCount;
2896
#endif
2897
2898
2899
2900
2901
2902
2903
2904
2905
          }
          else
          {
            isXgmiDst = true;
            numHopsDst = 0;
          }
        }

        // Skip this DST if it is not XGMI but only XGMI links may be used
2906
        if (dstList[k].first != MEM_NULL && useXgmiOnly && !isXgmiDst) continue;
2907
2908
2909
2910
2911
2912
2913

        // Skip this DST if total XGMI distance (SRC + DST) is less than min limit
        if (ev.sweepXgmiMin > 0 && (numHopsSrc + numHopsDst < ev.sweepXgmiMin)) continue;

        // Skip this DST if total XGMI distance (SRC + DST) is greater than max limit
        if (ev.sweepXgmiMax >= 0 && (numHopsSrc + numHopsDst) > ev.sweepXgmiMax) continue;

2914
2915
2916
2917
2918
2919
#if defined(__NVCC__)
        // Skip CPU executors on GPU memory on NVIDIA platform
        if (IsCpuType(exeList[i].first) && (IsGpuType(dstList[j].first) || IsGpuType(dstList[k].first)))
          continue;
#endif

gilbertlee-amd's avatar
gilbertlee-amd committed
2920
2921
        tinfo.dstType  = dstList[k].first;
        tinfo.dstIndex = dstList[k].second;
2922

2923
2924
2925
        // Skip if there is no src and dst
        if (tinfo.srcType == MEM_NULL && tinfo.dstType == MEM_NULL) continue;

2926
2927
2928
        possibleTransfers.push_back(tinfo);
      }
    }
Gilbert Lee's avatar
Gilbert Lee committed
2929
2930
  }

2931
2932
2933
  int const numPossible = (int)possibleTransfers.size();
  int maxParallelTransfers = (ev.sweepMax == 0 ? numPossible : ev.sweepMax);

Gilbert Lee's avatar
Gilbert Lee committed
2934
2935
2936
2937
2938
2939
  if (ev.sweepMin > numPossible)
  {
    printf("No valid test configurations exist\n");
    return;
  }

2940
2941
2942
2943
2944
2945
  if (ev.outputToCsv)
  {
    printf("\nTest#,Transfer#,NumBytes,Src,Exe,Dst,CUs,BW(GB/s),Time(ms),"
           "ExeToSrcLinkType,ExeToDstLinkType,SrcAddr,DstAddr\n");
  }

Gilbert Lee's avatar
Gilbert Lee committed
2946
2947
  int numTestsRun = 0;
  int M = ev.sweepMin;
gilbertlee-amd's avatar
gilbertlee-amd committed
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
  std::uniform_int_distribution<int> randSize(1, numBytesPerTransfer / sizeof(float));
  std::uniform_int_distribution<int> distribution(ev.sweepMin, maxParallelTransfers);

  // Log sweep to configuration file
  FILE *fp = fopen("lastSweep.cfg", "w");
  if (!fp)
  {
    printf("[ERROR] Unable to open lastSweep.cfg.  Check permissions\n");
    exit(1);
  }

Gilbert Lee's avatar
Gilbert Lee committed
2959
2960
2961
2962
2963
2964
2965
2966
2967
  // Create bitmask of numPossible triplets, of which M will be chosen
  std::string bitmask(M, 1);  bitmask.resize(numPossible, 0);
  auto cpuStart = std::chrono::high_resolution_clock::now();
  while (1)
  {
    if (isRandom)
    {
      // Pick random number of simultaneous transfers to execute
      // NOTE: This currently skews distribution due to some #s having more possibilities than others
gilbertlee-amd's avatar
gilbertlee-amd committed
2968
      M = distribution(*ev.generator);
Gilbert Lee's avatar
Gilbert Lee committed
2969
2970
2971
2972

      // Generate a random bitmask
      for (int i = 0; i < numPossible; i++)
        bitmask[i] = (i < M) ? 1 : 0;
2973
      std::shuffle(bitmask.begin(), bitmask.end(), *ev.generator);
Gilbert Lee's avatar
Gilbert Lee committed
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
    }

    // Convert bitmask to list of Transfers
    std::vector<Transfer> transfers;
    for (int value = 0; value < numPossible; ++value)
    {
      if (bitmask[value])
      {
        // Convert integer value to (SRC->EXE->DST) triplet
        Transfer transfer;
2984
2985
        transfer.numSrcs        = (possibleTransfers[value].srcType == MEM_NULL ? 0 : 1);
        transfer.numDsts        = (possibleTransfers[value].dstType == MEM_NULL ? 0 : 1);
gilbertlee-amd's avatar
gilbertlee-amd committed
2986
2987
2988
        transfer.srcType        = {possibleTransfers[value].srcType};
        transfer.srcIndex       = {possibleTransfers[value].srcIndex};
        transfer.exeType        = possibleTransfers[value].exeType;
2989
        transfer.exeIndex       = possibleTransfers[value].exeIndex;
2990
        transfer.exeSubIndex    = -1;
gilbertlee-amd's avatar
gilbertlee-amd committed
2991
2992
2993
        transfer.dstType        = {possibleTransfers[value].dstType};
        transfer.dstIndex       = {possibleTransfers[value].dstIndex};
        transfer.numSubExecs    = IsGpuType(transfer.exeType) ? numGpuSubExecs : numCpuSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
2994
        transfer.numBytes       = ev.sweepRandBytes ? randSize(*ev.generator) * sizeof(float) : 0;
Gilbert Lee's avatar
Gilbert Lee committed
2995
2996
2997
2998
        transfers.push_back(transfer);
      }
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
2999
3000
    LogTransfers(fp, ++numTestsRun, transfers);
    ExecuteTransfers(ev, numTestsRun, numBytesPerTransfer / sizeof(float), transfers);
Gilbert Lee's avatar
Gilbert Lee committed
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031

    // Check for test limit
    if (numTestsRun == ev.sweepTestLimit)
    {
      printf("Test limit reached\n");
      break;
    }

    // Check for time limit
    auto cpuDelta = std::chrono::high_resolution_clock::now() - cpuStart;
    double totalCpuTime = std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count();
    if (ev.sweepTimeLimit && totalCpuTime > ev.sweepTimeLimit)
    {
      printf("Time limit exceeded\n");
      break;
    }

    // Increment bitmask if not random sweep
    if (!isRandom && !std::prev_permutation(bitmask.begin(), bitmask.end()))
    {
      M++;
      // Check for completion
      if (M > maxParallelTransfers)
      {
        printf("Sweep complete\n");
        break;
      }
      for (int i = 0; i < numPossible; i++)
        bitmask[i] = (i < M) ? 1 : 0;
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
  fclose(fp);
}

void LogTransfers(FILE *fp, int const testNum, std::vector<Transfer> const& transfers)
{
  fprintf(fp, "# Test %d\n", testNum);
  fprintf(fp, "%d", -1 * (int)transfers.size());
  for (auto const& transfer : transfers)
  {
    fprintf(fp, " (%c%d->%c%d->%c%d %d %lu)",
gilbertlee-amd's avatar
gilbertlee-amd committed
3042
3043
3044
3045
            MemTypeStr[transfer.srcType[0]], transfer.srcIndex[0],
            ExeTypeStr[transfer.exeType],    transfer.exeIndex,
            MemTypeStr[transfer.dstType[0]], transfer.dstIndex[0],
            transfer.numSubExecs,
gilbertlee-amd's avatar
gilbertlee-amd committed
3046
3047
3048
3049
            transfer.numBytes);
  }
  fprintf(fp, "\n");
  fflush(fp);
Gilbert Lee's avatar
Gilbert Lee committed
3050
}
gilbertlee-amd's avatar
gilbertlee-amd committed
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061

std::string PtrVectorToStr(std::vector<float*> const& strVector, int const initOffset)
{
  std::stringstream ss;
  for (int i = 0; i < strVector.size(); ++i)
  {
    if (i) ss << " ";
    ss << (strVector[i] + initOffset);
  }
  return ss.str();
}
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
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374

void ReportResults(EnvVars const& ev, std::vector<Transfer> const& transfers, TestResults const results)
{
  char sep = ev.outputToCsv ? ',' : '|';
  size_t numTimedIterations = results.numTimedIterations;

  // Loop over each executor
  for (auto exeInfoPair : results.exeResults) {
    ExeResult const& exeResult = exeInfoPair.second;
    ExeType exeType  = exeInfoPair.first.first;
    int     exeIndex = exeInfoPair.first.second;

    printf(" Executor: %3s %02d %c %7.3f GB/s %c %8.3f ms %c %12lu bytes %c %-7.3f GB/s (sum)\n",
           ExeTypeName[exeType], exeIndex, sep, exeResult.bandwidthGbs, sep,
           exeResult.durationMsec, sep, exeResult.totalBytes, sep, exeResult.sumBandwidthGbs);

    for (int idx : exeResult.transferIdx) {
      Transfer const& t = transfers[idx];

      char exeSubIndexStr[32] = "";
      if (ev.useXccFilter || t.exeType == EXE_GPU_DMA) {
        if (t.exeSubIndex == -1)
          sprintf(exeSubIndexStr, ".*");
        else
          sprintf(exeSubIndexStr, ".%d", t.exeSubIndex);
      }
      printf("     Transfer %02d  %c %7.3f GB/s %c %8.3f ms %c %12lu bytes %c %s -> %s%02d%s:%03d -> %s\n",
             t.transferIndex, sep,
             t.transferBandwidth, sep,
             t.transferTime, sep,
             t.numBytesActual, sep,
             t.SrcToStr().c_str(),
             ExeTypeName[t.exeType], t.exeIndex,
             exeSubIndexStr,
             t.numSubExecs,
             t.DstToStr().c_str());

      // Show per-iteration timing information
      if (ev.showIterations) {

        std::set<std::pair<double, int>> times;
        double stdDevTime = 0;
        double stdDevBw = 0;
        for (int i = 0; i < numTimedIterations; i++) {
          times.insert(std::make_pair(t.perIterationTime[i], i+1));
          double const varTime = fabs(t.transferTime - t.perIterationTime[i]);
          stdDevTime += varTime * varTime;

          double iterBandwidthGbs = (t.numBytesActual / 1.0E9) / t.perIterationTime[i] * 1000.0f;
          double const varBw = fabs(iterBandwidthGbs - t.transferBandwidth);
          stdDevBw += varBw * varBw;
        }
        stdDevTime = sqrt(stdDevTime / numTimedIterations);
        stdDevBw = sqrt(stdDevBw / numTimedIterations);

        for (auto time : times) {
          double iterDurationMsec = time.first;
          double iterBandwidthGbs = (t.numBytesActual / 1.0E9) / iterDurationMsec * 1000.0f;
          printf("      Iter %03d    %c %7.3f GB/s %c %8.3f ms %c", time.second, sep, iterBandwidthGbs, sep, iterDurationMsec, sep);

          std::set<int> usedXccs;
          if (time.second - 1 < t.perIterationCUs.size()) {
            printf(" CUs:");
            for (auto x : t.perIterationCUs[time.second - 1]) {
              printf(" %02d:%02d", x.first, x.second);
              usedXccs.insert(x.first);
            }
          }
          printf(" XCCs:");
          for (auto x : usedXccs)
            printf(" %02d", x);
          printf("\n");
        }
        printf("      StandardDev %c %7.3f GB/s %c %8.3f ms %c\n", sep, stdDevBw, sep, stdDevTime, sep);
      }
    }
  }

  printf(" Aggregate (CPU)  %c %7.3f GB/s %c %8.3f ms %c %12lu bytes %c Overhead: %.3f ms\n", sep,
         results.totalBandwidthCpu, sep, results.totalDurationMsec, sep, results.totalBytesTransferred, sep, results.overheadMsec);
}

void RunHealthCheck(EnvVars ev)
{
  // Check for supported platforms
#if defined(__NVCC__)
  printf("[WARN] healthcheck preset not supported on NVIDIA hardware\n");
  return;
#else

  bool hasFail = false;

  // Force use of single stream
  ev.useSingleStream = 1;

  for (int gpuId = 0; gpuId < ev.numGpuDevices; gpuId++) {
    hipDeviceProp_t prop;
    HIP_CALL(hipGetDeviceProperties(&prop, gpuId));
    std::string fullName = prop.gcnArchName;
    std::string archName = fullName.substr(0, fullName.find(':'));
    if (!(archName == "gfx940" || archName == "gfx941" || archName == "gfx942"))
    {
      printf("[WARN] healthcheck preset is currently only supported on MI300 series hardware\n");
      exit(1);
    }
  }

  // Pass limits
  double udirLimit = getenv("LIMIT_UDIR") ? atof(getenv("LIMIT_UDIR")) : (int)(48 * 0.95);
  double bdirLimit = getenv("LIMIT_BDIR") ? atof(getenv("LIMIT_BDIR")) : (int)(96 * 0.95);
  double a2aLimit  = getenv("LIMIT_A2A")  ? atof(getenv("LIMIT_A2A"))  : (int)(45 * 0.95);

  // Run CPU to GPU

  // Run unidirectional read from CPU to GPU
  printf("Testing unidirectional reads from CPU ");
  {
    std::vector<std::pair<int, double>> fails;
    for (int gpuId = 0; gpuId < ev.numGpuDevices; gpuId++) {
      printf("."); fflush(stdout);
      std::vector<Transfer> transfers(1);
      Transfer& t = transfers[0];
      t.exeType     = EXE_GPU_GFX;
      t.exeIndex    = gpuId;
      t.numBytes    = 64*1024*1024;
      t.numBytesActual = 64*1024*1024;
      t.numSrcs     = 1;
      t.srcType.push_back(MEM_CPU);
      t.srcIndex.push_back(GetClosestNumaNode(gpuId));
      t.numDsts     = 0;
      t.dstType.clear();
      t.dstIndex.clear();

    // Loop over number of CUs to use
      bool passed = false;
      double bestResult = 0;
      for (int cu = 7; cu <= 10; cu++) {
        t.numSubExecs = cu;
        TestResults tesResults = ExecuteTransfersImpl(ev, transfers);
        bestResult = std::max(bestResult, t.transferBandwidth);
        if (t.transferBandwidth >= udirLimit) {
          passed = true;
          break;
      }
      }
      if (!passed) fails.push_back(std::make_pair(gpuId, bestResult));
    }
    if (fails.size() == 0) {
      printf("PASS\n");
    } else {
      hasFail = true;
      printf("FAIL (%lu test(s))\n", fails.size());
      for (auto p : fails) {
        printf(" GPU %02d: Measured: %6.2f GB/s      Criteria: %6.2f GB/s\n", p.first, p.second, udirLimit);
      }
    }
  }

  // Run unidirectional write from GPU to CPU
  printf("Testing unidirectional writes to  CPU ");
  {
    std::vector<std::pair<int, double>> fails;
    for (int gpuId = 0; gpuId < ev.numGpuDevices; gpuId++) {
      printf("."); fflush(stdout);
      std::vector<Transfer> transfers(1);
      Transfer& t = transfers[0];
      t.exeType     = EXE_GPU_GFX;
      t.exeIndex    = gpuId;
      t.numBytes    = 64*1024*1024;
      t.numBytesActual = 64*1024*1024;
      t.numDsts     = 1;
      t.dstType.push_back(MEM_CPU);
      t.dstIndex.push_back(GetClosestNumaNode(gpuId));
      t.numSrcs     = 0;
      t.srcType.clear();
      t.srcIndex.clear();

      // Loop over number of CUs to use
      bool passed = false;
      double bestResult = 0;
      for (int cu = 7; cu <= 10; cu++) {
        t.numSubExecs = cu;

        TestResults tesResults = ExecuteTransfersImpl(ev, transfers);
        bestResult = std::max(bestResult, t.transferBandwidth);
        if (t.transferBandwidth >= udirLimit) {
          passed = true;
          break;
        }
      }
      if (!passed) fails.push_back(std::make_pair(gpuId, bestResult));
    }
    if (fails.size() == 0) {
      printf("PASS\n");
    } else {
      hasFail = true;
      printf("FAIL (%lu test(s))\n", fails.size());
      for (auto p : fails) {
        printf(" GPU %02d: Measured: %6.2f GB/s      Criteria: %6.2f GB/s\n", p.first, p.second, udirLimit);
      }
    }
  }

  // Run bidirectional tests
  printf("Testing bidirectional  reads + writes ");
  {
    std::vector<std::pair<int, double>> fails;
    for (int gpuId = 0; gpuId < ev.numGpuDevices; gpuId++) {
      printf("."); fflush(stdout);
      std::vector<Transfer> transfers(2);
      Transfer& t0 = transfers[0];
      Transfer& t1 = transfers[1];

      t0.exeType     = EXE_GPU_GFX;
      t0.exeIndex    = gpuId;
      t0.numBytes    = 64*1024*1024;
      t0.numBytesActual = 64*1024*1024;
      t0.numSrcs     = 1;
      t0.srcType.push_back(MEM_CPU);
      t0.srcIndex.push_back(GetClosestNumaNode(gpuId));
      t0.numDsts     = 0;
      t0.dstType.clear();
      t0.dstIndex.clear();

      t1.exeType     = EXE_GPU_GFX;
      t1.exeIndex    = gpuId;
      t1.numBytes    = 64*1024*1024;
      t1.numBytesActual = 64*1024*1024;
      t1.numDsts     = 1;
      t1.dstType.push_back(MEM_CPU);
      t1.dstIndex.push_back(GetClosestNumaNode(gpuId));
      t1.numSrcs     = 0;
      t1.srcType.clear();
      t1.srcIndex.clear();

      // Loop over number of CUs to use
      bool passed = false;
      double bestResult = 0;
      for (int cu = 7; cu <= 10; cu++) {
        t0.numSubExecs = cu;
        t1.numSubExecs = cu;

        TestResults tesResults = ExecuteTransfersImpl(ev, transfers);
        double sum = t0.transferBandwidth + t1.transferBandwidth;
        bestResult = std::max(bestResult, sum);
        if (sum >= bdirLimit) {
          passed = true;
          break;
        }
      }
      if (!passed) fails.push_back(std::make_pair(gpuId, bestResult));
    }
    if (fails.size() == 0) {
      printf("PASS\n");
    } else {
      hasFail = true;
      printf("FAIL (%lu test(s))\n", fails.size());
      for (auto p : fails) {
        printf(" GPU %02d: Measured: %6.2f GB/s      Criteria: %6.2f GB/s\n", p.first, p.second, bdirLimit);
      }
    }
  }

  // Run XGMI tests:
  printf("Testing all-to-all XGMI copies        "); fflush(stdout);
  {
    ev.gfxUnroll = 2;
    std::vector<Transfer> transfers;
    for (int i = 0; i < ev.numGpuDevices; i++) {
      for (int j = 0; j < ev.numGpuDevices; j++) {
        if (i == j) continue;
        Transfer t;
        t.exeType = EXE_GPU_GFX;
        t.exeIndex = i;
        t.numBytes = t.numBytesActual = 64*1024*1024;
        t.numSrcs = 1;
        t.numDsts = 1;
        t.numSubExecs = 8;
        t.srcType.push_back(MEM_GPU_FINE);
        t.dstType.push_back(MEM_GPU_FINE);
        t.srcIndex.push_back(i);
        t.dstIndex.push_back(j);
        transfers.push_back(t);
      }
    }
    TestResults tesResults = ExecuteTransfersImpl(ev, transfers);
    std::vector<std::pair<std::pair<int,int>, double>> fails;
    int transferIdx = 0;
    for (int i = 0; i < ev.numGpuDevices; i++) {
      printf("."); fflush(stdout);
      for (int j = 0; j < ev.numGpuDevices; j++) {
        if (i == j) continue;
        Transfer const& t = transfers[transferIdx];
        if (t.transferBandwidth < a2aLimit) {
          fails.push_back(std::make_pair(std::make_pair(i,j), t.transferBandwidth));
        }
        transferIdx++;
      }
    }
    if (fails.size() == 0) {
      printf("PASS\n");
    } else {
      hasFail = true;
      printf("FAIL (%lu test(s))\n", fails.size());
      for (auto p : fails) {
        printf(" GPU %02d to GPU %02d: %6.2f GB/s      Criteria: %6.2f GB/s\n", p.first.first, p.first.second, p.second, a2aLimit);
      }
    }
  }

  exit(hasFail ? 1 : 0);
#endif
}