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

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

// 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
36
#include <stack>
#include <thread>

#include "TransferBench.hpp"
#include "GetClosestNumaNode.hpp"
#include "Kernels.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
  // Determine number of bytes to run per Transfer
Gilbert Lee's avatar
Gilbert Lee committed
57
58
59
  // If a non-zero number of bytes is specified, use it
  // Otherwise generate array of bytes values to execute over
  std::vector<size_t> valuesOfN;
Gilbert Lee's avatar
Gilbert Lee committed
60
  size_t numBytesPerTransfer = argc > 2 ? atoll(argv[2]) : DEFAULT_BYTES_PER_TRANSFER;
Gilbert Lee's avatar
Gilbert Lee committed
61
62
63
64
65
66
  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
67
68
69
    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
70
71
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
72
  PopulateTestSizes(numBytesPerTransfer, ev.samplingFactor, valuesOfN);
Gilbert Lee's avatar
Gilbert Lee committed
73

Gilbert Lee's avatar
Gilbert Lee committed
74
75
76
77
78
79
80
81
82
83
  // Check for preset tests
  // - Tests that sweep across possible sets of Transfers
  if (!strcmp(argv[1], "sweep") || !strcmp(argv[1], "rsweep"))
  {
    RunSweepPreset(ev, numBytesPerTransfer, !strcmp(argv[1], "rsweep"));
    exit(0);
  }
  // - Tests that benchmark peer-to-peer performance
  else if (!strcmp(argv[1], "p2p") || !strcmp(argv[1], "p2p_rr") ||
           !strcmp(argv[1], "g2g") || !strcmp(argv[1], "g2g_rr"))
Gilbert Lee's avatar
Gilbert Lee committed
84
85
86
87
88
89
90
91
92
93
94
95
96
  {
    int numBlocksToUse = 0;
    if (argc > 3)
      numBlocksToUse = atoi(argv[3]);
    else
      HIP_CALL(hipDeviceGetAttribute(&numBlocksToUse, hipDeviceAttributeMultiprocessorCount, 0));

    // Perform either local read (+remote write) [EXE = SRC] or
    // remote read (+local write)                [EXE = DST]
    int readMode = (!strcmp(argv[1], "p2p_rr") || !strcmp(argv[1], "g2g_rr") ? 1 : 0);
    int skipCpu  = (!strcmp(argv[1], "g2g"   ) || !strcmp(argv[1], "g2g_rr") ? 1 : 0);

    // Execute peer to peer benchmark mode
Gilbert Lee's avatar
Gilbert Lee committed
97
    RunPeerToPeerBenchmarks(ev, numBytesPerTransfer / sizeof(float), numBlocksToUse, readMode, skipCpu);
Gilbert Lee's avatar
Gilbert Lee committed
98
99
100
    exit(0);
  }

Gilbert Lee's avatar
Gilbert Lee committed
101
  // Check that Transfer configuration file can be opened
Gilbert Lee's avatar
Gilbert Lee committed
102
103
104
  FILE* fp = fopen(argv[1], "r");
  if (!fp)
  {
Gilbert Lee's avatar
Gilbert Lee committed
105
    printf("[ERROR] Unable to open transfer configuration file: [%s]\n", argv[1]);
Gilbert Lee's avatar
Gilbert Lee committed
106
107
108
    exit(1);
  }

Gilbert Lee's avatar
Gilbert Lee committed
109
  // Print environment variables and CSV header
Gilbert Lee's avatar
Gilbert Lee committed
110
111
112
113
  ev.DisplayEnvVars();
  if (ev.outputToCsv)
  {
    printf("Test,NumBytes,SrcMem,Executor,DstMem,CUs,BW(GB/s),Time(ms),"
Gilbert Lee's avatar
Gilbert Lee committed
114
           "TransferDesc,SrcAddr,DstAddr,ByteOffset,numWarmups,numIters\n");
Gilbert Lee's avatar
Gilbert Lee committed
115
116
117
118
119
120
121
122
123
  }

  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
124
125
126
127
    // 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
128

Gilbert Lee's avatar
Gilbert Lee committed
129
130
131
    ExecuteTransfers(ev, ++testNum, valuesOfN, transfers);
  }
  fclose(fp);
Gilbert Lee's avatar
Gilbert Lee committed
132

Gilbert Lee's avatar
Gilbert Lee committed
133
134
  return 0;
}
Gilbert Lee's avatar
Gilbert Lee committed
135

