TransferBench.cpp 58.8 KB
Newer Older
Gilbert Lee's avatar
Gilbert Lee committed
1
/*
gilbertlee-amd's avatar
gilbertlee-amd committed
2
Copyright (c) 2019-2023 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
25
26

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
#include <numa.h>
#include <numaif.h>
Gilbert Lee's avatar
Gilbert Lee committed
27
#include <random>
Gilbert Lee's avatar
Gilbert Lee committed
28
29
30
31
32
33
34
35
#include <stack>
#include <thread>

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

int main(int argc, char **argv)
{
Gilbert Lee's avatar
Gilbert Lee committed
36
37
38
39
40
41
42
  // 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
43
44
45
46
47
48
49
50
51
52
53
54
  // 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
55
56
  // 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
57
58
59
60
61
62
  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
63
64
65
    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
66
67
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
68
69
70
71
72
  if (numBytesPerTransfer % 4)
  {
    printf("[ERROR] numBytesPerTransfer (%lu) must be a multiple of 4\n", numBytesPerTransfer);
    exit(1);
  }
Gilbert Lee's avatar
Gilbert Lee committed
73

Gilbert Lee's avatar
Gilbert Lee committed
74
75
76
77
  // 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
78
79
    int numGpuSubExecs = (argc > 3 ? atoi(argv[3]) : 4);
    int numCpuSubExecs = (argc > 4 ? atoi(argv[4]) : 4);
gilbertlee-amd's avatar
gilbertlee-amd committed
80

81
    ev.configMode = CFG_SWEEP;
gilbertlee-amd's avatar
gilbertlee-amd committed
82
    RunSweepPreset(ev, numBytesPerTransfer, numGpuSubExecs, numCpuSubExecs, !strcmp(argv[1], "rsweep"));
Gilbert Lee's avatar
Gilbert Lee committed
83
84
85
    exit(0);
  }
  // - Tests that benchmark peer-to-peer performance
gilbertlee-amd's avatar
gilbertlee-amd committed
86
  else if (!strcmp(argv[1], "p2p"))
Gilbert Lee's avatar
Gilbert Lee committed
87
  {
88
    ev.configMode = CFG_P2P;
gilbertlee-amd's avatar
gilbertlee-amd committed
89
    RunPeerToPeerBenchmarks(ev, numBytesPerTransfer / sizeof(float));
Gilbert Lee's avatar
Gilbert Lee committed
90
91
92
    exit(0);
  }

Gilbert Lee's avatar
Gilbert Lee committed
93
  // Check that Transfer configuration file can be opened
94
  ev.configMode = CFG_FILE;
Gilbert Lee's avatar
Gilbert Lee committed
95
96
97
  FILE* fp = fopen(argv[1], "r");
  if (!fp)
  {
Gilbert Lee's avatar
Gilbert Lee committed
98
    printf("[ERROR] Unable to open transfer configuration file: [%s]\n", argv[1]);
Gilbert Lee's avatar
Gilbert Lee committed
99
100
101
    exit(1);
  }

Gilbert Lee's avatar
Gilbert Lee committed
102
  // Print environment variables and CSV header
Gilbert Lee's avatar
Gilbert Lee committed
103
104
105
  ev.DisplayEnvVars();
  if (ev.outputToCsv)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
106
    printf("Test#,Transfer#,NumBytes,Src,Exe,Dst,CUs,BW(GB/s),Time(ms),SrcAddr,DstAddr\n");
Gilbert Lee's avatar
Gilbert Lee committed
107
108
109
110
111
112
113
114
115
  }

  int testNum = 0;
  char line[2048];
  while(fgets(line, 2048, fp))
  {
    // 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
116
117
118
119
    // Parse set of parallel Transfers to execute
    std::vector<Transfer> transfers;
    ParseTransfers(line, ev.numCpuDevices, ev.numGpuDevices, transfers);
    if (transfers.empty()) continue;
Gilbert Lee's avatar
Gilbert Lee committed
120

gilbertlee-amd's avatar
gilbertlee-amd committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    // 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)
      {
        int delta = std::max(32, N / ev.samplingFactor);
        int curr = N;
        while (curr < N * 2)
        {
          ExecuteTransfers(ev, ++testNum, N, transfers);
          curr += delta;
        }
      }
    }
Gilbert Lee's avatar
Gilbert Lee committed
141
142
  }
  fclose(fp);
Gilbert Lee's avatar
Gilbert Lee committed
143

Gilbert Lee's avatar
Gilbert Lee committed
144
145
  return 0;
}
Gilbert Lee's avatar
Gilbert Lee committed
146

Gilbert Lee's avatar
Gilbert Lee committed
147
void ExecuteTransfers(EnvVars const& ev,
gilbertlee-amd's avatar
gilbertlee-amd committed
148
149
150
151
                      int const testNum,
                      size_t const N,
                      std::vector<Transfer>& transfers,
                      bool verbose)
Gilbert Lee's avatar
Gilbert Lee committed
152
153
{
  int const initOffset = ev.byteOffset / sizeof(float);
Gilbert Lee's avatar
Gilbert Lee committed
154

Gilbert Lee's avatar
Gilbert Lee committed
155
156
  // Map transfers by executor
  TransferMap transferMap;
gilbertlee-amd's avatar
gilbertlee-amd committed
157
  for (Transfer& transfer : transfers)
Gilbert Lee's avatar
Gilbert Lee committed
158
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
159
    Executor executor(transfer.exeType, transfer.exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
160
    ExecutorInfo& executorInfo = transferMap[executor];
gilbertlee-amd's avatar
gilbertlee-amd committed
161
    executorInfo.transfers.push_back(&transfer);
Gilbert Lee's avatar
Gilbert Lee committed
162
  }
Gilbert Lee's avatar
Gilbert Lee committed
163

gilbertlee-amd's avatar
gilbertlee-amd committed
164
  // Loop over each executor and prepare sub-executors
gilbertlee-amd's avatar
gilbertlee-amd committed
165
  std::map<int, Transfer*> transferList;
Gilbert Lee's avatar
Gilbert Lee committed
166
167
168
  for (auto& exeInfoPair : transferMap)
  {
    Executor const& executor = exeInfoPair.first;
gilbertlee-amd's avatar
gilbertlee-amd committed
169
170
171
172
    ExecutorInfo& exeInfo    = exeInfoPair.second;
    ExeType const exeType    = executor.first;
    int     const exeIndex   = RemappedIndex(executor.second, IsCpuType(exeType));

Gilbert Lee's avatar
Gilbert Lee committed
173
    exeInfo.totalTime = 0.0;
gilbertlee-amd's avatar
gilbertlee-amd committed
174
    exeInfo.totalSubExecs = 0;
Gilbert Lee's avatar
Gilbert Lee committed
175
176

    // Loop over each transfer this executor is involved in
gilbertlee-amd's avatar
gilbertlee-amd committed
177
    for (Transfer* transfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
178
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
179
180
181
182
183
184
      // Determine how many bytes to copy for this Transfer (use custom if pre-specified)
      transfer->numBytesActual = (transfer->numBytes ? transfer->numBytes : N * sizeof(float));

      // Allocate source memory
      transfer->srcMem.resize(transfer->numSrcs);
      for (int iSrc = 0; iSrc < transfer->numSrcs; ++iSrc)
Gilbert Lee's avatar
Gilbert Lee committed
185
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
186
187
188
        MemType const& srcType  = transfer->srcType[iSrc];
        int     const  srcIndex    = RemappedIndex(transfer->srcIndex[iSrc], IsCpuType(srcType));

Gilbert Lee's avatar
Gilbert Lee committed
189
        // Ensure executing GPU can access source memory
gilbertlee-amd's avatar
gilbertlee-amd committed
190
        if (IsGpuType(exeType) == MEM_GPU && IsGpuType(srcType) && srcIndex != exeIndex)
Gilbert Lee's avatar
Gilbert Lee committed
191
          EnablePeerAccess(exeIndex, srcIndex);
Gilbert Lee's avatar
Gilbert Lee committed
192

gilbertlee-amd's avatar
gilbertlee-amd committed
193
194
195
196
197
198
199
200
201
202
        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];
        int     const  dstIndex    = RemappedIndex(transfer->dstIndex[iDst], IsCpuType(dstType));

Gilbert Lee's avatar
Gilbert Lee committed
203
        // Ensure executing GPU can access destination memory
gilbertlee-amd's avatar
gilbertlee-amd committed
204
        if (IsGpuType(exeType) == MEM_GPU && IsGpuType(dstType) && dstIndex != exeIndex)
Gilbert Lee's avatar
Gilbert Lee committed
205
206
          EnablePeerAccess(exeIndex, dstIndex);

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

gilbertlee-amd's avatar
gilbertlee-amd committed
210
      exeInfo.totalSubExecs += transfer->numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
211
      transferList[transfer->transferIndex] = transfer;
Gilbert Lee's avatar
Gilbert Lee committed
212
213
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
214
215
    // Prepare additional requirement for GPU-based executors
    if (IsGpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
216
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
217
218
219
220
221
222
      // 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
223
      {
Gilbert Lee's avatar
Gilbert Lee committed
224
225
226
227
228
        HIP_CALL(hipSetDevice(exeIndex));
        HIP_CALL(hipStreamCreate(&exeInfo.streams[i]));
        HIP_CALL(hipEventCreate(&exeInfo.startEvents[i]));
        HIP_CALL(hipEventCreate(&exeInfo.stopEvents[i]));
      }
Gilbert Lee's avatar
Gilbert Lee committed
229

gilbertlee-amd's avatar
gilbertlee-amd committed
230
      if (exeType == EXE_GPU_GFX)
Gilbert Lee's avatar
Gilbert Lee committed
231
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
232
233
234
235
        // 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
        AllocateMemory(MEM_GPU, exeIndex, exeInfo.totalSubExecs * sizeof(SubExecParam),
                       (void**)&exeInfo.subExecParamGpu);
Gilbert Lee's avatar
Gilbert Lee committed
236
237
238
      }
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
239

gilbertlee-amd's avatar
gilbertlee-amd committed
240
241
242
243
  if (verbose && !ev.outputToCsv) printf("Test %d:\n", testNum);

  // Prepare input memory and block parameters for current N
  for (auto& exeInfoPair : transferMap)
Gilbert Lee's avatar
Gilbert Lee committed
244
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
245
246
    ExecutorInfo& exeInfo = exeInfoPair.second;
    exeInfo.totalBytes = 0;
Gilbert Lee's avatar
Gilbert Lee committed
247

gilbertlee-amd's avatar
gilbertlee-amd committed
248
249
    int transferOffset = 0;
    for (int i = 0; i < exeInfo.transfers.size(); ++i)
Gilbert Lee's avatar
Gilbert Lee committed
250
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
251
252
      // 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
253
254
255
      transfer->PrepareSubExecParams(ev);
      transfer->PrepareSrc(ev);
      exeInfo.totalBytes += transfer->numBytesActual;
Gilbert Lee's avatar
Gilbert Lee committed
256

gilbertlee-amd's avatar
gilbertlee-amd committed
257
      // Copy block parameters to GPU for GPU executors
gilbertlee-amd's avatar
gilbertlee-amd committed
258
      if (transfer->exeType == EXE_GPU_GFX)
Gilbert Lee's avatar
Gilbert Lee committed
259
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
260
261
262
263
        exeInfo.transfers[i]->subExecParamGpuPtr = exeInfo.subExecParamGpu + transferOffset;
        HIP_CALL(hipMemcpy(&exeInfo.subExecParamGpu[transferOffset],
                           transfer->subExecParam.data(),
                           transfer->subExecParam.size() * sizeof(SubExecParam),
gilbertlee-amd's avatar
gilbertlee-amd committed
264
                           hipMemcpyHostToDevice));
gilbertlee-amd's avatar
gilbertlee-amd committed
265
266

        transferOffset += transfer->subExecParam.size();
Gilbert Lee's avatar
Gilbert Lee committed
267
268
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
269
  }
Gilbert Lee's avatar
Gilbert Lee committed
270

gilbertlee-amd's avatar
gilbertlee-amd committed
271
272
273
274
275
276
  // Launch kernels (warmup iterations are not counted)
  double totalCpuTime = 0;
  size_t numTimedIterations = 0;
  std::stack<std::thread> threads;
  for (int iteration = -ev.numWarmups; ; iteration++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
277
    if (ev.numIterations > 0 && iteration    >= ev.numIterations) break;
gilbertlee-amd's avatar
gilbertlee-amd committed
278
    if (ev.numIterations < 0 && totalCpuTime > -ev.numIterations) break;
Gilbert Lee's avatar
Gilbert Lee committed
279

gilbertlee-amd's avatar
gilbertlee-amd committed
280
281
    // Pause before starting first timed iteration in interactive mode
    if (verbose && ev.useInteractive && iteration == 0)
Gilbert Lee's avatar
Gilbert Lee committed
282
    {
283
284
285
286
      printf("Memory prepared:\n");

      for (Transfer& transfer : transfers)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
287
288
289
290
291
        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]);
292
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
293
      printf("Hit <Enter> to continue: ");
294
295
296
297
298
      if (scanf("%*c") != 0)
      {
        printf("[ERROR] Unexpected input\n");
        exit(1);
      }
Gilbert Lee's avatar
Gilbert Lee committed
299
300
      printf("\n");
    }
Gilbert Lee's avatar
Gilbert Lee committed
301

gilbertlee-amd's avatar
gilbertlee-amd committed
302
303
304
305
306
    // Start CPU timing for this iteration
    auto cpuStart = std::chrono::high_resolution_clock::now();

    // Execute all Transfers in parallel
    for (auto& exeInfoPair : transferMap)
307
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
308
      ExecutorInfo& exeInfo = exeInfoPair.second;
gilbertlee-amd's avatar
gilbertlee-amd committed
309
310
311
      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
312
313
      for (int i = 0; i < numTransfersToRun; ++i)
        threads.push(std::thread(RunTransfer, std::ref(ev), iteration, std::ref(exeInfo), i));
314
    }
Gilbert Lee's avatar
Gilbert Lee committed
315

gilbertlee-amd's avatar
gilbertlee-amd committed
316
317
318
319
320
321
322
    // 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
323

gilbertlee-amd's avatar
gilbertlee-amd committed
324
325
326
327
328
    // 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();

    if (iteration >= 0)
Gilbert Lee's avatar
Gilbert Lee committed
329
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
330
331
332
333
      ++numTimedIterations;
      totalCpuTime += deltaSec;
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
334

gilbertlee-amd's avatar
gilbertlee-amd committed
335
336
337
338
  // Pause for interactive mode
  if (verbose && ev.useInteractive)
  {
    printf("Transfers complete. Hit <Enter> to continue: ");
339
340
341
342
343
    if (scanf("%*c") != 0)
    {
      printf("[ERROR] Unexpected input\n");
      exit(1);
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
344
345
    printf("\n");
  }
Gilbert Lee's avatar
Gilbert Lee committed
346

gilbertlee-amd's avatar
gilbertlee-amd committed
347
348
349
350
351
352
  // 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
353
354
    transfer->ValidateDst(ev);
    totalBytesTransferred += transfer->numBytesActual;
gilbertlee-amd's avatar
gilbertlee-amd committed
355
  }
Gilbert Lee's avatar
Gilbert Lee committed
356

gilbertlee-amd's avatar
gilbertlee-amd committed
357
358
359
360
  // Report timings
  totalCpuTime = totalCpuTime / (1.0 * numTimedIterations) * 1000;
  double totalBandwidthGbs = (totalBytesTransferred / 1.0E6) / totalCpuTime;
  double maxGpuTime = 0;
Gilbert Lee's avatar
Gilbert Lee committed
361

gilbertlee-amd's avatar
gilbertlee-amd committed
362
363
364
365
  if (ev.useSingleStream)
  {
    for (auto& exeInfoPair : transferMap)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
366
367
368
      ExecutorInfo  exeInfo  = exeInfoPair.second;
      ExeType const exeType  = exeInfoPair.first.first;
      int     const exeIndex = exeInfoPair.first.second;
Gilbert Lee's avatar
Gilbert Lee committed
369

gilbertlee-amd's avatar
gilbertlee-amd committed
370
371
      // Compute total time for non GPU executors
      if (exeType != EXE_GPU_GFX)
gilbertlee-amd's avatar
gilbertlee-amd committed
372
373
374
375
376
      {
        exeInfo.totalTime = 0;
        for (auto const& transfer : exeInfo.transfers)
          exeInfo.totalTime = std::max(exeInfo.totalTime, transfer->transferTime);
      }
377

gilbertlee-amd's avatar
gilbertlee-amd committed
378
379
380
      double exeDurationMsec = exeInfo.totalTime / (1.0 * numTimedIterations);
      double exeBandwidthGbs = (exeInfo.totalBytes / 1.0E9) / exeDurationMsec * 1000.0f;
      maxGpuTime = std::max(maxGpuTime, exeDurationMsec);
Gilbert Lee's avatar
Gilbert Lee committed
381

gilbertlee-amd's avatar
gilbertlee-amd committed
382
383
      if (verbose && !ev.outputToCsv)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
384
385
        printf(" Executor: %3s %02d | %7.3f GB/s | %8.3f ms | %12lu bytes\n",
               ExeTypeName[exeType], exeIndex, exeBandwidthGbs, exeDurationMsec, exeInfo.totalBytes);
Gilbert Lee's avatar
Gilbert Lee committed
386
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
387
388
389

      int totalCUs = 0;
      for (auto const& transfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
390
      {
Gilbert Lee's avatar
Gilbert Lee committed
391
        double transferDurationMsec = transfer->transferTime / (1.0 * numTimedIterations);
gilbertlee-amd's avatar
gilbertlee-amd committed
392
393
        double transferBandwidthGbs = (transfer->numBytesActual / 1.0E9) / transferDurationMsec * 1000.0f;
        totalCUs += transfer->numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
394
395

        if (!verbose) continue;
Gilbert Lee's avatar
Gilbert Lee committed
396
397
        if (!ev.outputToCsv)
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
398
          printf("     Transfer %02d  | %7.3f GB/s | %8.3f ms | %12lu bytes | %s -> %s%02d:%03d -> %s\n",
Gilbert Lee's avatar
Gilbert Lee committed
399
                 transfer->transferIndex,
gilbertlee-amd's avatar
gilbertlee-amd committed
400
401
                 transferBandwidthGbs,
                 transferDurationMsec,
gilbertlee-amd's avatar
gilbertlee-amd committed
402
403
404
405
406
                 transfer->numBytesActual,
                 transfer->SrcToStr().c_str(),
                 ExeTypeName[transfer->exeType], transfer->exeIndex,
                 transfer->numSubExecs,
                 transfer->DstToStr().c_str());
Gilbert Lee's avatar
Gilbert Lee committed
407
408
409
        }
        else
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
410
411
412
413
414
415
          printf("%d,%d,%lu,%s,%c%02d,%s,%d,%.3f,%.3f,%s,%s\n",
                 testNum, transfer->transferIndex, transfer->numBytesActual,
                 transfer->SrcToStr().c_str(),
                 MemTypeStr[transfer->exeType], transfer->exeIndex,
                 transfer->DstToStr().c_str(),
                 transfer->numSubExecs,
Gilbert Lee's avatar
Gilbert Lee committed
416
                 transferBandwidthGbs, transferDurationMsec,
gilbertlee-amd's avatar
gilbertlee-amd committed
417
418
                 PtrVectorToStr(transfer->srcMem, initOffset).c_str(),
                 PtrVectorToStr(transfer->dstMem, initOffset).c_str());
Gilbert Lee's avatar
Gilbert Lee committed
419
        }
Gilbert Lee's avatar
Gilbert Lee committed
420
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
421
422
423

      if (verbose && ev.outputToCsv)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
424
        printf("%d,ALL,%lu,ALL,%c%02d,ALL,%d,%.3f,%.3f,ALL,ALL\n",
gilbertlee-amd's avatar
gilbertlee-amd committed
425
               testNum, totalBytesTransferred,
gilbertlee-amd's avatar
gilbertlee-amd committed
426
               MemTypeStr[exeType], exeIndex, totalCUs,
gilbertlee-amd's avatar
gilbertlee-amd committed
427
428
               exeBandwidthGbs, exeDurationMsec);
      }
Gilbert Lee's avatar
Gilbert Lee committed
429
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
430
431
432
433
434
435
436
  }
  else
  {
    for (auto const& transferPair : transferList)
    {
      Transfer* transfer = transferPair.second;
      double transferDurationMsec = transfer->transferTime / (1.0 * numTimedIterations);
gilbertlee-amd's avatar
gilbertlee-amd committed
437
      double transferBandwidthGbs = (transfer->numBytesActual / 1.0E9) / transferDurationMsec * 1000.0f;
gilbertlee-amd's avatar
gilbertlee-amd committed
438
439
440
441
      maxGpuTime = std::max(maxGpuTime, transferDurationMsec);
      if (!verbose) continue;
      if (!ev.outputToCsv)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
442
        printf(" Transfer %02d      | %7.3f GB/s | %8.3f ms | %12lu bytes | %s -> %s%02d:%03d -> %s\n",
gilbertlee-amd's avatar
gilbertlee-amd committed
443
444
               transfer->transferIndex,
               transferBandwidthGbs, transferDurationMsec,
gilbertlee-amd's avatar
gilbertlee-amd committed
445
446
447
448
449
               transfer->numBytesActual,
               transfer->SrcToStr().c_str(),
               ExeTypeName[transfer->exeType], transfer->exeIndex,
               transfer->numSubExecs,
               transfer->DstToStr().c_str());
gilbertlee-amd's avatar
gilbertlee-amd committed
450
451
452
      }
      else
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
453
454
455
456
457
458
        printf("%d,%d,%lu,%s,%s%02d,%s,%d,%.3f,%.3f,%s,%s\n",
               testNum, transfer->transferIndex, transfer->numBytesActual,
               transfer->SrcToStr().c_str(),
               ExeTypeName[transfer->exeType], transfer->exeIndex,
               transfer->DstToStr().c_str(),
               transfer->numSubExecs,
gilbertlee-amd's avatar
gilbertlee-amd committed
459
               transferBandwidthGbs, transferDurationMsec,
gilbertlee-amd's avatar
gilbertlee-amd committed
460
461
               PtrVectorToStr(transfer->srcMem, initOffset).c_str(),
               PtrVectorToStr(transfer->dstMem, initOffset).c_str());
gilbertlee-amd's avatar
gilbertlee-amd committed
462
463
464
      }
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
465

gilbertlee-amd's avatar
gilbertlee-amd committed
466
467
468
  // Display aggregate statistics
  if (verbose)
  {
Gilbert Lee's avatar
Gilbert Lee committed
469
    if (!ev.outputToCsv)
Gilbert Lee's avatar
Gilbert Lee committed
470
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
471
      printf(" Aggregate (CPU)  | %7.3f GB/s | %8.3f ms | %12lu bytes | Overhead: %.3f ms\n",
472
             totalBandwidthGbs, totalCpuTime, totalBytesTransferred, totalCpuTime - maxGpuTime);
Gilbert Lee's avatar
Gilbert Lee committed
473
474
475
    }
    else
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
476
      printf("%d,ALL,%lu,ALL,ALL,ALL,ALL,%.3f,%.3f,ALL,ALL\n",
477
             testNum, totalBytesTransferred, totalBandwidthGbs, totalCpuTime);
Gilbert Lee's avatar
Gilbert Lee committed
478
479
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
480

Gilbert Lee's avatar
Gilbert Lee committed
481
482
483
  // Release GPU memory
  for (auto exeInfoPair : transferMap)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
484
485
486
487
    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
488
489
    for (auto& transfer : exeInfo.transfers)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
490
491
492
493
494
495
496
497
498
499
500
      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();
Gilbert Lee's avatar
Gilbert Lee committed
501
502
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
503
    if (IsGpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
504
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
505
506
      int const numStreams = (int)exeInfo.streams.size();
      for (int i = 0; i < numStreams; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
507
      {
Gilbert Lee's avatar
Gilbert Lee committed
508
509
510
        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
511
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
512
513
514
515
516

      if (exeType == EXE_GPU_GFX)
      {
        DeallocateMemory(MEM_GPU, exeInfo.subExecParamGpu);
      }
Gilbert Lee's avatar
Gilbert Lee committed
517
518
519
520
521
522
    }
  }
}

void DisplayUsage(char const* cmdName)
{
Gilbert Lee's avatar
Gilbert Lee committed
523
  printf("TransferBench v%s\n", TB_VERSION);
Gilbert Lee's avatar
Gilbert Lee committed
524
525
526
527
528
529
530
531
532
533
534
535
536
  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
537
  printf("          - Filename of configFile containing Transfers to execute (see example.cfg for format)\n");
gilbertlee-amd's avatar
gilbertlee-amd committed
538
539
540
541
  printf("          - Name of preset config:\n");
  printf("              p2p          - Peer-to-peer benchmark tests\n");
  printf("              sweep/rsweep - Sweep/random sweep across possible sets of Transfers\n");
  printf("                             - 3rd/4th optional args for # GPU SubExecs / # CPU SubExecs per Transfer\n");
Gilbert Lee's avatar
Gilbert Lee committed
542
  printf("  N     : (Optional) Number of bytes to copy per Transfer.\n");
Gilbert Lee's avatar
Gilbert Lee committed
543
  printf("          If not specified, defaults to %lu bytes. Must be a multiple of 4 bytes\n",
Gilbert Lee's avatar
Gilbert Lee committed
544
         DEFAULT_BYTES_PER_TRANSFER);
Gilbert Lee's avatar
Gilbert Lee committed
545
546
547
548
549
550
551
  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
552
int RemappedIndex(int const origIdx, bool const isCpuType)
Gilbert Lee's avatar
Gilbert Lee committed
553
{
554
555
  static std::vector<int> remappingCpu;
  static std::vector<int> remappingGpu;
Gilbert Lee's avatar
Gilbert Lee committed
556

557
558
559
560
561
562
563
564
  // 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
565

566
567
  // Build remappingGpu on first use
  if (remappingGpu.empty())
Gilbert Lee's avatar
Gilbert Lee committed
568
569
570
  {
    int numGpuDevices;
    HIP_CALL(hipGetDeviceCount(&numGpuDevices));
571
    remappingGpu.resize(numGpuDevices);
Gilbert Lee's avatar
Gilbert Lee committed
572
573
574
575

    int const usePcieIndexing = getenv("USE_PCIE_INDEX") ? atoi(getenv("USE_PCIE_INDEX")) : 0;
    if (!usePcieIndexing)
    {
576
      // For HIP-based indexing no remappingGpu is necessary
Gilbert Lee's avatar
Gilbert Lee committed
577
      for (int i = 0; i < numGpuDevices; ++i)
578
        remappingGpu[i] = i;
Gilbert Lee's avatar
Gilbert Lee committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    }
    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)
593
        remappingGpu[i] = mapping[i].second;
Gilbert Lee's avatar
Gilbert Lee committed
594
595
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
596
  return isCpuType ? remappingCpu[origIdx] : remappingGpu[origIdx];
Gilbert Lee's avatar
Gilbert Lee committed
597
598
599
600
}

void DisplayTopology(bool const outputToCsv)
{
601

602
  int numCpuDevices = numa_num_configured_nodes();
Gilbert Lee's avatar
Gilbert Lee committed
603
604
605
606
607
  int numGpuDevices;
  HIP_CALL(hipGetDeviceCount(&numGpuDevices));

  if (outputToCsv)
  {
608
    printf("NumCpus,%d\n", numCpuDevices);
Gilbert Lee's avatar
Gilbert Lee committed
609
    printf("NumGpus,%d\n", numGpuDevices);
610
611
612
  }
  else
  {
613
614
    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);
615
616
617
618
619
620
621
622
  }

  // Print out detected CPU topology
  if (outputToCsv)
  {
    printf("NUMA");
    for (int j = 0; j < numCpuDevices; j++)
      printf(",NUMA%02d", j);
623
    printf(",# CPUs,ClosestGPUs,ActualNode\n");
624
625
626
  }
  else
  {
627
    printf("            |");
628
    for (int j = 0; j < numCpuDevices; j++)
629
630
631
632
      printf("NUMA %02d|", j);
    printf(" #Cpus | Closest GPU(s)\n");

    printf("------------+");
633
    for (int j = 0; j <= numCpuDevices; j++)
634
635
      printf("-------+");
    printf("---------------\n");
636
637
638
639
  }

  for (int i = 0; i < numCpuDevices; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
640
    int nodeI = RemappedIndex(i, true);
641
    printf("NUMA %02d (%02d)%s", i, nodeI, outputToCsv ? "," : "|");
642
643
    for (int j = 0; j < numCpuDevices; j++)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
644
      int nodeJ = RemappedIndex(j, true);
645
      int numaDist = numa_distance(nodeI, nodeJ);
646
      if (outputToCsv)
gilbertlee-amd's avatar
gilbertlee-amd committed
647
        printf("%d,", numaDist);
648
      else
649
        printf(" %5d |", numaDist);
650
651
652
653
    }

    int numCpus = 0;
    for (int j = 0; j < numa_num_configured_cpus(); j++)
654
      if (numa_node_of_cpu(j) == nodeI) numCpus++;
655
656
657
    if (outputToCsv)
      printf("%d,", numCpus);
    else
658
      printf(" %5d | ", numCpus);
659

660
#if !defined(__NVCC__)
661
662
663
    bool isFirst = true;
    for (int j = 0; j < numGpuDevices; j++)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
664
      if (GetClosestNumaNode(RemappedIndex(j, false)) == i)
665
666
      {
        if (isFirst) isFirst = false;
gilbertlee-amd's avatar
gilbertlee-amd committed
667
668
        else printf(",");
        printf("%d", j);
669
670
      }
    }
671
#endif
672
673
674
675
    printf("\n");
  }
  printf("\n");

676
677
678
679
680
#if defined(__NVCC__)
  // No further topology detection done for NVIDIA platforms
  return;
#endif

681
682
683
  // Print out detected GPU topology
  if (outputToCsv)
  {
Gilbert Lee's avatar
Gilbert Lee committed
684
685
686
687
688
689
690
    printf("GPU");
    for (int j = 0; j < numGpuDevices; j++)
      printf(",GPU %02d", j);
    printf(",PCIe Bus ID,ClosestNUMA\n");
  }
  else
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
691
692
693
694
695
696
697
698
699
700
    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
701
702
703
    printf("        |");
    for (int j = 0; j < numGpuDevices; j++)
      printf(" GPU %02d |", j);
gilbertlee-amd's avatar
gilbertlee-amd committed
704
    printf(" PCIe Bus ID  | #CUs | Closest NUMA\n");
Gilbert Lee's avatar
Gilbert Lee committed
705
706
    for (int j = 0; j <= numGpuDevices; j++)
      printf("--------+");
gilbertlee-amd's avatar
gilbertlee-amd committed
707
    printf("--------------+------+-------------\n");
Gilbert Lee's avatar
Gilbert Lee committed
708
709
  }

710
#if !defined(__NVCC__)
Gilbert Lee's avatar
Gilbert Lee committed
711
712
713
  char pciBusId[20];
  for (int i = 0; i < numGpuDevices; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
714
    int const deviceIdx = RemappedIndex(i, false);
Gilbert Lee's avatar
Gilbert Lee committed
715
716
717
718
719
720
721
722
723
724
725
726
727
    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
728
729
        HIP_CALL(hipExtGetLinkTypeAndHopCount(deviceIdx,
                                              RemappedIndex(j, false),
Gilbert Lee's avatar
Gilbert Lee committed
730
731
732
733
734
735
736
737
738
739
740
                                              &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
741
742
743
744
745
    HIP_CALL(hipDeviceGetPCIBusId(pciBusId, 20, deviceIdx));

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

Gilbert Lee's avatar
Gilbert Lee committed
746
    if (outputToCsv)
gilbertlee-amd's avatar
gilbertlee-amd committed
747
      printf("%s,%d,%d\n", pciBusId, numDeviceCUs, GetClosestNumaNode(deviceIdx));
Gilbert Lee's avatar
Gilbert Lee committed
748
    else
gilbertlee-amd's avatar
gilbertlee-amd committed
749
      printf(" %11s | %4d | %d\n", pciBusId, numDeviceCUs, GetClosestNumaNode(deviceIdx));
Gilbert Lee's avatar
Gilbert Lee committed
750
  }
751
#endif
Gilbert Lee's avatar
Gilbert Lee committed
752
753
}

gilbertlee-amd's avatar
gilbertlee-amd committed
754
755
void ParseMemType(std::string const& token, int const numCpus, int const numGpus,
                  std::vector<MemType>& memTypes, std::vector<int>& memIndices)
Gilbert Lee's avatar
Gilbert Lee committed
756
757
{
  char typeChar;
gilbertlee-amd's avatar
gilbertlee-amd committed
758
759
  int offset = 0, devIndex, inc;
  bool found = false;
Gilbert Lee's avatar
Gilbert Lee committed
760

gilbertlee-amd's avatar
gilbertlee-amd committed
761
762
763
  memTypes.clear();
  memIndices.clear();
  while (sscanf(token.c_str() + offset, " %c %d%n", &typeChar, &devIndex, &inc) == 2)
Gilbert Lee's avatar
Gilbert Lee committed
764
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
765
766
767
768
    offset += inc;
    MemType memType = CharToMemType(typeChar);

    if (IsCpuType(memType) && (devIndex < 0 || devIndex >= numCpus))
Gilbert Lee's avatar
Gilbert Lee committed
769
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
770
      printf("[ERROR] CPU index must be between 0 and %d (instead of %d)\n", numCpus-1, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
771
772
      exit(1);
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
773
    if (IsGpuType(memType) && (devIndex < 0 || devIndex >= numGpus))
Gilbert Lee's avatar
Gilbert Lee committed
774
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
775
      printf("[ERROR] GPU index must be between 0 and %d (instead of %d)\n", numGpus-1, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
776
777
      exit(1);
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813

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

void ParseExeType(std::string const& token, int const numCpus, int const numGpus,
                  ExeType &exeType, int& exeIndex)
{
  char typeChar;
  if (sscanf(token.c_str(), " %c%d", &typeChar, &exeIndex) != 2)
  {
    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);

  if (IsCpuType(exeType) && (exeIndex < 0 || exeIndex >= numCpus))
  {
    printf("[ERROR] CPU index must be between 0 and %d (instead of %d)\n", numCpus-1, exeIndex);
    exit(1);
  }
  if (IsGpuType(exeType) && (exeIndex < 0 || exeIndex >= numGpus))
  {
    printf("[ERROR] GPU index must be between 0 and %d (instead of %d)\n", numGpus-1, exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
814
815
816
817
    exit(1);
  }
}

Gilbert Lee's avatar
Gilbert Lee committed
818
// Helper function to parse a list of Transfer definitions
Gilbert Lee's avatar
Gilbert Lee committed
819
void ParseTransfers(char* line, int numCpus, int numGpus, std::vector<Transfer>& transfers)
Gilbert Lee's avatar
Gilbert Lee committed
820
821
822
823
824
{
  // 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
825
  transfers.clear();
Gilbert Lee's avatar
Gilbert Lee committed
826

Gilbert Lee's avatar
Gilbert Lee committed
827
  int numTransfers = 0;
Gilbert Lee's avatar
Gilbert Lee committed
828
  std::istringstream iss(line);
Gilbert Lee's avatar
Gilbert Lee committed
829
  iss >> numTransfers;
Gilbert Lee's avatar
Gilbert Lee committed
830
831
832
833
834
  if (iss.fail()) return;

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

gilbertlee-amd's avatar
gilbertlee-amd committed
836
  // If numTransfers < 0, read 5-tuple (srcMem, exeMem, dstMem, #CUs, #Bytes)
Gilbert Lee's avatar
Gilbert Lee committed
837
  // otherwise read triples (srcMem, exeMem, dstMem)
gilbertlee-amd's avatar
gilbertlee-amd committed
838
  bool const advancedMode = (numTransfers < 0);
Gilbert Lee's avatar
Gilbert Lee committed
839
840
  numTransfers = abs(numTransfers);

gilbertlee-amd's avatar
gilbertlee-amd committed
841
  int numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
842
  if (!advancedMode)
Gilbert Lee's avatar
Gilbert Lee committed
843
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
844
845
    iss >> numSubExecs;
    if (numSubExecs <= 0 || iss.fail())
Gilbert Lee's avatar
Gilbert Lee committed
846
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
847
      printf("Parsing error: Number of blocks to use (%d) must be greater than 0\n", numSubExecs);
Gilbert Lee's avatar
Gilbert Lee committed
848
849
850
851
      exit(1);
    }
  }

gilbertlee-amd's avatar
gilbertlee-amd committed
852
  size_t numBytes = 0;
Gilbert Lee's avatar
Gilbert Lee committed
853
854
855
856
  for (int i = 0; i < numTransfers; i++)
  {
    Transfer transfer;
    transfer.transferIndex = i;
gilbertlee-amd's avatar
gilbertlee-amd committed
857
    transfer.numBytes = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
858
    transfer.numBytesActual = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
859
    if (!advancedMode)
Gilbert Lee's avatar
Gilbert Lee committed
860
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
861
862
863
864
865
866
867
868
869
870
      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
871
      iss >> srcMem >> exeMem >> dstMem >> numSubExecs >> numBytesToken;
gilbertlee-amd's avatar
gilbertlee-amd committed
872
873
874
875
876
877
878
879
880
881
882
      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
883
      switch (toupper(units))
gilbertlee-amd's avatar
gilbertlee-amd committed
884
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
885
886
887
      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
888
      }
Gilbert Lee's avatar
Gilbert Lee committed
889
    }
Gilbert Lee's avatar
Gilbert Lee committed
890

gilbertlee-amd's avatar
gilbertlee-amd committed
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
    ParseMemType(srcMem, numCpus, numGpus, transfer.srcType, transfer.srcIndex);
    ParseMemType(dstMem, numCpus, numGpus, transfer.dstType, transfer.dstIndex);
    ParseExeType(exeMem, numCpus, numGpus, transfer.exeType, transfer.exeIndex);

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

    if (transfer.exeType == EXE_GPU_DMA && (transfer.numSrcs > 1 || transfer.numDsts > 1))
    {
      printf("[ERROR] GPU DMA executor can only be used for single source / single dst Transfers\n");
      exit(1);
    }

    transfer.numSubExecs = numSubExecs;
gilbertlee-amd's avatar
gilbertlee-amd committed
910
    transfer.numBytes = numBytes;
Gilbert Lee's avatar
Gilbert Lee committed
911
    transfers.push_back(transfer);
Gilbert Lee's avatar
Gilbert Lee committed
912
913
914
915
916
917
918
919
920
921
922
923
924
  }
}

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
925
926
927
928
929
930
931
  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
932
933
934
935
936
937
938
939
940
941
}

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
942
  if (IsCpuType(memType))
Gilbert Lee's avatar
Gilbert Lee committed
943
944
  {
    // Set numa policy prior to call to hipHostMalloc
945
    numa_set_preferred(devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
946
947
948
949

    // Allocate host-pinned memory (should respect NUMA mem policy)
    if (memType == MEM_CPU_FINE)
    {
950
951
952
953
#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
954
      HIP_CALL(hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser));
955
#endif
Gilbert Lee's avatar
Gilbert Lee committed
956
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
957
    else if (memType == MEM_CPU)
Gilbert Lee's avatar
Gilbert Lee committed
958
    {
959
960
961
#if defined (__NVCC__)
      if (hipHostMalloc((void **)memPtr, numBytes, 0) != hipSuccess)
#else
962
      if (hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser | hipHostMallocNonCoherent) != hipSuccess)
963
#endif
964
965
966
967
      {
        printf("[ERROR] Unable to allocate non-coherent host memory on NUMA node %d\n", devIndex);
        exit(1);
      }
Gilbert Lee's avatar
Gilbert Lee committed
968
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
969
970
971
972
    else if (memType == MEM_CPU_UNPINNED)
    {
      *memPtr = numa_alloc_onnode(numBytes, devIndex);
    }
Gilbert Lee's avatar
Gilbert Lee committed
973
974

    // Check that the allocated pages are actually on the correct NUMA node
gilbertlee-amd's avatar
gilbertlee-amd committed
975
976
    memset(*memPtr, 0, numBytes);
    CheckPages((char*)*memPtr, numBytes, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
977
978

    // Reset to default numa mem policy
979
    numa_set_preferred(-1);
Gilbert Lee's avatar
Gilbert Lee committed
980
981
982
983
984
985
986
987
988
  }
  else 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)
  {
989
990
991
992
#if defined (__NVCC__)
    printf("[ERROR] Fine-grained GPU memory not supported on NVIDIA platform\n");
    exit(1);
#else
Gilbert Lee's avatar
Gilbert Lee committed
993
994
    HIP_CALL(hipSetDevice(devIndex));
    HIP_CALL(hipExtMallocWithFlags((void**)memPtr, numBytes, hipDeviceMallocFinegrained));
995
#endif
Gilbert Lee's avatar
Gilbert Lee committed
996
997
998
999
1000
1001
1002
1003
  }
  else
  {
    printf("[ERROR] Unsupported memory type %d\n", memType);
    exit(1);
  }
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1004
void DeallocateMemory(MemType memType, void* memPtr, size_t const bytes)
Gilbert Lee's avatar
Gilbert Lee committed
1005
1006
1007
1008
1009
{
  if (memType == MEM_CPU || memType == MEM_CPU_FINE)
  {
    HIP_CALL(hipHostFree(memPtr));
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1010
1011
1012
1013
  else if (memType == MEM_CPU_UNPINNED)
  {
    numa_free(memPtr, bytes);
  }
Gilbert Lee's avatar
Gilbert Lee committed
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
  else if (memType == MEM_GPU || memType == MEM_GPU_FINE)
  {
    HIP_CALL(hipFree(memPtr));
  }
}

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);
    printf("[ERROR] Ensure up-to-date ROCm is installed\n");
    exit(1);
  }
}

1059
void RunTransfer(EnvVars const& ev, int const iteration,
Gilbert Lee's avatar
Gilbert Lee committed
1060
                 ExecutorInfo& exeInfo, int const transferIdx)
Gilbert Lee's avatar
Gilbert Lee committed
1061
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1062
  Transfer* transfer = exeInfo.transfers[transferIdx];
Gilbert Lee's avatar
Gilbert Lee committed
1063

gilbertlee-amd's avatar
gilbertlee-amd committed
1064
  if (transfer->exeType == EXE_GPU_GFX)
Gilbert Lee's avatar
Gilbert Lee committed
1065
1066
  {
    // Switch to executing GPU
gilbertlee-amd's avatar
gilbertlee-amd committed
1067
    int const exeIndex = RemappedIndex(transfer->exeIndex, false);
Gilbert Lee's avatar
Gilbert Lee committed
1068
1069
    HIP_CALL(hipSetDevice(exeIndex));

Gilbert Lee's avatar
Gilbert Lee committed
1070
1071
1072
    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
1073

gilbertlee-amd's avatar
gilbertlee-amd committed
1074
1075
1076
1077
    // 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;
1078
1079
1080
1081
1082
#if defined(__NVCC__)
    HIP_CALL(hipEventRecord(startEvent, stream));
    GpuKernelTable[ev.gpuKernel]<<<numBlocksToRun, BLOCKSIZE, ev.sharedMemBytes, stream>>>(transfer->subExecParamGpuPtr);
    HIP_CALL(hipEventRecord(stopEvent, stream));
#else
gilbertlee-amd's avatar
gilbertlee-amd committed
1083
1084
1085
1086
1087
1088
    hipExtLaunchKernelGGL(GpuKernelTable[ev.gpuKernel],
                          dim3(numBlocksToRun, 1, 1),
                          dim3(BLOCKSIZE, 1, 1),
                          ev.sharedMemBytes, stream,
                          startEvent, stopEvent,
                          0, transfer->subExecParamGpuPtr);
1089
#endif
Gilbert Lee's avatar
Gilbert Lee committed
1090
1091
    // 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
1092
    HIP_CALL(hipStreamSynchronize(stream));
Gilbert Lee's avatar
Gilbert Lee committed
1093
1094
1095
1096

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

Gilbert Lee's avatar
Gilbert Lee committed
1100
1101
      if (ev.useSingleStream)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1102
        // Figure out individual timings for Transfers that were all launched together
gilbertlee-amd's avatar
gilbertlee-amd committed
1103
        for (Transfer* currTransfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
1104
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
1105
1106
1107
          long long minStartCycle = currTransfer->subExecParamGpuPtr[0].startCycle;
          long long maxStopCycle  = currTransfer->subExecParamGpuPtr[0].stopCycle;
          for (int i = 1; i < currTransfer->numSubExecs; i++)
Gilbert Lee's avatar
Gilbert Lee committed
1108
          {
gilbertlee-amd's avatar
gilbertlee-amd committed
1109
1110
            minStartCycle = std::min(minStartCycle, currTransfer->subExecParamGpuPtr[i].startCycle);
            maxStopCycle  = std::max(maxStopCycle,  currTransfer->subExecParamGpuPtr[i].stopCycle);
Gilbert Lee's avatar
Gilbert Lee committed
1111
          }
Gilbert Lee's avatar
Gilbert Lee committed
1112
1113
          int const wallClockRate = GetWallClockRate(exeIndex);
          double iterationTimeMs = (maxStopCycle - minStartCycle) / (double)(wallClockRate);
gilbertlee-amd's avatar
gilbertlee-amd committed
1114
          currTransfer->transferTime += iterationTimeMs;
Gilbert Lee's avatar
Gilbert Lee committed
1115
        }
Gilbert Lee's avatar
Gilbert Lee committed
1116
1117
1118
1119
        exeInfo.totalTime += gpuDeltaMsec;
      }
      else
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1120
        transfer->transferTime += gpuDeltaMsec;
Gilbert Lee's avatar
Gilbert Lee committed
1121
1122
1123
      }
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
  else if (transfer->exeType == EXE_GPU_DMA)
  {
    // Switch to executing GPU
    int const exeIndex = RemappedIndex(transfer->exeIndex, false);
    HIP_CALL(hipSetDevice(exeIndex));

    hipStream_t& stream     = exeInfo.streams[transferIdx];
    hipEvent_t&  startEvent = exeInfo.startEvents[transferIdx];
    hipEvent_t&  stopEvent  = exeInfo.stopEvents[transferIdx];

    HIP_CALL(hipEventRecord(startEvent, stream));
    if (transfer->numSrcs == 0 && transfer->numDsts == 1)
    {
      HIP_CALL(hipMemsetAsync(transfer->dstMem[0],
                              MEMSET_CHAR, transfer->numBytesActual, stream));
    }
    else if (transfer->numSrcs == 1 && transfer->numDsts == 1)
    {
      HIP_CALL(hipMemcpyAsync(transfer->dstMem[0], transfer->srcMem[0],
                              transfer->numBytesActual, hipMemcpyDefault,
                              stream));
    }
    HIP_CALL(hipEventRecord(stopEvent, stream));
    HIP_CALL(hipStreamSynchronize(stream));

    if (iteration >= 0)
    {
      // Record GPU timing
      float gpuDeltaMsec;
      HIP_CALL(hipEventElapsedTime(&gpuDeltaMsec, startEvent, stopEvent));
      transfer->transferTime += gpuDeltaMsec;
    }
  }
  else if (transfer->exeType == EXE_CPU) // CPU execution agent
Gilbert Lee's avatar
Gilbert Lee committed
1158
1159
  {
    // Force this thread and all child threads onto correct NUMA node
gilbertlee-amd's avatar
gilbertlee-amd committed
1160
    int const exeIndex = RemappedIndex(transfer->exeIndex, true);
1161
    if (numa_run_on_node(exeIndex))
Gilbert Lee's avatar
Gilbert Lee committed
1162
    {
1163
      printf("[ERROR] Unable to set CPU to NUMA node %d\n", exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1164
1165
1166
1167
1168
1169
1170
      exit(1);
    }

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

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

gilbertlee-amd's avatar
gilbertlee-amd committed
1171
1172
1173
    // 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
1174
1175

    // Wait for child-threads to finish
gilbertlee-amd's avatar
gilbertlee-amd committed
1176
    for (int i = 0; i < transfer->numSubExecs; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
1177
1178
1179
1180
1181
1182
      childThreads[i].join();

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

    // Record time if not a warmup iteration
    if (iteration >= 0)
gilbertlee-amd's avatar
gilbertlee-amd committed
1183
      transfer->transferTime += (std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0);
Gilbert Lee's avatar
Gilbert Lee committed
1184
1185
1186
  }
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1187
void RunPeerToPeerBenchmarks(EnvVars const& ev, size_t N)
Gilbert Lee's avatar
Gilbert Lee committed
1188
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1189
1190
  ev.DisplayP2PBenchmarkEnvVars();

Gilbert Lee's avatar
Gilbert Lee committed
1191
  // Collect the number of available CPUs/GPUs on this machine
gilbertlee-amd's avatar
gilbertlee-amd committed
1192
1193
  int const numCpus    = ev.numCpuDevices;
  int const numGpus    = ev.numGpuDevices;
Gilbert Lee's avatar
Gilbert Lee committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
  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++)
  {
    // Print header
    if (!ev.outputToCsv)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
1207
1208
1209
1210
1211
1212
1213
1214
      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");

      printf("%10s", "SRC\\DST");
      for (int i = 0; i < numCpus; i++) printf("%7s %02d", "CPU", i);
      for (int i = 0; i < numGpus; i++) printf("%7s %02d", "GPU", i);
Gilbert Lee's avatar
Gilbert Lee committed
1215
1216
1217
1218
1219
1220
      printf("\n");
    }

    // Loop over all possible src/dst pairs
    for (int src = 0; src < numDevices; src++)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
1221
1222
1223
      MemType const srcType  = (src < numCpus ? MEM_CPU : MEM_GPU);
      int     const srcIndex = (srcType == MEM_CPU ? src : src - numCpus);

Gilbert Lee's avatar
Gilbert Lee committed
1224
      if (!ev.outputToCsv)
gilbertlee-amd's avatar
gilbertlee-amd committed
1225
1226
        printf("%7s %02d", (srcType == MEM_CPU) ? "CPU" : "GPU", srcIndex);

Gilbert Lee's avatar
Gilbert Lee committed
1227
1228
      for (int dst = 0; dst < numDevices; dst++)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1229
1230
1231
1232
        MemType const dstType  = (dst < numCpus ? MEM_CPU : MEM_GPU);
        int     const dstIndex = (dstType == MEM_CPU ? dst : dst - numCpus);

        double bandwidth = GetPeakBandwidth(ev, N, isBidirectional, srcType, srcIndex, dstType, dstIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1233
1234
1235
1236
1237
1238
1239
1240
1241
        if (!ev.outputToCsv)
        {
          if (bandwidth == 0)
            printf("%10s", "N/A");
          else
            printf("%10.2f", bandwidth);
        }
        else
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
1242
1243
1244
          printf("%s %02d,%s %02d,%s,%s,%s,%.2f,%lu\n",
                 srcType == MEM_CPU ? "CPU" : "GPU", srcIndex,
                 dstType == MEM_CPU ? "CPU" : "GPU", dstIndex,
Gilbert Lee's avatar
Gilbert Lee committed
1245
                 isBidirectional ? "bidirectional" : "unidirectional",
gilbertlee-amd's avatar
gilbertlee-amd committed
1246
1247
                 ev.useRemoteRead ? "Remote" : "Local",
                 ev.useDmaCopy ? "DMA" : "GFX",
Gilbert Lee's avatar
Gilbert Lee committed
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
                 bandwidth,
                 N * sizeof(float));
        }
        fflush(stdout);
      }
      if (!ev.outputToCsv) printf("\n");
    }
    if (!ev.outputToCsv) printf("\n");
  }
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1259
double GetPeakBandwidth(EnvVars const& ev, size_t const N,
Gilbert Lee's avatar
Gilbert Lee committed
1260
                        int     const  isBidirectional,
gilbertlee-amd's avatar
gilbertlee-amd committed
1261
1262
                        MemType const  srcType, int const srcIndex,
                        MemType const  dstType, int const dstIndex)
Gilbert Lee's avatar
Gilbert Lee committed
1263
1264
{
  // Skip bidirectional on same device
gilbertlee-amd's avatar
gilbertlee-amd committed
1265
  if (isBidirectional && srcType == dstType && srcIndex == dstIndex) return 0.0f;
Gilbert Lee's avatar
Gilbert Lee committed
1266

Gilbert Lee's avatar
Gilbert Lee committed
1267
  // Prepare Transfers
gilbertlee-amd's avatar
gilbertlee-amd committed
1268
  std::vector<Transfer> transfers(2);
gilbertlee-amd's avatar
gilbertlee-amd committed
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
  transfers[0].numBytes = transfers[1].numBytes = N * sizeof(float);

  // SRC -> DST
  transfers[0].numSrcs = transfers[0].numDsts = 1;
  transfers[0].srcType.push_back(srcType);
  transfers[0].dstType.push_back(dstType);
  transfers[0].srcIndex.push_back(srcIndex);
  transfers[0].dstIndex.push_back(dstIndex);

  // DST -> SRC
  transfers[1].numSrcs = transfers[1].numDsts = 1;
  transfers[1].srcType.push_back(dstType);
  transfers[1].dstType.push_back(srcType);
  transfers[1].srcIndex.push_back(dstIndex);
  transfers[1].dstIndex.push_back(srcIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1284
1285

  // Either perform (local read + remote write), or (remote read + local write)
gilbertlee-amd's avatar
gilbertlee-amd committed
1286
1287
1288
1289
1290
1291
1292
1293
1294
  ExeType gpuExeType = ev.useDmaCopy ? EXE_GPU_DMA : EXE_GPU_GFX;
  transfers[0].exeType = IsGpuType(ev.useRemoteRead ? dstType : srcType) ? gpuExeType : EXE_CPU;
  transfers[1].exeType = IsGpuType(ev.useRemoteRead ? srcType : dstType) ? gpuExeType : EXE_CPU;
  transfers[0].exeIndex = (ev.useRemoteRead ? dstIndex : srcIndex);
  transfers[1].exeIndex = (ev.useRemoteRead ? srcIndex : dstIndex);
  transfers[0].numSubExecs = IsGpuType(transfers[0].exeType) ? ev.numGpuSubExecs : ev.numCpuSubExecs;
  transfers[1].numSubExecs = IsGpuType(transfers[0].exeType) ? ev.numGpuSubExecs : ev.numCpuSubExecs;

  // Remove (DST->SRC) if not bidirectional
gilbertlee-amd's avatar
gilbertlee-amd committed
1295
  transfers.resize(isBidirectional + 1);
Gilbert Lee's avatar
Gilbert Lee committed
1296

1297
1298
1299
  // Abort if executing on NUMA node with no CPUs
  for (int i = 0; i <= isBidirectional; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1300
    if (transfers[i].exeType == EXE_CPU && ev.numCpusPerNuma[transfers[i].exeIndex] == 0)
1301
      return 0;
1302
1303
1304
1305
1306
1307

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

gilbertlee-amd's avatar
gilbertlee-amd committed
1310
  ExecuteTransfers(ev, 0, N, transfers, false);
Gilbert Lee's avatar
Gilbert Lee committed
1311
1312
1313
1314
1315

  // Collect aggregate bandwidth
  double totalBandwidth = 0;
  for (int i = 0; i <= isBidirectional; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1316
    double transferDurationMsec = transfers[i].transferTime / (1.0 * ev.numIterations);
gilbertlee-amd's avatar
gilbertlee-amd committed
1317
    double transferBandwidthGbs = (transfers[i].numBytesActual / 1.0E9) / transferDurationMsec * 1000.0f;
Gilbert Lee's avatar
Gilbert Lee committed
1318
    totalBandwidth += transferBandwidthGbs;
Gilbert Lee's avatar
Gilbert Lee committed
1319
1320
1321
1322
  }
  return totalBandwidth;
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1323
void Transfer::PrepareSubExecParams(EnvVars const& ev)
Gilbert Lee's avatar
Gilbert Lee committed
1324
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1325
1326
1327
1328
1329
1330
1331
  // 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
1332

gilbertlee-amd's avatar
gilbertlee-amd committed
1333
1334
1335
1336
1337
  // In some cases, there may not be enough data for all subExectors
  int const maxSubExecToUse = std::min((int)(N + targetMultiple - 1) / targetMultiple, this->numSubExecs);

  this->subExecParam.clear();
  this->subExecParam.resize(this->numSubExecs);
Gilbert Lee's avatar
Gilbert Lee committed
1338
1339

  size_t assigned = 0;
gilbertlee-amd's avatar
gilbertlee-amd committed
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
  for (int i = 0; i < this->numSubExecs; ++i)
  {
    int    const subExecLeft = std::max(0, maxSubExecToUse - i);
    size_t const leftover    = N - assigned;
    size_t const roundedN    = (leftover + targetMultiple - 1) / targetMultiple;

    SubExecParam& p = this->subExecParam[i];
    p.N             = subExecLeft ? std::min(leftover, ((roundedN / subExecLeft) * targetMultiple)) : 0;
    p.numSrcs       = this->numSrcs;
    p.numDsts       = this->numDsts;
    for (int iSrc = 0; iSrc < this->numSrcs; ++iSrc)
      p.src[iSrc] = this->srcMem[iSrc] + assigned + initOffset;
    for (int iDst = 0; iDst < this->numDsts; ++iDst)
      p.dst[iDst] = this->dstMem[iDst] + assigned + initOffset;

    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
1360

gilbertlee-amd's avatar
gilbertlee-amd committed
1361
1362
1363
    p.startCycle = 0;
    p.stopCycle  = 0;
    assigned += p.N;
Gilbert Lee's avatar
Gilbert Lee committed
1364
1365
  }

Gilbert Lee's avatar
Gilbert Lee committed
1366
  this->transferTime = 0.0;
Gilbert Lee's avatar
Gilbert Lee committed
1367
1368
}

gilbertlee-amd's avatar
gilbertlee-amd committed
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
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)
        buffer[i] = (i % 383 + 31) * (bufferIdx + 1);
    }
  }
  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];
          }
        }
      }
    }
  }
}

void Transfer::PrepareSrc(EnvVars const& ev)
{
  if (this->numSrcs == 0) return;
  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)
  {
    //PrepareReference(ev, reference, srcIdx);
    PrepareReference(ev, reference, srcIdx);
    HIP_CALL(hipMemcpy(this->srcMem[srcIdx] + initOffset, reference.data(), this->numBytesActual, hipMemcpyDefault));
  }
}

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;
    if (IsCpuType(this->dstType[dstIdx]))
    {
      output = this->dstMem[dstIdx] + initOffset;
    }
    else
    {
      HIP_CALL(hipMemcpy(hostBuffer.data(), this->dstMem[dstIdx] + initOffset, this->numBytesActual, hipMemcpyDefault));
      output = hostBuffer.data();
    }

    for (size_t i = 0; i < N; ++i)
    {
      if (reference[i] != output[i])
      {
1455
	printf("\n[ERROR] Destination array %d value at index %lu (%.3f) [%X] does not match expected value (%.3f) [%X]\n", dstIdx, i, output[i], *(unsigned int*)&output[i], reference[i], *(unsigned int*)&reference[i]);
gilbertlee-amd's avatar
gilbertlee-amd committed
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
        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());
        exit(1);
      }
    }
  }
}

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

Gilbert Lee's avatar
Gilbert Lee committed
1486
1487
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
// NOTE: This is a stop-gap solution until HIP provides wallclock values
int GetWallClockRate(int deviceId)
{
  static std::vector<int> wallClockPerDeviceMhz;

  if (wallClockPerDeviceMhz.size() == 0)
  {
    int numGpuDevices;
    HIP_CALL(hipGetDeviceCount(&numGpuDevices));
    wallClockPerDeviceMhz.resize(numGpuDevices);

    hipDeviceProp_t prop;
    for (int i = 0; i < numGpuDevices; i++)
    {
      HIP_CALL(hipGetDeviceProperties(&prop, i));
      int value = 25000;
      switch (prop.gcnArch)
      {
      case 906: case 910: value = 25000; break;
      default:
        printf("Unrecognized GCN arch %d\n", prop.gcnArch);
      }
      wallClockPerDeviceMhz[i] = value;
    }
  }
  return wallClockPerDeviceMhz[deviceId];
}
Gilbert Lee's avatar
Gilbert Lee committed
1513

gilbertlee-amd's avatar
gilbertlee-amd committed
1514
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
1515
1516
1517
1518
{
  ev.DisplaySweepEnvVars();

  // Compute how many possible Transfers are permitted (unique SRC/EXE/DST triplets)
gilbertlee-amd's avatar
gilbertlee-amd committed
1519
  std::vector<std::pair<ExeType, int>> exeList;
Gilbert Lee's avatar
Gilbert Lee committed
1520
1521
  for (auto exe : ev.sweepExe)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1522
1523
    ExeType const exeType = CharToExeType(exe);
    if (IsGpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
1524
    {
1525
      for (int exeIndex = 0; exeIndex < ev.numGpuDevices; ++exeIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
1526
        exeList.push_back(std::make_pair(exeType, exeIndex));
Gilbert Lee's avatar
Gilbert Lee committed
1527
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
1528
    else if (IsCpuType(exeType))
Gilbert Lee's avatar
Gilbert Lee committed
1529
    {
1530
1531
1532
1533
      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
1534
        exeList.push_back(std::make_pair(exeType, exeIndex));
1535
      }
Gilbert Lee's avatar
Gilbert Lee committed
1536
1537
    }
  }
1538
  int numExes = exeList.size();
Gilbert Lee's avatar
Gilbert Lee committed
1539
1540
1541
1542

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

Gilbert Lee's avatar
Gilbert Lee committed
1546
    for (int srcIndex = 0; srcIndex < numDevices; ++srcIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
1547
      srcList.push_back(std::make_pair(srcType, srcIndex));
Gilbert Lee's avatar
Gilbert Lee committed
1548
1549
1550
1551
1552
1553
1554
  }
  int numSrcs = srcList.size();


  std::vector<std::pair<MemType, int>> dstList;
  for (auto dst : ev.sweepDst)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1555
1556
    MemType const dstType = CharToMemType(dst);
    int const numDevices = IsGpuType(dstType) ? ev.numGpuDevices : ev.numCpuDevices;
Gilbert Lee's avatar
Gilbert Lee committed
1557
1558

    for (int dstIndex = 0; dstIndex < numDevices; ++dstIndex)
gilbertlee-amd's avatar
gilbertlee-amd committed
1559
      dstList.push_back(std::make_pair(dstType, dstIndex));
Gilbert Lee's avatar
Gilbert Lee committed
1560
1561
1562
  }
  int numDsts = dstList.size();

1563
1564
  // Build array of possibilities, respecting any additional restrictions (e.g. XGMI hop count)
  struct TransferInfo
Gilbert Lee's avatar
Gilbert Lee committed
1565
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1566
1567
1568
    MemType srcType; int srcIndex;
    ExeType exeType; int exeIndex;
    MemType dstType; int dstIndex;
1569
1570
1571
1572
1573
1574
1575
1576
  };

  // 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
1577
  {
1578
1579
    // Skip CPU executors if XGMI link must be used
    if (useXgmiOnly && !IsGpuType(exeList[i].first)) continue;
gilbertlee-amd's avatar
gilbertlee-amd committed
1580
1581
    tinfo.exeType  = exeList[i].first;
    tinfo.exeIndex = exeList[i].second;
1582

gilbertlee-amd's avatar
gilbertlee-amd committed
1583
    bool isXgmiSrc  = false;
1584
1585
1586
1587
1588
1589
1590
    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)
        {
1591
1592
1593
#if defined(__NVCC__)
          isXgmiSrc = false;
#else
1594
          uint32_t exeToSrcLinkType, exeToSrcHopCount;
gilbertlee-amd's avatar
gilbertlee-amd committed
1595
1596
          HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(exeList[i].second, false),
                                                RemappedIndex(srcList[j].second, false),
1597
1598
1599
1600
                                                &exeToSrcLinkType,
                                                &exeToSrcHopCount));
          isXgmiSrc = (exeToSrcLinkType == HSA_AMD_LINK_INFO_TYPE_XGMI);
          if (isXgmiSrc) numHopsSrc = exeToSrcHopCount;
1601
#endif
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
        }
        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;
      }
      else if (useXgmiOnly) continue;

gilbertlee-amd's avatar
gilbertlee-amd committed
1617
1618
      tinfo.srcType  = srcList[j].first;
      tinfo.srcIndex = srcList[j].second;
1619
1620
1621
1622
1623
1624
1625
1626
1627

      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)
          {
1628
1629
1630
#if defined(__NVCC__)
            isXgmiSrc = false;
#else
1631
            uint32_t exeToDstLinkType, exeToDstHopCount;
gilbertlee-amd's avatar
gilbertlee-amd committed
1632
1633
            HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(exeList[i].second, false),
                                                  RemappedIndex(dstList[k].second, false),
1634
1635
1636
1637
                                                  &exeToDstLinkType,
                                                  &exeToDstHopCount));
            isXgmiDst = (exeToDstLinkType == HSA_AMD_LINK_INFO_TYPE_XGMI);
            if (isXgmiDst) numHopsDst = exeToDstHopCount;
1638
#endif
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
          }
          else
          {
            isXgmiDst = true;
            numHopsDst = 0;
          }
        }

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

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

1656
1657
1658
1659
1660
1661
#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
1662
1663
        tinfo.dstType  = dstList[k].first;
        tinfo.dstIndex = dstList[k].second;
1664
1665
1666
1667

        possibleTransfers.push_back(tinfo);
      }
    }
Gilbert Lee's avatar
Gilbert Lee committed
1668
1669
  }

1670
1671
1672
  int const numPossible = (int)possibleTransfers.size();
  int maxParallelTransfers = (ev.sweepMax == 0 ? numPossible : ev.sweepMax);

Gilbert Lee's avatar
Gilbert Lee committed
1673
1674
1675
1676
1677
1678
  if (ev.sweepMin > numPossible)
  {
    printf("No valid test configurations exist\n");
    return;
  }

1679
1680
1681
1682
1683
1684
  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
1685
1686
  int numTestsRun = 0;
  int M = ev.sweepMin;
gilbertlee-amd's avatar
gilbertlee-amd committed
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
  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
1698
1699
1700
1701
1702
1703
1704
1705
1706
  // 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
1707
      M = distribution(*ev.generator);
Gilbert Lee's avatar
Gilbert Lee committed
1708
1709
1710
1711

      // Generate a random bitmask
      for (int i = 0; i < numPossible; i++)
        bitmask[i] = (i < M) ? 1 : 0;
1712
      std::shuffle(bitmask.begin(), bitmask.end(), *ev.generator);
Gilbert Lee's avatar
Gilbert Lee committed
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
    }

    // 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;
gilbertlee-amd's avatar
gilbertlee-amd committed
1723
1724
1725
1726
1727
        transfer.numSrcs        = 1;
        transfer.numDsts        = 1;
        transfer.srcType        = {possibleTransfers[value].srcType};
        transfer.srcIndex       = {possibleTransfers[value].srcIndex};
        transfer.exeType        = possibleTransfers[value].exeType;
1728
        transfer.exeIndex       = possibleTransfers[value].exeIndex;
gilbertlee-amd's avatar
gilbertlee-amd committed
1729
1730
1731
        transfer.dstType        = {possibleTransfers[value].dstType};
        transfer.dstIndex       = {possibleTransfers[value].dstIndex};
        transfer.numSubExecs    = IsGpuType(transfer.exeType) ? numGpuSubExecs : numCpuSubExecs;
1732
        transfer.transferIndex  = transfers.size();
gilbertlee-amd's avatar
gilbertlee-amd committed
1733
        transfer.numBytes       = ev.sweepRandBytes ? randSize(*ev.generator) * sizeof(float) : 0;
Gilbert Lee's avatar
Gilbert Lee committed
1734
1735
1736
1737
        transfers.push_back(transfer);
      }
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
1738
1739
    LogTransfers(fp, ++numTestsRun, transfers);
    ExecuteTransfers(ev, numTestsRun, numBytesPerTransfer / sizeof(float), transfers);
Gilbert Lee's avatar
Gilbert Lee committed
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770

    // 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
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
  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
1781
1782
1783
1784
            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
1785
1786
1787
1788
            transfer.numBytes);
  }
  fprintf(fp, "\n");
  fflush(fp);
Gilbert Lee's avatar
Gilbert Lee committed
1789
}
gilbertlee-amd's avatar
gilbertlee-amd committed
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800

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