Gilbert Lee's avatar
Gilbert Lee committed
136
137
138
139
140
141
void ExecuteTransfers(EnvVars const& ev,
                      int testNum,
                      std::vector<size_t> const& valuesOfN,
                      std::vector<Transfer>& transfers)
{
  int const initOffset = ev.byteOffset / sizeof(float);
Gilbert Lee's avatar
Gilbert Lee committed
142

Gilbert Lee's avatar
Gilbert Lee committed
143
144
145
146
  // Find the largest N to be used - memory will only be allocated once per set of Transfers
  size_t maxN = valuesOfN[0];
  for (auto N : valuesOfN)
    maxN = std::max(maxN, N);
Gilbert Lee's avatar
Gilbert Lee committed
147

Gilbert Lee's avatar
Gilbert Lee committed
148
149
150
151
152
153
154
155
  // Map transfers by executor
  TransferMap transferMap;
  for (Transfer const& transfer : transfers)
  {
    Executor executor(transfer.exeMemType, transfer.exeIndex);
    ExecutorInfo& executorInfo = transferMap[executor];
    executorInfo.transfers.push_back(transfer);
  }
Gilbert Lee's avatar
Gilbert Lee committed
156

Gilbert Lee's avatar
Gilbert Lee committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
  // Loop over each executor and prepare GPU resources
  std::vector<Transfer*> transferList;
  for (auto& exeInfoPair : transferMap)
  {
    Executor const& executor = exeInfoPair.first;
    ExecutorInfo& exeInfo = exeInfoPair.second;
    exeInfo.totalTime = 0.0;
    exeInfo.totalBlocks = 0;

    // Loop over each transfer this executor is involved in
    for (Transfer& transfer : exeInfo.transfers)
    {
      // Get some aliases to transfer variables
      MemType const& exeMemType  = transfer.exeMemType;
      MemType const& srcMemType  = transfer.srcMemType;
      MemType const& dstMemType  = transfer.dstMemType;
      int     const& blocksToUse = transfer.numBlocksToUse;

      // Get potentially remapped device indices
      int const srcIndex = RemappedIndex(transfer.srcIndex, srcMemType);
      int const exeIndex = RemappedIndex(transfer.exeIndex, exeMemType);
      int const dstIndex = RemappedIndex(transfer.dstIndex, dstMemType);

      // Enable peer-to-peer access if necessary (can only be called once per unique pair)
Gilbert Lee's avatar
Gilbert Lee committed
181
182
      if (exeMemType == MEM_GPU)
      {
Gilbert Lee's avatar
Gilbert Lee committed
183
184
185
        // Ensure executing GPU can access source memory
        if ((srcMemType == MEM_GPU || srcMemType == MEM_GPU_FINE) && srcIndex != exeIndex)
          EnablePeerAccess(exeIndex, srcIndex);
Gilbert Lee's avatar
Gilbert Lee committed
186

Gilbert Lee's avatar
Gilbert Lee committed
187
188
189
        // Ensure executing GPU can access destination memory
        if ((dstMemType == MEM_GPU || dstMemType == MEM_GPU_FINE) && dstIndex != exeIndex)
          EnablePeerAccess(exeIndex, dstIndex);
Gilbert Lee's avatar
Gilbert Lee committed
190
      }
Gilbert Lee's avatar
Gilbert Lee committed
191
192
193
194
195
196
197
198

      // Allocate (maximum) source / destination memory based on type / device index
      AllocateMemory(srcMemType, srcIndex, maxN * sizeof(float) + ev.byteOffset, (void**)&transfer.srcMem);
      AllocateMemory(dstMemType, dstIndex, maxN * sizeof(float) + ev.byteOffset, (void**)&transfer.dstMem);

      transfer.blockParam.resize(exeMemType == MEM_CPU ? ev.numCpuPerTransfer : blocksToUse);
      exeInfo.totalBlocks += transfer.blockParam.size();
      transferList.push_back(&transfer);
Gilbert Lee's avatar
Gilbert Lee committed
199
200
    }

Gilbert Lee's avatar
Gilbert Lee committed
201
202
203
204
    // Prepare per-threadblock parameters for GPU executors
    MemType const exeMemType = executor.first;
    int     const exeIndex   = RemappedIndex(executor.second, exeMemType);
    if (exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
205
    {
Gilbert Lee's avatar
Gilbert Lee committed
206
207
208
209
210
211
212
213
214
215
      // 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(exeMemType, exeIndex, exeInfo.totalBlocks * sizeof(BlockParam),
                     (void**)&exeInfo.blockParamGpu);

      int const numTransfersToRun = ev.useSingleStream ? 1 : exeInfo.transfers.size();
      exeInfo.streams.resize(numTransfersToRun);
      exeInfo.startEvents.resize(numTransfersToRun);
      exeInfo.stopEvents.resize(numTransfersToRun);
      for (int i = 0; i < numTransfersToRun; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
216
      {
Gilbert Lee's avatar
Gilbert Lee committed
217
218
219
220
221
        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
222

Gilbert Lee's avatar
Gilbert Lee committed
223
224
225
226
227
228
229
230
231
      // Assign each transfer its portion of threadblock parameters
      int transferOffset = 0;
      for (int i = 0; i < exeInfo.transfers.size(); i++)
      {
        exeInfo.transfers[i].blockParamGpuPtr = exeInfo.blockParamGpu + transferOffset;
        transferOffset += exeInfo.transfers[i].blockParam.size();
      }
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
232

Gilbert Lee's avatar
Gilbert Lee committed
233
234
235
236
  // Loop over all the different number of bytes to use per Transfer
  for (auto N : valuesOfN)
  {
    if (!ev.outputToCsv) printf("Test %d: [%lu bytes]\n", testNum, N * sizeof(float));
Gilbert Lee's avatar
Gilbert Lee committed
237

Gilbert Lee's avatar
Gilbert Lee committed
238
239
240
241
    // Prepare input memory and block parameters for current N
    for (auto& exeInfoPair : transferMap)
    {
      ExecutorInfo& exeInfo = exeInfoPair.second;
Gilbert Lee's avatar
Gilbert Lee committed
242

Gilbert Lee's avatar
Gilbert Lee committed
243
244
      int transferOffset = 0;
      for (int i = 0; i < exeInfo.transfers.size(); ++i)
Gilbert Lee's avatar
Gilbert Lee committed
245
      {
Gilbert Lee's avatar
Gilbert Lee committed
246
247
248
        // Prepare subarrays each threadblock works on and fill src memory with patterned data
        Transfer& transfer = exeInfo.transfers[i];
        transfer.PrepareBlockParams(ev, N);
Gilbert Lee's avatar
Gilbert Lee committed
249

Gilbert Lee's avatar
Gilbert Lee committed
250
251
        // Copy block parameters to GPU for GPU executors
        if (transfer.exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
252
        {
Gilbert Lee's avatar
Gilbert Lee committed
253
254
255
256
257
          HIP_CALL(hipMemcpy(&exeInfo.blockParamGpu[transferOffset],
                             transfer.blockParam.data(),
                             transfer.blockParam.size() * sizeof(BlockParam),
                             hipMemcpyHostToDevice));
          transferOffset += transfer.blockParam.size();
Gilbert Lee's avatar
Gilbert Lee committed
258
        }
Gilbert Lee's avatar
Gilbert Lee committed
259
260
      }
    }
Gilbert Lee's avatar
Gilbert Lee committed
261

Gilbert Lee's avatar
Gilbert Lee committed
262
263
264
265
266
267
268
269
    // 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++)
    {
      if (ev.numIterations > 0 && iteration >= ev.numIterations) break;
      if (ev.numIterations < 0 && totalCpuTime > -ev.numIterations) break;
Gilbert Lee's avatar
Gilbert Lee committed
270

Gilbert Lee's avatar
Gilbert Lee committed
271
272
273
274
275
276
277
      // Pause before starting first timed iteration in interactive mode
      if (ev.useInteractive && iteration == 0)
      {
        printf("Hit <Enter> to continue: ");
        scanf("%*c");
        printf("\n");
      }
Gilbert Lee's avatar
Gilbert Lee committed
278

Gilbert Lee's avatar
Gilbert Lee committed
279
280
      // Start CPU timing for this iteration
      auto cpuStart = std::chrono::high_resolution_clock::now();
Gilbert Lee's avatar
Gilbert Lee committed
281

Gilbert Lee's avatar
Gilbert Lee committed
282
283
284
285
286
287
288
289
290
      // Execute all Transfers in parallel
      for (auto& exeInfoPair : transferMap)
      {
        ExecutorInfo& exeInfo = exeInfoPair.second;
        int const numTransfersToRun = (IsGpuType(exeInfoPair.first.first) && ev.useSingleStream) ?
          1 : exeInfo.transfers.size();
        for (int i = 0; i < numTransfersToRun; ++i)
          threads.push(std::thread(RunTransfer, std::ref(ev), N, iteration, std::ref(exeInfo), i));
      }
Gilbert Lee's avatar
Gilbert Lee committed
291

Gilbert Lee's avatar
Gilbert Lee committed
292
293
294
295
296
297
      // 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
298
299
      }

Gilbert Lee's avatar
Gilbert Lee committed
300
301
302
303
304
      // 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
305
      {
Gilbert Lee's avatar
Gilbert Lee committed
306
307
        ++numTimedIterations;
        totalCpuTime += deltaSec;
Gilbert Lee's avatar
Gilbert Lee committed
308
      }
Gilbert Lee's avatar
Gilbert Lee committed
309
310
311
312
313
314
315
316
317
    }

    // Pause for interactive mode
    if (ev.useInteractive)
    {
      printf("Transfers complete. Hit <Enter> to continue: ");
      scanf("%*c");
      printf("\n");
    }
Gilbert Lee's avatar
Gilbert Lee committed
318

Gilbert Lee's avatar
Gilbert Lee committed
319
320
321
322
    // Validate that each transfer has transferred correctly
    int const numTransfers = transferList.size();
    for (auto transfer : transferList)
      CheckOrFill(MODE_CHECK, N, ev.useMemset, ev.useHipCall, ev.fillPattern, transfer->dstMem + initOffset);
Gilbert Lee's avatar
Gilbert Lee committed
323

Gilbert Lee's avatar
Gilbert Lee committed
324
325
326
327
    // Report timings
    totalCpuTime = totalCpuTime / (1.0 * numTimedIterations) * 1000;
    double totalBandwidthGbs = (numTransfers * N * sizeof(float) / 1.0E6) / totalCpuTime;
    double maxGpuTime = 0;
Gilbert Lee's avatar
Gilbert Lee committed
328

Gilbert Lee's avatar
Gilbert Lee committed
329
330
331
    if (ev.useSingleStream)
    {
      for (auto& exeInfoPair : transferMap)
Gilbert Lee's avatar
Gilbert Lee committed
332
      {
Gilbert Lee's avatar
Gilbert Lee committed
333
334
335
336
337
338
        ExecutorInfo  exeInfo    = exeInfoPair.second;
        MemType const exeMemType = exeInfoPair.first.first;
        int     const exeIndex   = exeInfoPair.first.second;

        // Compute total time for CPU executors
        if (!IsGpuType(exeMemType))
Gilbert Lee's avatar
Gilbert Lee committed
339
        {
Gilbert Lee's avatar
Gilbert Lee committed
340
341
342
343
          exeInfo.totalTime = 0;
          for (auto const& transfer : exeInfo.transfers)
            exeInfo.totalTime = std::max(exeInfo.totalTime, transfer.transferTime);
        }
Gilbert Lee's avatar
Gilbert Lee committed
344

Gilbert Lee's avatar
Gilbert Lee committed
345
346
347
348
        double exeDurationMsec = exeInfo.totalTime / (1.0 * numTimedIterations);
        double exeBandwidthGbs = (exeInfo.transfers.size() * N * sizeof(float) / 1.0E9) /
          exeDurationMsec * 1000.0f;
        maxGpuTime = std::max(maxGpuTime, exeDurationMsec);
Gilbert Lee's avatar
Gilbert Lee committed
349

Gilbert Lee's avatar
Gilbert Lee committed
350
351
352
353
        if (!ev.outputToCsv)
        {
          printf(" Executor: %cPU %02d        (# Transfers %02lu)| %9.3f GB/s | %8.3f ms |\n",
                 MemTypeStr[exeMemType], exeIndex, exeInfo.transfers.size(), exeBandwidthGbs, exeDurationMsec);
Gilbert Lee's avatar
Gilbert Lee committed
354
        }
Gilbert Lee's avatar
Gilbert Lee committed
355
356

        for (auto const& transfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
357
        {
Gilbert Lee's avatar
Gilbert Lee committed
358
          double transferDurationMsec = transfer.transferTime / (1.0 * numTimedIterations);
Gilbert Lee's avatar
Gilbert Lee committed
359
          double transferBandwidthGbs = (N * sizeof(float) / 1.0E9) / transferDurationMsec * 1000.0f;
Gilbert Lee's avatar
Gilbert Lee committed
360

Gilbert Lee's avatar
Gilbert Lee committed
361
362
          if (!ev.outputToCsv)
          {
Gilbert Lee's avatar
Gilbert Lee committed
363
364
365
366
367
368
369
370
            printf("                            Transfer  %02d | %9.3f GB/s | %8.3f ms | %c%02d -> %c%02d:(%03d) -> %c%02d\n",
                   transfer.transferIndex,
                   transferBandwidthGbs,
                   transferDurationMsec,
                   MemTypeStr[transfer.srcMemType], transfer.srcIndex,
                   MemTypeStr[transfer.exeMemType], transfer.exeIndex,
                   transfer.exeMemType == MEM_CPU ? ev.numCpuPerTransfer : transfer.numBlocksToUse,
                   MemTypeStr[transfer.dstMemType], transfer.dstIndex);
Gilbert Lee's avatar
Gilbert Lee committed
371
372
373
          }
          else
          {
Gilbert Lee's avatar
Gilbert Lee committed
374
            printf("%d,%lu,%c%02d,%c%02d,%c%02d,%d,%.3f,%.3f,%s,%p,%p,%d,%d,%lu\n",
Gilbert Lee's avatar
Gilbert Lee committed
375
                   testNum, N * sizeof(float),
Gilbert Lee's avatar
Gilbert Lee committed
376
377
378
379
                   MemTypeStr[transfer.srcMemType], transfer.srcIndex,
                   MemTypeStr[transfer.exeMemType], transfer.exeIndex,
                   MemTypeStr[transfer.dstMemType], transfer.dstIndex,
                   transfer.exeMemType == MEM_CPU ? ev.numCpuPerTransfer : transfer.numBlocksToUse,
Gilbert Lee's avatar
Gilbert Lee committed
380
                   transferBandwidthGbs, transferDurationMsec,
Gilbert Lee's avatar
Gilbert Lee committed
381
382
                   GetTransferDesc(transfer).c_str(),
                   transfer.srcMem + initOffset, transfer.dstMem + initOffset,
Gilbert Lee's avatar
Gilbert Lee committed
383
                   ev.byteOffset,
Gilbert Lee's avatar
Gilbert Lee committed
384
                   ev.numWarmups, numTimedIterations);
Gilbert Lee's avatar
Gilbert Lee committed
385
386
387
          }
        }

Gilbert Lee's avatar
Gilbert Lee committed
388
389
390
391
392
393
394
395
396
        if (ev.outputToCsv)
        {
          printf("%d,%lu,ALL,%c%02d,ALL,ALL,%.3f,%.3f,ALL,ALL,ALL,%d,%d,%lu\n",
                 testNum, N * sizeof(float),
                 MemTypeStr[exeMemType], exeIndex,
                 exeBandwidthGbs, exeDurationMsec,
                 ev.byteOffset,
                 ev.numWarmups, numTimedIterations);
        }
Gilbert Lee's avatar
Gilbert Lee committed
397
      }
Gilbert Lee's avatar
Gilbert Lee committed
398
399
400
401
    }
    else
    {
      for (auto const& transfer : transferList)
Gilbert Lee's avatar
Gilbert Lee committed
402
      {
Gilbert Lee's avatar
Gilbert Lee committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
        double transferDurationMsec = transfer->transferTime / (1.0 * numTimedIterations);
        double transferBandwidthGbs = (N * sizeof(float) / 1.0E9) / transferDurationMsec * 1000.0f;
        maxGpuTime = std::max(maxGpuTime, transferDurationMsec);
        if (!ev.outputToCsv)
        {
          printf(" Transfer %02d: %c%02d -> [%cPU %02d:%03d] -> %c%02d | %9.3f GB/s | %8.3f ms | %-16s\n",
                 transfer->transferIndex,
                 MemTypeStr[transfer->srcMemType], transfer->srcIndex,
                 MemTypeStr[transfer->exeMemType], transfer->exeIndex,
                 transfer->exeMemType == MEM_CPU ? ev.numCpuPerTransfer : transfer->numBlocksToUse,
                 MemTypeStr[transfer->dstMemType], transfer->dstIndex,
                 transferBandwidthGbs, transferDurationMsec,
                 GetTransferDesc(*transfer).c_str());
        }
        else
        {
          printf("%d,%lu,%c%02d,%c%02d,%c%02d,%d,%.3f,%.3f,%s,%p,%p,%d,%d,%lu\n",
                 testNum, N * sizeof(float),
                 MemTypeStr[transfer->srcMemType], transfer->srcIndex,
                 MemTypeStr[transfer->exeMemType], transfer->exeIndex,
                 MemTypeStr[transfer->dstMemType], transfer->dstIndex,
                 transfer->exeMemType == MEM_CPU ? ev.numCpuPerTransfer : transfer->numBlocksToUse,
                 transferBandwidthGbs, transferDurationMsec,
                 GetTransferDesc(*transfer).c_str(),
                 transfer->srcMem + initOffset, transfer->dstMem + initOffset,
                 ev.byteOffset,
                 ev.numWarmups, numTimedIterations);
        }
Gilbert Lee's avatar
Gilbert Lee committed
431
432
433
      }
    }

Gilbert Lee's avatar
Gilbert Lee committed
434
435
    // Display aggregate statistics
    if (!ev.outputToCsv)
Gilbert Lee's avatar
Gilbert Lee committed
436
    {
Gilbert Lee's avatar
Gilbert Lee committed
437
438
439
440
441
442
443
444
445
446
      printf(" Aggregate Bandwidth (CPU timed)         | %9.3f GB/s | %8.3f ms | Overhead: %.3f ms\n",
             totalBandwidthGbs, totalCpuTime, totalCpuTime - maxGpuTime);
    }
    else
    {
      printf("%d,%lu,ALL,ALL,ALL,ALL,%.3f,%.3f,ALL,ALL,ALL,%d,%d,%lu\n",
             testNum, N * sizeof(float), totalBandwidthGbs, totalCpuTime, ev.byteOffset,
             ev.numWarmups, numTimedIterations);
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
447

Gilbert Lee's avatar
Gilbert Lee committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
  // Release GPU memory
  for (auto exeInfoPair : transferMap)
  {
    ExecutorInfo& exeInfo = exeInfoPair.second;
    for (auto& transfer : exeInfo.transfers)
    {
      // Get some aliases to Transfer variables
      MemType const& exeMemType = transfer.exeMemType;
      MemType const& srcMemType = transfer.srcMemType;
      MemType const& dstMemType = transfer.dstMemType;

      // Allocate (maximum) source / destination memory based on type / device index
      DeallocateMemory(srcMemType, transfer.srcMem);
      DeallocateMemory(dstMemType, transfer.dstMem);
      transfer.blockParam.clear();
    }

    MemType const exeMemType = exeInfoPair.first.first;
    int     const exeIndex   = RemappedIndex(exeInfoPair.first.second, exeMemType);
    if (exeMemType == MEM_GPU)
    {
      DeallocateMemory(exeMemType, exeInfo.blockParamGpu);
      int const numTransfersToRun = ev.useSingleStream ? 1 : exeInfo.transfers.size();
      for (int i = 0; i < numTransfersToRun; ++i)
Gilbert Lee's avatar
Gilbert Lee committed
472
      {
Gilbert Lee's avatar
Gilbert Lee committed
473
474
475
        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
476
477
478
479
480
481
482
      }
    }
  }
}

void DisplayUsage(char const* cmdName)
{
Gilbert Lee's avatar
Gilbert Lee committed
483
  printf("TransferBench v%s\n", TB_VERSION);
Gilbert Lee's avatar
Gilbert Lee committed
484
485
486
487
488
489
490
491
492
493
494
495
496
  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
497
  printf("          - Filename of configFile containing Transfers to execute (see example.cfg for format)\n");
Gilbert Lee's avatar
Gilbert Lee committed
498
  printf("          - Name of preset benchmark:\n");
Gilbert Lee's avatar
Gilbert Lee committed
499
500
501
502
  printf("              p2p{_rr} - All CPU/GPU pairs benchmark {with remote reads}\n");
  printf("              g2g{_rr} - All GPU/GPU pairs benchmark {with remote reads}\n");
  printf("              sweep    - Sweep across possible sets of Transfers\n");
  printf("              rsweep   - Randomly sweep across possible sets of Transfers\n");
Gilbert Lee's avatar
Gilbert Lee committed
503
  printf("            - 3rd optional argument will be used as # of CUs to use (uses all by default)\n");
Gilbert Lee's avatar
Gilbert Lee committed
504
  printf("  N     : (Optional) Number of bytes to copy per Transfer.\n");
Gilbert Lee's avatar
Gilbert Lee committed
505
  printf("          If not specified, defaults to %lu bytes. Must be a multiple of 4 bytes\n",
Gilbert Lee's avatar
Gilbert Lee committed
506
         DEFAULT_BYTES_PER_TRANSFER);
Gilbert Lee's avatar
Gilbert Lee committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
  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();
}

int RemappedIndex(int const origIdx, MemType const memType)
{
  static std::vector<int> remapping;

  // No need to re-map CPU devices
  if (memType == MEM_CPU) return origIdx;

  // Build remapping on first use
  if (remapping.empty())
  {
    int numGpuDevices;
    HIP_CALL(hipGetDeviceCount(&numGpuDevices));
    remapping.resize(numGpuDevices);

    int const usePcieIndexing = getenv("USE_PCIE_INDEX") ? atoi(getenv("USE_PCIE_INDEX")) : 0;
    if (!usePcieIndexing)
    {
      // For HIP-based indexing no remapping is necessary
      for (int i = 0; i < numGpuDevices; ++i)
        remapping[i] = i;
    }
    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)
        remapping[i] = mapping[i].second;
    }
  }
  return remapping[origIdx];
}

void DisplayTopology(bool const outputToCsv)
{
  int numGpuDevices;
  HIP_CALL(hipGetDeviceCount(&numGpuDevices));

  if (outputToCsv)
  {
    printf("NumCpus,%d\n", numa_num_configured_nodes());
    printf("NumGpus,%d\n", numGpuDevices);
    printf("GPU");
    for (int j = 0; j < numGpuDevices; j++)
      printf(",GPU %02d", j);
    printf(",PCIe Bus ID,ClosestNUMA\n");
  }
  else
  {
    printf("\nDetected topology: %d CPU NUMA node(s)   %d GPU device(s)\n", numa_num_configured_nodes(), numGpuDevices);
    printf("        |");
    for (int j = 0; j < numGpuDevices; j++)
      printf(" GPU %02d |", j);
    printf(" PCIe Bus ID  | Closest NUMA\n");
    for (int j = 0; j <= numGpuDevices; j++)
      printf("--------+");
    printf("--------------+-------------\n");
  }

  char pciBusId[20];

  for (int i = 0; i < numGpuDevices; i++)
  {
    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;
        HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(i, MEM_GPU),
                                              RemappedIndex(j, MEM_GPU),
                                              &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 ? "," : " |");
      }
    }
    HIP_CALL(hipDeviceGetPCIBusId(pciBusId, 20, RemappedIndex(i, MEM_GPU)));
    if (outputToCsv)
      printf("%s,%d\n", pciBusId, GetClosestNumaNode(RemappedIndex(i, MEM_GPU)));
    else
      printf(" %11s |  %d  \n", pciBusId, GetClosestNumaNode(RemappedIndex(i, MEM_GPU)));
  }
}

Gilbert Lee's avatar
Gilbert Lee committed
618
void PopulateTestSizes(size_t const numBytesPerTransfer,
Gilbert Lee's avatar
Gilbert Lee committed
619
620
621
622
623
624
                       int const samplingFactor,
                       std::vector<size_t>& valuesOfN)
{
  valuesOfN.clear();

  // If the number of bytes is specified, use it
Gilbert Lee's avatar
Gilbert Lee committed
625
  if (numBytesPerTransfer != 0)
Gilbert Lee's avatar
Gilbert Lee committed
626
  {
Gilbert Lee's avatar
Gilbert Lee committed
627
    if (numBytesPerTransfer % 4)
Gilbert Lee's avatar
Gilbert Lee committed
628
    {
Gilbert Lee's avatar
Gilbert Lee committed
629
      printf("[ERROR] numBytesPerTransfer (%lu) must be a multiple of 4\n", numBytesPerTransfer);
Gilbert Lee's avatar
Gilbert Lee committed
630
631
      exit(1);
    }
Gilbert Lee's avatar
Gilbert Lee committed
632
    size_t N = numBytesPerTransfer / sizeof(float);
Gilbert Lee's avatar
Gilbert Lee committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
    valuesOfN.push_back(N);
  }
  else
  {
    // Otherwise generate a range of values
    // (Powers of 2, with samplingFactor samples between successive powers of 2)
    for (int N = 256; N <= (1<<27); N *= 2)
    {
      int delta = std::max(32, N / samplingFactor);
      int curr = N;
      while (curr < N * 2)
      {
        valuesOfN.push_back(curr);
        curr += delta;
      }
    }
  }
}

void ParseMemType(std::string const& token, int const numCpus, int const numGpus, MemType* memType, int* memIndex)
{
  char typeChar;
  if (sscanf(token.c_str(), " %c %d", &typeChar, memIndex) != 2)
  {
    printf("[ERROR] Unable to parse memory type token %s - expecting either 'B,C,G or F' followed by an index\n",
           token.c_str());
    exit(1);
  }

  switch (typeChar)
  {
  case 'C': case 'c': case 'B': case 'b':
    *memType = (typeChar == 'C' || typeChar == 'c') ? MEM_CPU : MEM_CPU_FINE;
    if (*memIndex < 0 || *memIndex >= numCpus)
    {
      printf("[ERROR] CPU index must be between 0 and %d (instead of %d)\n", numCpus-1, *memIndex);
      exit(1);
    }
    break;
  case 'G': case 'g': case 'F': case 'f':
    *memType = (typeChar == 'G' || typeChar == 'g') ? MEM_GPU : MEM_GPU_FINE;
    if (*memIndex < 0 || *memIndex >= numGpus)
    {
      printf("[ERROR] GPU index must be between 0 and %d (instead of %d)\n", numGpus-1, *memIndex);
      exit(1);
    }
    break;
  default:
    printf("[ERROR] Unrecognized memory type %s.  Expecting either 'B', 'C' or 'G' or 'F'\n", token.c_str());
    exit(1);
  }
}

Gilbert Lee's avatar
Gilbert Lee committed
686
// Helper function to parse a list of Transfer definitions
Gilbert Lee's avatar
Gilbert Lee committed
687
void ParseTransfers(char* line, int numCpus, int numGpus, std::vector<Transfer>& transfers)
Gilbert Lee's avatar
Gilbert Lee committed
688
689
690
691
692
{
  // 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
693
  transfers.clear();
Gilbert Lee's avatar
Gilbert Lee committed
694

Gilbert Lee's avatar
Gilbert Lee committed
695
  int numTransfers = 0;
Gilbert Lee's avatar
Gilbert Lee committed
696
  std::istringstream iss(line);
Gilbert Lee's avatar
Gilbert Lee committed
697
  iss >> numTransfers;
Gilbert Lee's avatar
Gilbert Lee committed
698
699
700
701
702
  if (iss.fail()) return;

  std::string exeMem;
  std::string srcMem;
  std::string dstMem;
Gilbert Lee's avatar
Gilbert Lee committed
703
704
705
706
707
708
709
710

  // If numTransfers < 0, read quads (srcMem, exeMem, dstMem, #CUs)
  // otherwise read triples (srcMem, exeMem, dstMem)
  bool const perTransferCUs = (numTransfers < 0);
  numTransfers = abs(numTransfers);

  int numBlocksToUse;
  if (!perTransferCUs)
Gilbert Lee's avatar
Gilbert Lee committed
711
712
713
714
715
716
717
718
719
  {
    iss >> numBlocksToUse;
    if (numBlocksToUse <= 0 || iss.fail())
    {
      printf("Parsing error: Number of blocks to use (%d) must be greater than 0\n", numBlocksToUse);
      exit(1);
    }
  }

Gilbert Lee's avatar
Gilbert Lee committed
720
721
722
723
724
725
726
  for (int i = 0; i < numTransfers; i++)
  {
    Transfer transfer;
    transfer.transferIndex = i;
    iss >> srcMem >> exeMem >> dstMem;
    if (perTransferCUs) iss >> numBlocksToUse;
    if (iss.fail())
Gilbert Lee's avatar
Gilbert Lee committed
727
    {
Gilbert Lee's avatar
Gilbert Lee committed
728
      if (perTransferCUs)
Gilbert Lee's avatar
Gilbert Lee committed
729
        printf("Parsing error: Unable to read valid Transfer quadruple (possibly missing a SRC or EXE or DST or #CU)\n");
Gilbert Lee's avatar
Gilbert Lee committed
730
731
732
      else
        printf("Parsing error: Unable to read valid Transfer triplet (possibly missing a SRC or EXE or DST)\n");
      exit(1);
Gilbert Lee's avatar
Gilbert Lee committed
733
    }
Gilbert Lee's avatar
Gilbert Lee committed
734
735
736
737
738
739

    ParseMemType(srcMem, numCpus, numGpus, &transfer.srcMemType, &transfer.srcIndex);
    ParseMemType(exeMem, numCpus, numGpus, &transfer.exeMemType, &transfer.exeIndex);
    ParseMemType(dstMem, numCpus, numGpus, &transfer.dstMemType, &transfer.dstIndex);
    transfer.numBlocksToUse = numBlocksToUse;
    transfers.push_back(transfer);
Gilbert Lee's avatar
Gilbert Lee committed
740
741
742
743
744
745
746
747
748
749
750
751
752
  }
}

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
753
754
755
756
757
758
759
  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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
}

void AllocateMemory(MemType memType, int devIndex, size_t numBytes, void** memPtr)
{
  if (numBytes == 0)
  {
    printf("[ERROR] Unable to allocate 0 bytes\n");
    exit(1);
  }

  if (memType == MEM_CPU || memType == MEM_CPU_FINE)
  {
    // Set numa policy prior to call to hipHostMalloc
    // NOTE: It may be possible that the actual configured numa nodes do not start at 0
    //       so remapping may be necessary
    // Find the 'deviceId'-th available NUMA node
    int numaIdx = 0;
    for (int i = 0; i <= devIndex; i++)
      while (!numa_bitmask_isbitset(numa_get_mems_allowed(), numaIdx))
        ++numaIdx;

    unsigned long nodemask = (1ULL << numaIdx);
    long retCode = set_mempolicy(MPOL_BIND, &nodemask, sizeof(nodemask)*8);
    if (retCode)
    {
      printf("[ERROR] Unable to set NUMA memory policy to bind to NUMA node %d\n", numaIdx);
      exit(1);
    }

    // Allocate host-pinned memory (should respect NUMA mem policy)
Gilbert Lee's avatar
Gilbert Lee committed
790

Gilbert Lee's avatar
Gilbert Lee committed
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
    if (memType == MEM_CPU_FINE)
    {
      HIP_CALL(hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser));
    }
    else
    {
      HIP_CALL(hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser | hipHostMallocNonCoherent));
    }

    // Check that the allocated pages are actually on the correct NUMA node
    CheckPages((char*)*memPtr, numBytes, numaIdx);

    // Reset to default numa mem policy
    retCode = set_mempolicy(MPOL_DEFAULT, NULL, 8);
    if (retCode)
    {
      printf("[ERROR] Unable reset to default NUMA memory policy\n");
      exit(1);
    }
  }
  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)
  {
    HIP_CALL(hipSetDevice(devIndex));
    HIP_CALL(hipExtMallocWithFlags((void**)memPtr, numBytes, hipDeviceMallocFinegrained));
  }
  else
  {
    printf("[ERROR] Unsupported memory type %d\n", memType);
    exit(1);
  }
}

void DeallocateMemory(MemType memType, void* memPtr)
{
  if (memType == MEM_CPU || memType == MEM_CPU_FINE)
  {
    HIP_CALL(hipHostFree(memPtr));
  }
  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);
  }
}

// Helper function to either fill a device pointer with pseudo-random data, or to check to see if it matches
void CheckOrFill(ModeType mode, int N, bool isMemset, bool isHipCall, std::vector<float>const& fillPattern, float* ptr)
{
  // Prepare reference resultx
  float* refBuffer = (float*)malloc(N * sizeof(float));
  if (isMemset)
  {
    if (isHipCall)
    {
      memset(refBuffer, 42, N * sizeof(float));
    }
    else
    {
      for (int i = 0; i < N; i++)
        refBuffer[i] = 1234.0f;
    }
  }
  else
  {
    // Fill with repeated pattern if specified
    size_t patternLen = fillPattern.size();
    if (patternLen > 0)
    {
      for (int i = 0; i < N; i++)
        refBuffer[i] = fillPattern[i % patternLen];
    }
    else // Otherwise fill with pseudo-random values
    {
      for (int i = 0; i < N; i++)
        refBuffer[i] = (i % 383 + 31);
    }
  }

  // Either fill the memory with the reference buffer, or compare against it
  if (mode == MODE_FILL)
  {
    HIP_CALL(hipMemcpy(ptr, refBuffer, N * sizeof(float), hipMemcpyDefault));
  }
  else if (mode == MODE_CHECK)
  {
    float* hostBuffer = (float*) malloc(N * sizeof(float));
    HIP_CALL(hipMemcpy(hostBuffer, ptr, N * sizeof(float), hipMemcpyDefault));
    for (int i = 0; i < N; i++)
    {
      if (refBuffer[i] != hostBuffer[i])
      {
        printf("[ERROR] Mismatch at element %d Ref: %f Actual: %f\n", i, refBuffer[i], hostBuffer[i]);
        exit(1);
      }
    }
    free(hostBuffer);
  }

  free(refBuffer);
}

std::string GetLinkTypeDesc(uint32_t linkType, uint32_t hopCount)
{
  char result[10];

  switch (linkType)
  {
  case HSA_AMD_LINK_INFO_TYPE_HYPERTRANSPORT: sprintf(result, "  HT-%d", hopCount); break;
  case HSA_AMD_LINK_INFO_TYPE_QPI           : sprintf(result, " QPI-%d", hopCount); break;
  case HSA_AMD_LINK_INFO_TYPE_PCIE          : sprintf(result, "PCIE-%d", hopCount); break;
  case HSA_AMD_LINK_INFO_TYPE_INFINBAND     : sprintf(result, "INFB-%d", hopCount); break;
  case HSA_AMD_LINK_INFO_TYPE_XGMI          : sprintf(result, "XGMI-%d", hopCount); break;
  default: sprintf(result, "??????");
  }
  return result;
}

std::string GetDesc(MemType srcMemType, int srcIndex,
                    MemType dstMemType, int dstIndex)
{
  if (srcMemType == MEM_CPU || srcMemType == MEM_CPU_FINE)
  {
    if (dstMemType == MEM_CPU || dstMemType == MEM_CPU_FINE)
      return (srcIndex == dstIndex) ? "LOCAL" : "NUMA";
    else if (dstMemType == MEM_GPU || dstMemType == MEM_GPU_FINE)
      return "PCIE";
    else
      goto error;
  }
  else if (srcMemType == MEM_GPU || srcMemType == MEM_GPU_FINE)
  {
    if (dstMemType == MEM_CPU || dstMemType == MEM_CPU_FINE)
      return "PCIE";
    else if (dstMemType == MEM_GPU || dstMemType == MEM_GPU_FINE)
    {
      if (srcIndex == dstIndex) return "LOCAL";
      else
      {
        uint32_t linkType, hopCount;
        HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(srcIndex, MEM_GPU),
                                              RemappedIndex(dstIndex, MEM_GPU),
                                              &linkType, &hopCount));
        return GetLinkTypeDesc(linkType, hopCount);
      }
    }
    else
      goto error;
  }
error:
  printf("[ERROR] Unrecognized memory type\n");
  exit(1);
}

Gilbert Lee's avatar
Gilbert Lee committed
988
std::string GetTransferDesc(Transfer const& transfer)
Gilbert Lee's avatar
Gilbert Lee committed
989
{
Gilbert Lee's avatar
Gilbert Lee committed
990
991
  return GetDesc(transfer.srcMemType, transfer.srcIndex, transfer.exeMemType, transfer.exeIndex) + "-"
    + GetDesc(transfer.exeMemType, transfer.exeIndex, transfer.dstMemType, transfer.dstIndex);
Gilbert Lee's avatar
Gilbert Lee committed
992
993
}

Gilbert Lee's avatar
Gilbert Lee committed
994
995
void RunTransfer(EnvVars const& ev, size_t const N, int const iteration,
                 ExecutorInfo& exeInfo, int const transferIdx)
Gilbert Lee's avatar
Gilbert Lee committed
996
{
Gilbert Lee's avatar
Gilbert Lee committed
997
  Transfer& transfer = exeInfo.transfers[transferIdx];
Gilbert Lee's avatar
Gilbert Lee committed
998
999

  // GPU execution agent
Gilbert Lee's avatar
Gilbert Lee committed
1000
  if (transfer.exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
1001
1002
  {
    // Switch to executing GPU
Gilbert Lee's avatar
Gilbert Lee committed
1003
    int const exeIndex = RemappedIndex(transfer.exeIndex, MEM_GPU);
Gilbert Lee's avatar
Gilbert Lee committed
1004
1005
    HIP_CALL(hipSetDevice(exeIndex));

Gilbert Lee's avatar
Gilbert Lee committed
1006
1007
1008
    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
1009
1010
1011
1012
1013
1014

    int const initOffset = ev.byteOffset / sizeof(float);

    if (ev.useHipCall)
    {
      // Record start event
Gilbert Lee's avatar
Gilbert Lee committed
1015
      HIP_CALL(hipEventRecord(startEvent, stream));
Gilbert Lee's avatar
Gilbert Lee committed
1016
1017
1018

      // Execute hipMemset / hipMemcpy
      if (ev.useMemset)
Gilbert Lee's avatar
Gilbert Lee committed
1019
        HIP_CALL(hipMemsetAsync(transfer.dstMem + initOffset, 42, N * sizeof(float), stream));
Gilbert Lee's avatar
Gilbert Lee committed
1020
      else
Gilbert Lee's avatar
Gilbert Lee committed
1021
1022
        HIP_CALL(hipMemcpyAsync(transfer.dstMem + initOffset,
                                transfer.srcMem + initOffset,
Gilbert Lee's avatar
Gilbert Lee committed
1023
1024
1025
                                N * sizeof(float), hipMemcpyDefault,
                                stream));
      // Record stop event
Gilbert Lee's avatar
Gilbert Lee committed
1026
      HIP_CALL(hipEventRecord(stopEvent, stream));
Gilbert Lee's avatar
Gilbert Lee committed
1027
1028
1029
    }
    else
    {
Gilbert Lee's avatar
Gilbert Lee committed
1030
      int const numBlocksToRun = ev.useSingleStream ? exeInfo.totalBlocks : transfer.numBlocksToUse;
Gilbert Lee's avatar
Gilbert Lee committed
1031
1032
1033
1034
      hipExtLaunchKernelGGL(ev.useMemset ? GpuMemsetKernel : GpuCopyKernel,
                            dim3(numBlocksToRun, 1, 1),
                            dim3(BLOCKSIZE, 1, 1),
                            ev.sharedMemBytes, stream,
Gilbert Lee's avatar
Gilbert Lee committed
1035
1036
                            startEvent, stopEvent,
                            0, transfer.blockParamGpuPtr);
Gilbert Lee's avatar
Gilbert Lee committed
1037
1038
1039
1040
    }

    // 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
1041
    HIP_CALL(hipStreamSynchronize(stream));
Gilbert Lee's avatar
Gilbert Lee committed
1042
1043
1044
1045

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

Gilbert Lee's avatar
Gilbert Lee committed
1049
1050
1051
      if (ev.useSingleStream)
      {
        for (Transfer& currTransfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
1052
        {
Gilbert Lee's avatar
Gilbert Lee committed
1053
1054
1055
          long long minStartCycle = currTransfer.blockParamGpuPtr[0].startCycle;
          long long maxStopCycle  = currTransfer.blockParamGpuPtr[0].stopCycle;
          for (int i = 1; i < currTransfer.numBlocksToUse; i++)
Gilbert Lee's avatar
Gilbert Lee committed
1056
          {
Gilbert Lee's avatar
Gilbert Lee committed
1057
1058
            minStartCycle = std::min(minStartCycle, currTransfer.blockParamGpuPtr[i].startCycle);
            maxStopCycle  = std::max(maxStopCycle,  currTransfer.blockParamGpuPtr[i].stopCycle);
Gilbert Lee's avatar
Gilbert Lee committed
1059
          }
Gilbert Lee's avatar
Gilbert Lee committed
1060
1061
1062
          int const wallClockRate = GetWallClockRate(exeIndex);
          double iterationTimeMs = (maxStopCycle - minStartCycle) / (double)(wallClockRate);
          currTransfer.transferTime += iterationTimeMs;
Gilbert Lee's avatar
Gilbert Lee committed
1063
        }
Gilbert Lee's avatar
Gilbert Lee committed
1064
1065
1066
1067
1068
        exeInfo.totalTime += gpuDeltaMsec;
      }
      else
      {
        transfer.transferTime += gpuDeltaMsec;
Gilbert Lee's avatar
Gilbert Lee committed
1069
1070
1071
      }
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
1072
  else if (transfer.exeMemType == MEM_CPU) // CPU execution agent
Gilbert Lee's avatar
Gilbert Lee committed
1073
1074
  {
    // Force this thread and all child threads onto correct NUMA node
Gilbert Lee's avatar
Gilbert Lee committed
1075
    if (numa_run_on_node(transfer.exeIndex))
Gilbert Lee's avatar
Gilbert Lee committed
1076
    {
Gilbert Lee's avatar
Gilbert Lee committed
1077
      printf("[ERROR] Unable to set CPU to NUMA node %d\n", transfer.exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1078
1079
1080
1081
1082
1083
1084
1085
      exit(1);
    }

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

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

    // Launch child-threads to perform memcopies
Gilbert Lee's avatar
Gilbert Lee committed
1086
1087
    for (int i = 0; i < ev.numCpuPerTransfer; i++)
      childThreads.push_back(std::thread(ev.useMemset ? CpuMemsetKernel : CpuCopyKernel, std::ref(transfer.blockParam[i])));
Gilbert Lee's avatar
Gilbert Lee committed
1088
1089

    // Wait for child-threads to finish
Gilbert Lee's avatar
Gilbert Lee committed
1090
    for (int i = 0; i < ev.numCpuPerTransfer; i++)
Gilbert Lee's avatar
Gilbert Lee committed
1091
1092
1093
1094
1095
1096
      childThreads[i].join();

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

    // Record time if not a warmup iteration
    if (iteration >= 0)
Gilbert Lee's avatar
Gilbert Lee committed
1097
      transfer.transferTime += (std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0);
Gilbert Lee's avatar
Gilbert Lee committed
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
  }
}

void RunPeerToPeerBenchmarks(EnvVars const& ev, size_t N, int numBlocksToUse, int readMode, int skipCpu)
{
  // Collect the number of available CPUs/GPUs on this machine
  int numGpus;
  HIP_CALL(hipGetDeviceCount(&numGpus));
  int const numCpus = numa_num_configured_nodes();
  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);

  if (!ev.outputToCsv)
  {
    printf("Performing copies in each direction of %lu bytes\n", N * sizeof(float));
Gilbert Lee's avatar
Gilbert Lee committed
1117
    printf("Using %d threads per NUMA node for CPU copies\n", ev.numCpuPerTransfer);
Gilbert Lee's avatar
Gilbert Lee committed
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    printf("Using %d CUs per transfer\n", numBlocksToUse);
  }
  else
  {
    printf("SRC,DST,Direction,ReadMode,BW(GB/s),Bytes\n");
  }

  // Perform unidirectional / bidirectional
  for (int isBidirectional = 0; isBidirectional <= 1; isBidirectional++)
  {
    // Print header
    if (!ev.outputToCsv)
    {
      printf("%sdirectional copy peak bandwidth GB/s [%s read / %s write]\n", isBidirectional ? "Bi" : "Uni",
             readMode == 0 ? "Local" : "Remote",
             readMode == 0 ? "Remote" : "Local");
      printf("%10s", "D/D");
      if (!skipCpu)
      {
        for (int i = 0; i < numCpus; i++)
          printf("%7s %02d", "CPU", i);
      }
      for (int i = 0; i < numGpus; i++)
        printf("%7s %02d", "GPU", i);
      printf("\n");
    }

    // Loop over all possible src/dst pairs
    for (int src = 0; src < numDevices; src++)
    {
      MemType const& srcMemType = (src < numCpus ? MEM_CPU : MEM_GPU);
      if (skipCpu && srcMemType == MEM_CPU) continue;
      int srcIndex = (srcMemType == MEM_CPU ? src : src - numCpus);
      if (!ev.outputToCsv)
        printf("%7s %02d", (srcMemType == MEM_CPU) ? "CPU" : "GPU", srcIndex);
      for (int dst = 0; dst < numDevices; dst++)
      {
        MemType const& dstMemType = (dst < numCpus ? MEM_CPU : MEM_GPU);
        if (skipCpu && dstMemType == MEM_CPU) continue;
        int dstIndex = (dstMemType == MEM_CPU ? dst : dst - numCpus);
        double bandwidth = GetPeakBandwidth(ev, N, isBidirectional, readMode, numBlocksToUse,
                                            srcMemType, srcIndex, dstMemType, dstIndex);
        if (!ev.outputToCsv)
        {
          if (bandwidth == 0)
            printf("%10s", "N/A");
          else
            printf("%10.2f", bandwidth);
        }
        else
        {
          printf("%s %02d,%s %02d,%s,%s,%.2f,%lu\n",
                 srcMemType == MEM_CPU ? "CPU" : "GPU",
                 srcIndex,
                 dstMemType == MEM_CPU ? "CPU" : "GPU",
                 dstIndex,
                 isBidirectional ? "bidirectional" : "unidirectional",
                 readMode == 0 ? "Local" : "Remote",
                 bandwidth,
                 N * sizeof(float));
        }
        fflush(stdout);
      }
      if (!ev.outputToCsv) printf("\n");
    }
    if (!ev.outputToCsv) printf("\n");
  }
}

double GetPeakBandwidth(EnvVars const& ev,
                        size_t  const  N,
                        int     const  isBidirectional,
                        int     const  readMode,
                        int     const  numBlocksToUse,
                        MemType const  srcMemType,
                        int     const  srcIndex,
                        MemType const  dstMemType,
                        int     const  dstIndex)
{
  // Skip bidirectional on same device
  if (isBidirectional && srcMemType == dstMemType && srcIndex == dstIndex) return 0.0f;

  int const initOffset = ev.byteOffset / sizeof(float);

Gilbert Lee's avatar
Gilbert Lee committed
1202
1203
  // Prepare Transfers
  std::vector<Transfer*> transfers;
Gilbert Lee's avatar
Gilbert Lee committed
1204
1205
1206
  ExecutorInfo exeInfo[2];
  for (int i = 0; i < 2; i++)
  {
Gilbert Lee's avatar
Gilbert Lee committed
1207
    exeInfo[i].transfers.resize(1);
Gilbert Lee's avatar
Gilbert Lee committed
1208
1209
1210
    exeInfo[i].streams.resize(1);
    exeInfo[i].startEvents.resize(1);
    exeInfo[i].stopEvents.resize(1);
Gilbert Lee's avatar
Gilbert Lee committed
1211
    transfers.push_back(&exeInfo[i].transfers[0]);
Gilbert Lee's avatar
Gilbert Lee committed
1212
1213
  }

Gilbert Lee's avatar
Gilbert Lee committed
1214
1215
1216
1217
  transfers[0]->srcMemType = transfers[1]->dstMemType = srcMemType;
  transfers[0]->dstMemType = transfers[1]->srcMemType = dstMemType;
  transfers[0]->srcIndex   = transfers[1]->dstIndex   = RemappedIndex(srcIndex, srcMemType);
  transfers[0]->dstIndex   = transfers[1]->srcIndex   = RemappedIndex(dstIndex, dstMemType);
Gilbert Lee's avatar
Gilbert Lee committed
1218
1219

  // Either perform (local read + remote write), or (remote read + local write)
Gilbert Lee's avatar
Gilbert Lee committed
1220
1221
1222
1223
  transfers[0]->exeMemType = (readMode == 0 ? srcMemType : dstMemType);
  transfers[1]->exeMemType = (readMode == 0 ? dstMemType : srcMemType);
  transfers[0]->exeIndex   = RemappedIndex((readMode == 0 ? srcIndex : dstIndex), transfers[0]->exeMemType);
  transfers[1]->exeIndex   = RemappedIndex((readMode == 0 ? dstIndex : srcIndex), transfers[1]->exeMemType);
Gilbert Lee's avatar
Gilbert Lee committed
1224
1225
1226

  for (int i = 0; i <= isBidirectional; i++)
  {
Gilbert Lee's avatar
Gilbert Lee committed
1227
1228
1229
1230
    AllocateMemory(transfers[i]->srcMemType, transfers[i]->srcIndex,
                   N * sizeof(float) + ev.byteOffset, (void**)&transfers[i]->srcMem);
    AllocateMemory(transfers[i]->dstMemType, transfers[i]->dstIndex,
                   N * sizeof(float) + ev.byteOffset, (void**)&transfers[i]->dstMem);
Gilbert Lee's avatar
Gilbert Lee committed
1231
1232

    // Prepare block parameters on CPU
Gilbert Lee's avatar
Gilbert Lee committed
1233
1234
1235
    transfers[i]->numBlocksToUse = (transfers[i]->exeMemType == MEM_GPU) ? numBlocksToUse : ev.numCpuPerTransfer;
    transfers[i]->blockParam.resize(transfers[i]->numBlocksToUse);
    transfers[i]->PrepareBlockParams(ev, N);
Gilbert Lee's avatar
Gilbert Lee committed
1236

Gilbert Lee's avatar
Gilbert Lee committed
1237
    if (transfers[i]->exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
1238
1239
    {
      // Copy block parameters onto GPU
Gilbert Lee's avatar
Gilbert Lee committed
1240
1241
1242
1243
      AllocateMemory(MEM_GPU, transfers[i]->exeIndex, numBlocksToUse * sizeof(BlockParam),
                     (void **)&transfers[i]->blockParamGpuPtr);
      HIP_CALL(hipMemcpy(transfers[i]->blockParamGpuPtr,
                         transfers[i]->blockParam.data(),
Gilbert Lee's avatar
Gilbert Lee committed
1244
1245
1246
1247
                         numBlocksToUse * sizeof(BlockParam),
                         hipMemcpyHostToDevice));

      // Prepare GPU resources
Gilbert Lee's avatar
Gilbert Lee committed
1248
      HIP_CALL(hipSetDevice(transfers[i]->exeIndex));
Gilbert Lee's avatar
Gilbert Lee committed
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
      HIP_CALL(hipStreamCreate(&exeInfo[i].streams[0]));
      HIP_CALL(hipEventCreate(&exeInfo[i].startEvents[0]));
      HIP_CALL(hipEventCreate(&exeInfo[i].stopEvents[0]));
    }
  }

  std::stack<std::thread> threads;

  // Perform iteration
  for (int iteration = -ev.numWarmups; iteration < ev.numIterations; iteration++)
  {
    // Perform timed iterations
    for (int i = 0; i <= isBidirectional; i++)
Gilbert Lee's avatar
Gilbert Lee committed
1262
      threads.push(std::thread(RunTransfer, std::ref(ev), N, iteration, std::ref(exeInfo[i]), 0));
Gilbert Lee's avatar
Gilbert Lee committed
1263
1264
1265
1266
1267
1268
1269
1270
1271

    // Wait for all threads to finish
    for (int i = 0; i <= isBidirectional; i++)
    {
      threads.top().join();
      threads.pop();
    }
  }

Gilbert Lee's avatar
Gilbert Lee committed
1272
  // Validate that each Transfer has transferred correctly
Gilbert Lee's avatar
Gilbert Lee committed
1273
  for (int i = 0; i <= isBidirectional; i++)
Gilbert Lee's avatar
Gilbert Lee committed
1274
    CheckOrFill(MODE_CHECK, N, ev.useMemset, ev.useHipCall, ev.fillPattern, transfers[i]->dstMem + initOffset);
Gilbert Lee's avatar
Gilbert Lee committed
1275
1276
1277
1278
1279

  // Collect aggregate bandwidth
  double totalBandwidth = 0;
  for (int i = 0; i <= isBidirectional; i++)
  {
Gilbert Lee's avatar
Gilbert Lee committed
1280
1281
1282
    double transferDurationMsec = transfers[i]->transferTime / (1.0 * ev.numIterations);
    double transferBandwidthGbs = (N * sizeof(float) / 1.0E9) / transferDurationMsec * 1000.0f;
    totalBandwidth += transferBandwidthGbs;
Gilbert Lee's avatar
Gilbert Lee committed
1283
1284
1285
1286
1287
  }

  // Release GPU memory
  for (int i = 0; i <= isBidirectional; i++)
  {
Gilbert Lee's avatar
Gilbert Lee committed
1288
1289
    DeallocateMemory(transfers[i]->srcMemType, transfers[i]->srcMem);
    DeallocateMemory(transfers[i]->dstMemType, transfers[i]->dstMem);
Gilbert Lee's avatar
Gilbert Lee committed
1290

Gilbert Lee's avatar
Gilbert Lee committed
1291
    if (transfers[i]->exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
1292
    {
Gilbert Lee's avatar
Gilbert Lee committed
1293
      DeallocateMemory(MEM_GPU, transfers[i]->blockParamGpuPtr);
Gilbert Lee's avatar
Gilbert Lee committed
1294
1295
1296
1297
1298
1299
1300
1301
      HIP_CALL(hipStreamDestroy(exeInfo[i].streams[0]));
      HIP_CALL(hipEventDestroy(exeInfo[i].startEvents[0]));
      HIP_CALL(hipEventDestroy(exeInfo[i].stopEvents[0]));
    }
  }
  return totalBandwidth;
}

Gilbert Lee's avatar
Gilbert Lee committed
1302
void Transfer::PrepareBlockParams(EnvVars const& ev, size_t const N)
Gilbert Lee's avatar
Gilbert Lee committed
1303
1304
1305
1306
1307
1308
1309
{
  int const initOffset = ev.byteOffset / sizeof(float);

  // Initialize source memory with patterned data
  CheckOrFill(MODE_FILL, N, ev.useMemset, ev.useHipCall, ev.fillPattern, this->srcMem + initOffset);

  // Each block needs to know src/dst pointers and how many elements to transfer
Gilbert Lee's avatar
Gilbert Lee committed
1310
  // Figure out the sub-array each block does for this Transfer
Gilbert Lee's avatar
Gilbert Lee committed
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
  // - Partition N as evenly as possible, but try to keep blocks as multiples of BLOCK_BYTES bytes,
  //   except the very last one, for alignment reasons
  int const targetMultiple = ev.blockBytes / sizeof(float);
  int const maxNumBlocksToUse = std::min((N + targetMultiple - 1) / targetMultiple, this->blockParam.size());
  size_t assigned = 0;
  for (int j = 0; j < this->blockParam.size(); j++)
  {
    int    const blocksLeft = std::max(0, maxNumBlocksToUse - j);
    size_t const leftover   = N - assigned;
    size_t const roundedN   = (leftover + targetMultiple - 1) / targetMultiple;

    BlockParam& param = this->blockParam[j];
    param.N          = blocksLeft ? std::min(leftover, ((roundedN / blocksLeft) * targetMultiple)) : 0;
    param.src        = this->srcMem + assigned + initOffset;
    param.dst        = this->dstMem + assigned + initOffset;
    param.startCycle = 0;
    param.stopCycle  = 0;
    assigned += param.N;
  }

Gilbert Lee's avatar
Gilbert Lee committed
1331
  this->transferTime = 0.0;
Gilbert Lee's avatar
Gilbert Lee committed
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
}

// 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
1361
1362
1363
1364
1365
1366
1367
1368
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
1455
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
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508

void RunSweepPreset(EnvVars const& ev, size_t const numBytesPerTransfer, bool const isRandom)
{
  ev.DisplaySweepEnvVars();
  std::vector<size_t> valuesOfN(1, numBytesPerTransfer / sizeof(float));

  // Compute how many possible Transfers are permitted (unique SRC/EXE/DST triplets)
  bool hasCpuExecutor = false;
  bool hasGpuExecutor = false;
  std::vector<std::pair<MemType, int>> exeList;
  for (auto exe : ev.sweepExe)
  {
    MemType const exeMemType = CharToMemType(exe);
    int numDevices;
    if (IsGpuType(exeMemType))
    {
      numDevices = ev.numGpuDevices;
      hasGpuExecutor = true;
    }
    else
    {
      numDevices = ev.numCpuDevices;
      hasCpuExecutor = true;
    }
    for (int exeIndex = 0; exeIndex < numDevices; ++exeIndex)
      exeList.push_back(std::make_pair(exeMemType, exeIndex));
  }
  int numExes = ev.sweepSrcIsExe ? 1 : exeList.size();

  std::vector<std::pair<MemType, int>> srcList;
  for (auto src : ev.sweepSrc)
  {
    MemType const srcMemType = CharToMemType(src);
    int const numDevices = IsGpuType(srcMemType) ? ev.numGpuDevices : ev.numCpuDevices;
    // Skip source memory type if executor is supposed to be source but not specified
    if ((IsGpuType(srcMemType) && !hasGpuExecutor) ||
        (!IsGpuType(srcMemType) && !hasCpuExecutor)) continue;
    for (int srcIndex = 0; srcIndex < numDevices; ++srcIndex)
      srcList.push_back(std::make_pair(srcMemType, srcIndex));
  }
  int numSrcs = srcList.size();


  std::vector<std::pair<MemType, int>> dstList;
  for (auto dst : ev.sweepDst)
  {
    MemType const dstMemType = CharToMemType(dst);
    int const numDevices = IsGpuType(dstMemType) ? ev.numGpuDevices : ev.numCpuDevices;

    for (int dstIndex = 0; dstIndex < numDevices; ++dstIndex)
      dstList.push_back(std::make_pair(dstMemType, dstIndex));
  }
  int numDsts = dstList.size();

  int const numPossible = numSrcs * numExes * numDsts;
  int maxParallelTransfers = (ev.sweepMax == 0 ? numPossible : ev.sweepMax);
  if (ev.sweepSrcIsExe)
  {
    printf("Num possible (SRC/DST) triplets: (%d/%d) = %d\n", numSrcs, numDsts, numPossible);
  }
  else
  {
    printf("Num possible (SRC/EXE/DST) triplets: (%d/%d/%d) = %d\n", numSrcs, numExes, numDsts, numPossible);
  }

  if (ev.sweepMin > numPossible)
  {
    printf("No valid test configurations exist\n");
    return;
  }

  int numTestsRun = 0;
  int M = ev.sweepMin;
  // Create bitmask of numPossible triplets, of which M will be chosen
  std::string bitmask(M, 1);  bitmask.resize(numPossible, 0);
  auto rng = std::default_random_engine {};
  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
      M = ((maxParallelTransfers > ev.sweepMin) ? (rand() % (maxParallelTransfers - ev.sweepMin)) : 0)
        + ev.sweepMin;

      // Generate a random bitmask
      for (int i = 0; i < numPossible; i++)
        bitmask[i] = (i < M) ? 1 : 0;
      std::shuffle(bitmask.begin(), bitmask.end(), rng);
    }

    // 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;
        int srcValue = value / numDsts / numExes;
        int exeValue = value / numDsts % numExes;
        int dstValue = value % numDsts;
        transfer.srcMemType = srcList[srcValue].first;
        transfer.srcIndex   = srcList[srcValue].second;
        transfer.exeMemType = ev.sweepSrcIsExe ? transfer.srcMemType : exeList[exeValue].first;
        transfer.exeIndex   = ev.sweepSrcIsExe ? transfer.srcIndex   : exeList[exeValue].second;
        transfer.dstMemType = dstList[dstValue].first;
        transfer.dstIndex   = dstList[dstValue].second;
        transfer.numBlocksToUse = IsGpuType(transfer.exeMemType) ? 4 : ev.numCpuPerTransfer;
        transfer.transferIndex = transfers.size();
        transfers.push_back(transfer);
      }
    }

    ExecuteTransfers(ev, ++numTestsRun, valuesOfN, transfers);

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