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

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

81
    ev.configMode = CFG_SWEEP;
gilbertlee-amd's avatar
gilbertlee-amd committed
82
    RunSweepPreset(ev, numBytesPerTransfer, numBlocksToUse, !strcmp(argv[1], "rsweep"));
Gilbert Lee's avatar
Gilbert Lee committed
83
84
85
86
87
    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
88
89
90
91
92
93
94
95
96
97
98
99
100
  {
    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
101
    ev.configMode = CFG_P2P;
Gilbert Lee's avatar
Gilbert Lee committed
102
    RunPeerToPeerBenchmarks(ev, numBytesPerTransfer / sizeof(float), numBlocksToUse, readMode, skipCpu);
Gilbert Lee's avatar
Gilbert Lee committed
103
104
105
    exit(0);
  }

Gilbert Lee's avatar
Gilbert Lee committed
106
  // Check that Transfer configuration file can be opened
107
  ev.configMode = CFG_FILE;
Gilbert Lee's avatar
Gilbert Lee committed
108
109
110
  FILE* fp = fopen(argv[1], "r");
  if (!fp)
  {
Gilbert Lee's avatar
Gilbert Lee committed
111
    printf("[ERROR] Unable to open transfer configuration file: [%s]\n", argv[1]);
Gilbert Lee's avatar
Gilbert Lee committed
112
113
114
    exit(1);
  }

Gilbert Lee's avatar
Gilbert Lee committed
115
  // Print environment variables and CSV header
Gilbert Lee's avatar
Gilbert Lee committed
116
117
118
  ev.DisplayEnvVars();
  if (ev.outputToCsv)
  {
119
120
    printf("Test#,Transfer#,NumBytes,Src,Exe,Dst,CUs,BW(GB/s),Time(ms),"
           "ExeToSrcLinkType,ExeToDstLinkType,SrcAddr,DstAddr\n");
Gilbert Lee's avatar
Gilbert Lee committed
121
122
123
124
125
126
127
128
129
  }

  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
130
131
132
133
    // 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
134

gilbertlee-amd's avatar
gilbertlee-amd committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    // 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
155
156
  }
  fclose(fp);
Gilbert Lee's avatar
Gilbert Lee committed
157

Gilbert Lee's avatar
Gilbert Lee committed
158
159
  return 0;
}
Gilbert Lee's avatar
Gilbert Lee committed
160

Gilbert Lee's avatar
Gilbert Lee committed
161
void ExecuteTransfers(EnvVars const& ev,
gilbertlee-amd's avatar
gilbertlee-amd committed
162
163
164
165
                      int const testNum,
                      size_t const N,
                      std::vector<Transfer>& transfers,
                      bool verbose)
Gilbert Lee's avatar
Gilbert Lee committed
166
167
{
  int const initOffset = ev.byteOffset / sizeof(float);
Gilbert Lee's avatar
Gilbert Lee committed
168

Gilbert Lee's avatar
Gilbert Lee committed
169
170
  // Map transfers by executor
  TransferMap transferMap;
gilbertlee-amd's avatar
gilbertlee-amd committed
171
  for (Transfer& transfer : transfers)
Gilbert Lee's avatar
Gilbert Lee committed
172
173
174
  {
    Executor executor(transfer.exeMemType, transfer.exeIndex);
    ExecutorInfo& executorInfo = transferMap[executor];
gilbertlee-amd's avatar
gilbertlee-amd committed
175
    executorInfo.transfers.push_back(&transfer);
Gilbert Lee's avatar
Gilbert Lee committed
176
  }
Gilbert Lee's avatar
Gilbert Lee committed
177

Gilbert Lee's avatar
Gilbert Lee committed
178
  // Loop over each executor and prepare GPU resources
gilbertlee-amd's avatar
gilbertlee-amd committed
179
  std::map<int, Transfer*> transferList;
Gilbert Lee's avatar
Gilbert Lee committed
180
181
182
183
184
185
186
187
  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
gilbertlee-amd's avatar
gilbertlee-amd committed
188
    for (Transfer* transfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
189
190
    {
      // Get some aliases to transfer variables
gilbertlee-amd's avatar
gilbertlee-amd committed
191
192
193
194
      MemType const& exeMemType  = transfer->exeMemType;
      MemType const& srcMemType  = transfer->srcMemType;
      MemType const& dstMemType  = transfer->dstMemType;
      int     const& blocksToUse = transfer->numBlocksToUse;
Gilbert Lee's avatar
Gilbert Lee committed
195
196

      // Get potentially remapped device indices
gilbertlee-amd's avatar
gilbertlee-amd committed
197
198
199
      int const srcIndex = RemappedIndex(transfer->srcIndex, srcMemType);
      int const exeIndex = RemappedIndex(transfer->exeIndex, exeMemType);
      int const dstIndex = RemappedIndex(transfer->dstIndex, dstMemType);
Gilbert Lee's avatar
Gilbert Lee committed
200
201

      // Enable peer-to-peer access if necessary (can only be called once per unique pair)
Gilbert Lee's avatar
Gilbert Lee committed
202
203
      if (exeMemType == MEM_GPU)
      {
Gilbert Lee's avatar
Gilbert Lee committed
204
205
206
        // 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
207

Gilbert Lee's avatar
Gilbert Lee committed
208
209
210
        // 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
211
      }
Gilbert Lee's avatar
Gilbert Lee committed
212
213

      // Allocate (maximum) source / destination memory based on type / device index
gilbertlee-amd's avatar
gilbertlee-amd committed
214
215
216
      transfer->numBytesToCopy = (transfer->numBytes ? transfer->numBytes : N * sizeof(float));
      AllocateMemory(srcMemType, srcIndex, transfer->numBytesToCopy + ev.byteOffset, (void**)&transfer->srcMem);
      AllocateMemory(dstMemType, dstIndex, transfer->numBytesToCopy + ev.byteOffset, (void**)&transfer->dstMem);
Gilbert Lee's avatar
Gilbert Lee committed
217

gilbertlee-amd's avatar
gilbertlee-amd committed
218
219
220
      transfer->blockParam.resize(exeMemType == MEM_CPU ? ev.numCpuPerTransfer : blocksToUse);
      exeInfo.totalBlocks += transfer->blockParam.size();
      transferList[transfer->transferIndex] = transfer;
Gilbert Lee's avatar
Gilbert Lee committed
221
222
    }

Gilbert Lee's avatar
Gilbert Lee committed
223
224
225
226
    // 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
227
    {
Gilbert Lee's avatar
Gilbert Lee committed
228
229
230
231
232
233
234
235
236
237
      // 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
238
      {
Gilbert Lee's avatar
Gilbert Lee committed
239
240
241
242
243
        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
244

Gilbert Lee's avatar
Gilbert Lee committed
245
246
247
248
      // Assign each transfer its portion of threadblock parameters
      int transferOffset = 0;
      for (int i = 0; i < exeInfo.transfers.size(); i++)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
249
250
        exeInfo.transfers[i]->blockParamGpuPtr = exeInfo.blockParamGpu + transferOffset;
        transferOffset += exeInfo.transfers[i]->blockParam.size();
Gilbert Lee's avatar
Gilbert Lee committed
251
252
253
      }
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
254

gilbertlee-amd's avatar
gilbertlee-amd committed
255
256
257
258
  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
259
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
260
261
    ExecutorInfo& exeInfo = exeInfoPair.second;
    exeInfo.totalBytes = 0;
Gilbert Lee's avatar
Gilbert Lee committed
262

gilbertlee-amd's avatar
gilbertlee-amd committed
263
264
    int transferOffset = 0;
    for (int i = 0; i < exeInfo.transfers.size(); ++i)
Gilbert Lee's avatar
Gilbert Lee committed
265
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
266
267
268
269
      // Prepare subarrays each threadblock works on and fill src memory with patterned data
      Transfer* transfer = exeInfo.transfers[i];
      transfer->PrepareBlockParams(ev, transfer->numBytesToCopy / sizeof(float));
      exeInfo.totalBytes += transfer->numBytesToCopy;
Gilbert Lee's avatar
Gilbert Lee committed
270

gilbertlee-amd's avatar
gilbertlee-amd committed
271
272
      // Copy block parameters to GPU for GPU executors
      if (transfer->exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
273
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
274
275
276
277
278
        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
279
280
      }
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
281
  }
Gilbert Lee's avatar
Gilbert Lee committed
282

gilbertlee-amd's avatar
gilbertlee-amd committed
283
284
285
286
287
288
289
290
  // 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
291

gilbertlee-amd's avatar
gilbertlee-amd committed
292
293
    // Pause before starting first timed iteration in interactive mode
    if (verbose && ev.useInteractive && iteration == 0)
Gilbert Lee's avatar
Gilbert Lee committed
294
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
295
      printf("Hit <Enter> to continue: ");
Gilbert Lee's avatar
Gilbert Lee committed
296
297
298
      scanf("%*c");
      printf("\n");
    }
Gilbert Lee's avatar
Gilbert Lee committed
299

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

    // Execute all Transfers in parallel
    for (auto& exeInfoPair : transferMap)
305
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
306
307
308
309
310
      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), iteration, std::ref(exeInfo), i));
311
    }
Gilbert Lee's avatar
Gilbert Lee committed
312

gilbertlee-amd's avatar
gilbertlee-amd committed
313
314
315
316
317
318
319
    // 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
320

gilbertlee-amd's avatar
gilbertlee-amd committed
321
322
323
324
325
    // 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
326
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
327
328
329
330
      ++numTimedIterations;
      totalCpuTime += deltaSec;
    }
  }
Gilbert Lee's avatar
Gilbert Lee committed
331

gilbertlee-amd's avatar
gilbertlee-amd committed
332
333
334
335
336
337
338
  // Pause for interactive mode
  if (verbose && ev.useInteractive)
  {
    printf("Transfers complete. Hit <Enter> to continue: ");
    scanf("%*c");
    printf("\n");
  }
Gilbert Lee's avatar
Gilbert Lee committed
339

gilbertlee-amd's avatar
gilbertlee-amd committed
340
341
342
343
344
345
346
347
348
  // Validate that each transfer has transferred correctly
  size_t totalBytesTransferred = 0;
  int const numTransfers = transferList.size();
  for (auto transferPair : transferList)
  {
    Transfer* transfer = transferPair.second;
    CheckOrFill(MODE_CHECK, transfer->numBytesToCopy / sizeof(float), ev.useMemset, ev.useHipCall, ev.fillPattern, transfer->dstMem + initOffset);
    totalBytesTransferred += transfer->numBytesToCopy;
  }
Gilbert Lee's avatar
Gilbert Lee committed
349

gilbertlee-amd's avatar
gilbertlee-amd committed
350
351
352
353
  // Report timings
  totalCpuTime = totalCpuTime / (1.0 * numTimedIterations) * 1000;
  double totalBandwidthGbs = (totalBytesTransferred / 1.0E6) / totalCpuTime;
  double maxGpuTime = 0;
Gilbert Lee's avatar
Gilbert Lee committed
354

gilbertlee-amd's avatar
gilbertlee-amd committed
355
356
357
358
359
360
361
  if (ev.useSingleStream)
  {
    for (auto& exeInfoPair : transferMap)
    {
      ExecutorInfo  exeInfo    = exeInfoPair.second;
      MemType const exeMemType = exeInfoPair.first.first;
      int     const exeIndex   = exeInfoPair.first.second;
Gilbert Lee's avatar
Gilbert Lee committed
362

gilbertlee-amd's avatar
gilbertlee-amd committed
363
364
365
366
367
368
369
      // Compute total time for CPU executors
      if (!IsGpuType(exeMemType))
      {
        exeInfo.totalTime = 0;
        for (auto const& transfer : exeInfo.transfers)
          exeInfo.totalTime = std::max(exeInfo.totalTime, transfer->transferTime);
      }
370

gilbertlee-amd's avatar
gilbertlee-amd committed
371
372
373
      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
374

gilbertlee-amd's avatar
gilbertlee-amd committed
375
376
377
378
      if (verbose && !ev.outputToCsv)
      {
        printf(" Executor: %cPU %02d        (# Transfers %02lu)| %9.3f GB/s | %8.3f ms | %12lu bytes\n",
               MemTypeStr[exeMemType], exeIndex, exeInfo.transfers.size(), exeBandwidthGbs, exeDurationMsec, exeInfo.totalBytes);
Gilbert Lee's avatar
Gilbert Lee committed
379
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
380
381
382

      int totalCUs = 0;
      for (auto const& transfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
383
      {
Gilbert Lee's avatar
Gilbert Lee committed
384
        double transferDurationMsec = transfer->transferTime / (1.0 * numTimedIterations);
gilbertlee-amd's avatar
gilbertlee-amd committed
385
386
387
388
        double transferBandwidthGbs = (N * sizeof(float) / 1.0E9) / transferDurationMsec * 1000.0f;
        totalCUs += transfer->exeMemType == MEM_CPU ? ev.numCpuPerTransfer : transfer->numBlocksToUse;

        if (!verbose) continue;
Gilbert Lee's avatar
Gilbert Lee committed
389
390
        if (!ev.outputToCsv)
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
391
          printf("                            Transfer  %02d | %9.3f GB/s | %8.3f ms | %12lu bytes | %c%02d -> %c%02d:(%03d) -> %c%02d\n",
Gilbert Lee's avatar
Gilbert Lee committed
392
                 transfer->transferIndex,
gilbertlee-amd's avatar
gilbertlee-amd committed
393
394
395
                 transferBandwidthGbs,
                 transferDurationMsec,
                 transfer->numBytesToCopy,
Gilbert Lee's avatar
Gilbert Lee committed
396
397
398
                 MemTypeStr[transfer->srcMemType], transfer->srcIndex,
                 MemTypeStr[transfer->exeMemType], transfer->exeIndex,
                 transfer->exeMemType == MEM_CPU ? ev.numCpuPerTransfer : transfer->numBlocksToUse,
gilbertlee-amd's avatar
gilbertlee-amd committed
399
400
                 MemTypeStr[transfer->dstMemType], transfer->dstIndex);

Gilbert Lee's avatar
Gilbert Lee committed
401
402
403
        }
        else
        {
404
          printf("%d,%d,%lu,%c%02d,%c%02d,%c%02d,%d,%.3f,%.3f,%s,%s,%p,%p\n",
gilbertlee-amd's avatar
gilbertlee-amd committed
405
                 testNum, transfer->transferIndex, transfer->numBytesToCopy,
Gilbert Lee's avatar
Gilbert Lee committed
406
407
408
409
410
                 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,
411
412
413
                 GetDesc(transfer->exeMemType, transfer->exeIndex, transfer->srcMemType, transfer->srcIndex).c_str(),
                 GetDesc(transfer->exeMemType, transfer->exeIndex, transfer->dstMemType, transfer->dstIndex).c_str(),
                 transfer->srcMem + initOffset, transfer->dstMem + initOffset);
Gilbert Lee's avatar
Gilbert Lee committed
414
        }
Gilbert Lee's avatar
Gilbert Lee committed
415
      }
gilbertlee-amd's avatar
gilbertlee-amd committed
416
417
418
419
420
421
422
423

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

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

Gilbert Lee's avatar
Gilbert Lee committed
478
479
480
481
482
483
484
  // Release GPU memory
  for (auto exeInfoPair : transferMap)
  {
    ExecutorInfo& exeInfo = exeInfoPair.second;
    for (auto& transfer : exeInfo.transfers)
    {
      // Get some aliases to Transfer variables
gilbertlee-amd's avatar
gilbertlee-amd committed
485
486
487
      MemType const& exeMemType = transfer->exeMemType;
      MemType const& srcMemType = transfer->srcMemType;
      MemType const& dstMemType = transfer->dstMemType;
Gilbert Lee's avatar
Gilbert Lee committed
488
489

      // Allocate (maximum) source / destination memory based on type / device index
gilbertlee-amd's avatar
gilbertlee-amd committed
490
491
492
      DeallocateMemory(srcMemType, transfer->srcMem,  N * sizeof(float) + ev.byteOffset);
      DeallocateMemory(dstMemType, transfer->dstMem,  N * sizeof(float) + ev.byteOffset);
      transfer->blockParam.clear();
Gilbert Lee's avatar
Gilbert Lee committed
493
494
495
496
497
498
499
500
501
    }

    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
502
      {
Gilbert Lee's avatar
Gilbert Lee committed
503
504
505
        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
506
507
508
509
510
511
512
      }
    }
  }
}

void DisplayUsage(char const* cmdName)
{
Gilbert Lee's avatar
Gilbert Lee committed
513
  printf("TransferBench v%s\n", TB_VERSION);
Gilbert Lee's avatar
Gilbert Lee committed
514
515
516
517
518
519
520
521
522
523
524
525
526
  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
527
  printf("          - Filename of configFile containing Transfers to execute (see example.cfg for format)\n");
Gilbert Lee's avatar
Gilbert Lee committed
528
  printf("          - Name of preset benchmark:\n");
Gilbert Lee's avatar
Gilbert Lee committed
529
530
531
532
  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");
gilbertlee-amd's avatar
gilbertlee-amd committed
533
  printf("            - 3rd optional argument used as # of CUs to use (all by default for p2p / 4 for sweep)\n");
Gilbert Lee's avatar
Gilbert Lee committed
534
  printf("  N     : (Optional) Number of bytes to copy per Transfer.\n");
Gilbert Lee's avatar
Gilbert Lee committed
535
  printf("          If not specified, defaults to %lu bytes. Must be a multiple of 4 bytes\n",
Gilbert Lee's avatar
Gilbert Lee committed
536
         DEFAULT_BYTES_PER_TRANSFER);
Gilbert Lee's avatar
Gilbert Lee committed
537
538
539
540
541
542
543
544
545
  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)
{
546
547
  static std::vector<int> remappingCpu;
  static std::vector<int> remappingGpu;
Gilbert Lee's avatar
Gilbert Lee committed
548

549
550
551
552
553
554
555
556
  // 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
557

558
559
  // Build remappingGpu on first use
  if (remappingGpu.empty())
Gilbert Lee's avatar
Gilbert Lee committed
560
561
562
  {
    int numGpuDevices;
    HIP_CALL(hipGetDeviceCount(&numGpuDevices));
563
    remappingGpu.resize(numGpuDevices);
Gilbert Lee's avatar
Gilbert Lee committed
564
565
566
567

    int const usePcieIndexing = getenv("USE_PCIE_INDEX") ? atoi(getenv("USE_PCIE_INDEX")) : 0;
    if (!usePcieIndexing)
    {
568
      // For HIP-based indexing no remappingGpu is necessary
Gilbert Lee's avatar
Gilbert Lee committed
569
      for (int i = 0; i < numGpuDevices; ++i)
570
        remappingGpu[i] = i;
Gilbert Lee's avatar
Gilbert Lee committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
    }
    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)
585
        remappingGpu[i] = mapping[i].second;
Gilbert Lee's avatar
Gilbert Lee committed
586
587
    }
  }
588
  return IsCpuType(memType) ? remappingCpu[origIdx] : remappingGpu[origIdx];
Gilbert Lee's avatar
Gilbert Lee committed
589
590
591
592
}

void DisplayTopology(bool const outputToCsv)
{
593
  int numCpuDevices = numa_num_configured_nodes();
Gilbert Lee's avatar
Gilbert Lee committed
594
595
596
597
598
  int numGpuDevices;
  HIP_CALL(hipGetDeviceCount(&numGpuDevices));

  if (outputToCsv)
  {
599
    printf("NumCpus,%d\n", numCpuDevices);
Gilbert Lee's avatar
Gilbert Lee committed
600
    printf("NumGpus,%d\n", numGpuDevices);
601
602
603
  }
  else
  {
604
605
    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);
606
607
608
609
610
611
612
613
  }

  // Print out detected CPU topology
  if (outputToCsv)
  {
    printf("NUMA");
    for (int j = 0; j < numCpuDevices; j++)
      printf(",NUMA%02d", j);
614
    printf(",# CPUs,ClosestGPUs,ActualNode\n");
615
616
617
  }
  else
  {
618
    printf("            |");
619
    for (int j = 0; j < numCpuDevices; j++)
620
621
622
623
      printf("NUMA %02d|", j);
    printf(" #Cpus | Closest GPU(s)\n");

    printf("------------+");
624
    for (int j = 0; j <= numCpuDevices; j++)
625
626
      printf("-------+");
    printf("---------------\n");
627
628
629
630
  }

  for (int i = 0; i < numCpuDevices; i++)
  {
631
632
    int nodeI = RemappedIndex(i, MEM_CPU);
    printf("NUMA %02d (%02d)%s", i, nodeI, outputToCsv ? "," : "|");
633
634
    for (int j = 0; j < numCpuDevices; j++)
    {
635
636
      int nodeJ = RemappedIndex(j, MEM_CPU);
      int numaDist = numa_distance(nodeI, nodeJ);
637
      if (outputToCsv)
gilbertlee-amd's avatar
gilbertlee-amd committed
638
        printf("%d,", numaDist);
639
      else
640
        printf(" %5d |", numaDist);
641
642
643
644
    }

    int numCpus = 0;
    for (int j = 0; j < numa_num_configured_cpus(); j++)
645
      if (numa_node_of_cpu(j) == nodeI) numCpus++;
646
647
648
    if (outputToCsv)
      printf("%d,", numCpus);
    else
649
      printf(" %5d | ", numCpus);
650
651
652
653
654
655
656

    bool isFirst = true;
    for (int j = 0; j < numGpuDevices; j++)
    {
      if (GetClosestNumaNode(RemappedIndex(j, MEM_GPU)) == i)
      {
        if (isFirst) isFirst = false;
gilbertlee-amd's avatar
gilbertlee-amd committed
657
658
        else printf(",");
        printf("%d", j);
659
660
661
662
663
664
665
666
667
      }
    }
    printf("\n");
  }
  printf("\n");

  // Print out detected GPU topology
  if (outputToCsv)
  {
Gilbert Lee's avatar
Gilbert Lee committed
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    printf("GPU");
    for (int j = 0; j < numGpuDevices; j++)
      printf(",GPU %02d", j);
    printf(",PCIe Bus ID,ClosestNUMA\n");
  }
  else
  {
    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)));
  }
}

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)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
734
735
  case 'C': case 'c': case 'B': case 'b': case 'U': case 'u':
    *memType = (typeChar == 'C' || typeChar == 'c') ? MEM_CPU : ((typeChar == 'B' || typeChar == 'b') ? MEM_CPU_FINE : MEM_CPU_UNPINNED);
Gilbert Lee's avatar
Gilbert Lee committed
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
    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:
gilbertlee-amd's avatar
gilbertlee-amd committed
751
    printf("[ERROR] Unrecognized memory type %s.  Expecting either 'B','C','U','G' or 'F'\n", token.c_str());
Gilbert Lee's avatar
Gilbert Lee committed
752
753
754
755
    exit(1);
  }
}

Gilbert Lee's avatar
Gilbert Lee committed
756
// Helper function to parse a list of Transfer definitions
Gilbert Lee's avatar
Gilbert Lee committed
757
void ParseTransfers(char* line, int numCpus, int numGpus, std::vector<Transfer>& transfers)
Gilbert Lee's avatar
Gilbert Lee committed
758
759
760
761
762
{
  // 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
763
  transfers.clear();
Gilbert Lee's avatar
Gilbert Lee committed
764

Gilbert Lee's avatar
Gilbert Lee committed
765
  int numTransfers = 0;
Gilbert Lee's avatar
Gilbert Lee committed
766
  std::istringstream iss(line);
Gilbert Lee's avatar
Gilbert Lee committed
767
  iss >> numTransfers;
Gilbert Lee's avatar
Gilbert Lee committed
768
769
770
771
772
  if (iss.fail()) return;

  std::string exeMem;
  std::string srcMem;
  std::string dstMem;
Gilbert Lee's avatar
Gilbert Lee committed
773
774
775

  // If numTransfers < 0, read quads (srcMem, exeMem, dstMem, #CUs)
  // otherwise read triples (srcMem, exeMem, dstMem)
gilbertlee-amd's avatar
gilbertlee-amd committed
776
  bool const advancedMode = (numTransfers < 0);
Gilbert Lee's avatar
Gilbert Lee committed
777
778
779
  numTransfers = abs(numTransfers);

  int numBlocksToUse;
gilbertlee-amd's avatar
gilbertlee-amd committed
780
  if (!advancedMode)
Gilbert Lee's avatar
Gilbert Lee committed
781
782
783
784
785
786
787
788
789
  {
    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);
    }
  }

gilbertlee-amd's avatar
gilbertlee-amd committed
790
  size_t numBytes = 0;
Gilbert Lee's avatar
Gilbert Lee committed
791
792
793
794
  for (int i = 0; i < numTransfers; i++)
  {
    Transfer transfer;
    transfer.transferIndex = i;
gilbertlee-amd's avatar
gilbertlee-amd committed
795
796
797
    transfer.numBytes = 0;
    transfer.numBytesToCopy = 0;
    if (!advancedMode)
Gilbert Lee's avatar
Gilbert Lee committed
798
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
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
      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;
      iss >> srcMem >> exeMem >> dstMem >> numBlocksToUse >> numBytesToken;
      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();
      switch (units)
      {
      case 'K': case 'k': numBytes *= 1024; break;
      case 'M': case 'm': numBytes *= 1024*1024; break;
      case 'G': case 'g': numBytes *= 1024*1024*1024; break;
      }
Gilbert Lee's avatar
Gilbert Lee committed
827
    }
Gilbert Lee's avatar
Gilbert Lee committed
828
829
830
831
832

    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;
gilbertlee-amd's avatar
gilbertlee-amd committed
833
    transfer.numBytes = numBytes;
Gilbert Lee's avatar
Gilbert Lee committed
834
    transfers.push_back(transfer);
Gilbert Lee's avatar
Gilbert Lee committed
835
836
837
838
839
840
841
842
843
844
845
846
847
  }
}

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
848
849
850
851
852
853
854
  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
855
856
857
858
859
860
861
862
863
864
}

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
865
  if (IsCpuType(memType))
Gilbert Lee's avatar
Gilbert Lee committed
866
867
  {
    // Set numa policy prior to call to hipHostMalloc
gilbertlee-amd's avatar
gilbertlee-amd committed
868
    unsigned long nodemask = (1ULL << devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
869
870
871
    long retCode = set_mempolicy(MPOL_BIND, &nodemask, sizeof(nodemask)*8);
    if (retCode)
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
872
      printf("[ERROR] Unable to set NUMA memory policy to bind to NUMA node %d\n", devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
873
874
875
876
      exit(1);
    }

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

Gilbert Lee's avatar
Gilbert Lee committed
878
879
880
881
    if (memType == MEM_CPU_FINE)
    {
      HIP_CALL(hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser));
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
882
    else if (memType == MEM_CPU)
Gilbert Lee's avatar
Gilbert Lee committed
883
    {
884
885
886
887
888
      if (hipHostMalloc((void **)memPtr, numBytes, hipHostMallocNumaUser | hipHostMallocNonCoherent) != hipSuccess)
      {
        printf("[ERROR] Unable to allocate non-coherent host memory on NUMA node %d\n", devIndex);
        exit(1);
      }
Gilbert Lee's avatar
Gilbert Lee committed
889
    }
gilbertlee-amd's avatar
gilbertlee-amd committed
890
891
892
893
    else if (memType == MEM_CPU_UNPINNED)
    {
      *memPtr = numa_alloc_onnode(numBytes, devIndex);
    }
Gilbert Lee's avatar
Gilbert Lee committed
894
895

    // Check that the allocated pages are actually on the correct NUMA node
gilbertlee-amd's avatar
gilbertlee-amd committed
896
897
    memset(*memPtr, 0, numBytes);
    CheckPages((char*)*memPtr, numBytes, devIndex);
Gilbert Lee's avatar
Gilbert Lee committed
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

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

gilbertlee-amd's avatar
gilbertlee-amd committed
925
void DeallocateMemory(MemType memType, void* memPtr, size_t const bytes)
Gilbert Lee's avatar
Gilbert Lee committed
926
927
928
929
930
{
  if (memType == MEM_CPU || memType == MEM_CPU_FINE)
  {
    HIP_CALL(hipHostFree(memPtr));
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
931
932
933
934
  else if (memType == MEM_CPU_UNPINNED)
  {
    numa_free(memPtr, bytes);
  }
Gilbert Lee's avatar
Gilbert Lee committed
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
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
  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)
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1055
  if (IsCpuType(srcMemType))
Gilbert Lee's avatar
Gilbert Lee committed
1056
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1057
1058
1059
    if (IsCpuType(dstMemType)) return (srcIndex == dstIndex) ? "LOCAL" : "NUMA";
    if (IsGpuType(dstMemType)) return "PCIE";
    goto error;
Gilbert Lee's avatar
Gilbert Lee committed
1060
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1061
  if (IsGpuType(srcMemType))
Gilbert Lee's avatar
Gilbert Lee committed
1062
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1063
1064
    if (IsCpuType(dstMemType)) return "PCIE";
    if (IsGpuType(dstMemType))
Gilbert Lee's avatar
Gilbert Lee committed
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
    {
      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);
      }
    }
  }
error:
  printf("[ERROR] Unrecognized memory type\n");
  exit(1);
}

Gilbert Lee's avatar
Gilbert Lee committed
1082
std::string GetTransferDesc(Transfer const& transfer)
Gilbert Lee's avatar
Gilbert Lee committed
1083
{
Gilbert Lee's avatar
Gilbert Lee committed
1084
1085
  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
1086
1087
}

1088
void RunTransfer(EnvVars const& ev, int const iteration,
Gilbert Lee's avatar
Gilbert Lee committed
1089
                 ExecutorInfo& exeInfo, int const transferIdx)
Gilbert Lee's avatar
Gilbert Lee committed
1090
{
gilbertlee-amd's avatar
gilbertlee-amd committed
1091
  Transfer* transfer = exeInfo.transfers[transferIdx];
Gilbert Lee's avatar
Gilbert Lee committed
1092
1093

  // GPU execution agent
gilbertlee-amd's avatar
gilbertlee-amd committed
1094
  if (transfer->exeMemType == MEM_GPU)
Gilbert Lee's avatar
Gilbert Lee committed
1095
1096
  {
    // Switch to executing GPU
gilbertlee-amd's avatar
gilbertlee-amd committed
1097
    int const exeIndex = RemappedIndex(transfer->exeIndex, MEM_GPU);
Gilbert Lee's avatar
Gilbert Lee committed
1098
1099
    HIP_CALL(hipSetDevice(exeIndex));

Gilbert Lee's avatar
Gilbert Lee committed
1100
1101
1102
    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
1103
1104
1105
1106
1107
1108

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

    if (ev.useHipCall)
    {
      // Record start event
Gilbert Lee's avatar
Gilbert Lee committed
1109
      HIP_CALL(hipEventRecord(startEvent, stream));
Gilbert Lee's avatar
Gilbert Lee committed
1110
1111
1112

      // Execute hipMemset / hipMemcpy
      if (ev.useMemset)
gilbertlee-amd's avatar
gilbertlee-amd committed
1113
        HIP_CALL(hipMemsetAsync(transfer->dstMem + initOffset, 42, transfer->numBytesToCopy, stream));
Gilbert Lee's avatar
Gilbert Lee committed
1114
      else
gilbertlee-amd's avatar
gilbertlee-amd committed
1115
1116
1117
        HIP_CALL(hipMemcpyAsync(transfer->dstMem + initOffset,
                                transfer->srcMem + initOffset,
                                transfer->numBytesToCopy, hipMemcpyDefault,
Gilbert Lee's avatar
Gilbert Lee committed
1118
1119
                                stream));
      // Record stop event
Gilbert Lee's avatar
Gilbert Lee committed
1120
      HIP_CALL(hipEventRecord(stopEvent, stream));
Gilbert Lee's avatar
Gilbert Lee committed
1121
1122
1123
    }
    else
    {
gilbertlee-amd's avatar
gilbertlee-amd committed
1124
      int const numBlocksToRun = ev.useSingleStream ? exeInfo.totalBlocks : transfer->numBlocksToUse;
Gilbert Lee's avatar
Gilbert Lee committed
1125
1126
1127
1128
      hipExtLaunchKernelGGL(ev.useMemset ? GpuMemsetKernel : GpuCopyKernel,
                            dim3(numBlocksToRun, 1, 1),
                            dim3(BLOCKSIZE, 1, 1),
                            ev.sharedMemBytes, stream,
Gilbert Lee's avatar
Gilbert Lee committed
1129
                            startEvent, stopEvent,
gilbertlee-amd's avatar
gilbertlee-amd committed
1130
                            0, transfer->blockParamGpuPtr);
Gilbert Lee's avatar
Gilbert Lee committed
1131
1132
1133
1134
    }

    // 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
1135
    HIP_CALL(hipStreamSynchronize(stream));
Gilbert Lee's avatar
Gilbert Lee committed
1136
1137
1138
1139

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

Gilbert Lee's avatar
Gilbert Lee committed
1143
1144
      if (ev.useSingleStream)
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1145
        for (Transfer* currTransfer : exeInfo.transfers)
Gilbert Lee's avatar
Gilbert Lee committed
1146
        {
gilbertlee-amd's avatar
gilbertlee-amd committed
1147
1148
1149
          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
1150
          {
gilbertlee-amd's avatar
gilbertlee-amd committed
1151
1152
            minStartCycle = std::min(minStartCycle, currTransfer->blockParamGpuPtr[i].startCycle);
            maxStopCycle  = std::max(maxStopCycle,  currTransfer->blockParamGpuPtr[i].stopCycle);
Gilbert Lee's avatar
Gilbert Lee committed
1153
          }
Gilbert Lee's avatar
Gilbert Lee committed
1154
1155
          int const wallClockRate = GetWallClockRate(exeIndex);
          double iterationTimeMs = (maxStopCycle - minStartCycle) / (double)(wallClockRate);
gilbertlee-amd's avatar
gilbertlee-amd committed
1156
          currTransfer->transferTime += iterationTimeMs;
Gilbert Lee's avatar
Gilbert Lee committed
1157
        }
Gilbert Lee's avatar
Gilbert Lee committed
1158
1159
1160
1161
        exeInfo.totalTime += gpuDeltaMsec;
      }
      else
      {
gilbertlee-amd's avatar
gilbertlee-amd committed
1162
        transfer->transferTime += gpuDeltaMsec;
Gilbert Lee's avatar
Gilbert Lee committed
1163
1164
1165
      }
    }
  }
gilbertlee-amd's avatar
gilbertlee-amd committed
1166
  else if (transfer->exeMemType == MEM_CPU) // CPU execution agent
Gilbert Lee's avatar
Gilbert Lee committed
1167
1168
  {
    // Force this thread and all child threads onto correct NUMA node
1169
1170
    int const exeIndex = RemappedIndex(transfer->exeIndex, MEM_CPU);
    if (numa_run_on_node(exeIndex))
Gilbert Lee's avatar
Gilbert Lee committed
1171
    {
1172
      printf("[ERROR] Unable to set CPU to NUMA node %d\n", exeIndex);
Gilbert Lee's avatar
Gilbert Lee committed
1173
1174
1175
1176
1177
1178
1179
1180
      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
1181
    for (int i = 0; i < ev.numCpuPerTransfer; i++)
gilbertlee-amd's avatar
gilbertlee-amd committed
1182
      childThreads.push_back(std::thread(ev.useMemset ? CpuMemsetKernel : CpuCopyKernel, std::ref(transfer->blockParam[i])));
Gilbert Lee's avatar
Gilbert Lee committed
1183
1184

    // Wait for child-threads to finish
Gilbert Lee's avatar
Gilbert Lee committed
1185
    for (int i = 0; i < ev.numCpuPerTransfer; i++)
Gilbert Lee's avatar
Gilbert Lee committed
1186
1187
1188
1189
1190
1191
      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
1192
      transfer->transferTime += (std::chrono::duration_cast<std::chrono::duration<double>>(cpuDelta).count() * 1000.0);
Gilbert Lee's avatar
Gilbert Lee committed
1193
1194
1195
1196
1197
1198
  }
}

void RunPeerToPeerBenchmarks(EnvVars const& ev, size_t N, int numBlocksToUse, int readMode, int skipCpu)
{
  // Collect the number of available CPUs/GPUs on this machine
1199
1200
  int const numGpus = ev.numGpuDevices;
  int const numCpus = ev.numCpuDevices;
Gilbert Lee's avatar
Gilbert Lee committed
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
  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
1211
    printf("Using %d threads per NUMA node for CPU copies\n", ev.numCpuPerTransfer);
Gilbert Lee's avatar
Gilbert Lee committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
    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
1296
  // Prepare Transfers
gilbertlee-amd's avatar
gilbertlee-amd committed
1297
1298
1299
  std::vector<Transfer> transfers(2);
  transfers[0].srcMemType     = transfers[1].dstMemType     = srcMemType;
  transfers[0].dstMemType     = transfers[1].srcMemType     = dstMemType;
1300
1301
  transfers[0].srcIndex       = transfers[1].dstIndex       = srcIndex;
  transfers[0].dstIndex       = transfers[1].srcIndex       = dstIndex;
gilbertlee-amd's avatar
gilbertlee-amd committed
1302
1303
  transfers[0].numBytes       = transfers[1].numBytes       = N * sizeof(float);
  transfers[0].numBlocksToUse = transfers[1].numBlocksToUse = numBlocksToUse;
Gilbert Lee's avatar
Gilbert Lee committed
1304
1305

  // Either perform (local read + remote write), or (remote read + local write)
gilbertlee-amd's avatar
gilbertlee-amd committed
1306
1307
  transfers[0].exeMemType = (readMode == 0 ? srcMemType : dstMemType);
  transfers[1].exeMemType = (readMode == 0 ? dstMemType : srcMemType);
1308
1309
  transfers[0].exeIndex   = (readMode == 0 ? srcIndex   : dstIndex);
  transfers[1].exeIndex   = (readMode == 0 ? dstIndex   : srcIndex);
gilbertlee-amd's avatar
gilbertlee-amd committed
1310
1311

  transfers.resize(isBidirectional + 1);
Gilbert Lee's avatar
Gilbert Lee committed
1312

1313
1314
1315
  // Abort if executing on NUMA node with no CPUs
  for (int i = 0; i <= isBidirectional; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1316
    if (transfers[i].exeMemType == MEM_CPU && ev.numCpusPerNuma[transfers[i].exeIndex] == 0)
1317
1318
1319
      return 0;
  }

gilbertlee-amd's avatar
gilbertlee-amd committed
1320
  ExecuteTransfers(ev, 0, N, transfers, false);
Gilbert Lee's avatar
Gilbert Lee committed
1321
1322
1323
1324
1325

  // Collect aggregate bandwidth
  double totalBandwidth = 0;
  for (int i = 0; i <= isBidirectional; i++)
  {
gilbertlee-amd's avatar
gilbertlee-amd committed
1326
1327
    double transferDurationMsec = transfers[i].transferTime / (1.0 * ev.numIterations);
    double transferBandwidthGbs = (transfers[i].numBytesToCopy / 1.0E9) / transferDurationMsec * 1000.0f;
Gilbert Lee's avatar
Gilbert Lee committed
1328
    totalBandwidth += transferBandwidthGbs;
Gilbert Lee's avatar
Gilbert Lee committed
1329
1330
1331
1332
1333
  }

  return totalBandwidth;
}

Gilbert Lee's avatar
Gilbert Lee committed
1334
void Transfer::PrepareBlockParams(EnvVars const& ev, size_t const N)
Gilbert Lee's avatar
Gilbert Lee committed
1335
1336
1337
1338
1339
1340
1341
{
  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
1342
  // Figure out the sub-array each block does for this Transfer
Gilbert Lee's avatar
Gilbert Lee committed
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
  // - 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
1363
  this->transferTime = 0.0;
Gilbert Lee's avatar
Gilbert Lee committed
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
}

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

gilbertlee-amd's avatar
gilbertlee-amd committed
1394
void RunSweepPreset(EnvVars const& ev, size_t const numBytesPerTransfer, int const numBlocksToUse, bool const isRandom)
Gilbert Lee's avatar
Gilbert Lee committed
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
{
  ev.DisplaySweepEnvVars();

  // Compute how many possible Transfers are permitted (unique SRC/EXE/DST triplets)
  std::vector<std::pair<MemType, int>> exeList;
  for (auto exe : ev.sweepExe)
  {
    MemType const exeMemType = CharToMemType(exe);
    if (IsGpuType(exeMemType))
    {
1405
1406
      for (int exeIndex = 0; exeIndex < ev.numGpuDevices; ++exeIndex)
        exeList.push_back(std::make_pair(exeMemType, exeIndex));
Gilbert Lee's avatar
Gilbert Lee committed
1407
1408
1409
    }
    else
    {
1410
1411
1412
1413
1414
1415
      for (int exeIndex = 0; exeIndex < ev.numCpuDevices; ++exeIndex)
      {
        // Skip NUMA nodes that have no CPUs (e.g. CXL)
        if (ev.numCpusPerNuma[exeIndex] == 0) continue;
        exeList.push_back(std::make_pair(exeMemType, exeIndex));
      }
Gilbert Lee's avatar
Gilbert Lee committed
1416
1417
    }
  }
1418
  int numExes = exeList.size();
Gilbert Lee's avatar
Gilbert Lee committed
1419
1420
1421
1422
1423
1424

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

Gilbert Lee's avatar
Gilbert Lee committed
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
    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();

1443
1444
  // Build array of possibilities, respecting any additional restrictions (e.g. XGMI hop count)
  struct TransferInfo
Gilbert Lee's avatar
Gilbert Lee committed
1445
  {
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    MemType srcMemType; int srcIndex;
    MemType exeMemType; int exeIndex;
    MemType dstMemType; int dstIndex;
  };

  // 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
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
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
    // Skip CPU executors if XGMI link must be used
    if (useXgmiOnly && !IsGpuType(exeList[i].first)) continue;
    tinfo.exeMemType = exeList[i].first;
    tinfo.exeIndex   = exeList[i].second;

    bool isXgmiSrc = false;
    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)
        {
          uint32_t exeToSrcLinkType, exeToSrcHopCount;
          HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(exeList[i].second, MEM_GPU),
                                                RemappedIndex(srcList[j].second, MEM_GPU),
                                                &exeToSrcLinkType,
                                                &exeToSrcHopCount));
          isXgmiSrc = (exeToSrcLinkType == HSA_AMD_LINK_INFO_TYPE_XGMI);
          if (isXgmiSrc) numHopsSrc = exeToSrcHopCount;
        }
        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;

      tinfo.srcMemType = srcList[j].first;
      tinfo.srcIndex   = srcList[j].second;

      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)
          {
            uint32_t exeToDstLinkType, exeToDstHopCount;
            HIP_CALL(hipExtGetLinkTypeAndHopCount(RemappedIndex(exeList[i].second, MEM_GPU),
                                                  RemappedIndex(dstList[k].second, MEM_GPU),
                                                  &exeToDstLinkType,
                                                  &exeToDstHopCount));
            isXgmiDst = (exeToDstLinkType == HSA_AMD_LINK_INFO_TYPE_XGMI);
            if (isXgmiDst) numHopsDst = exeToDstHopCount;
          }
          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;

        tinfo.dstMemType = dstList[k].first;
        tinfo.dstIndex   = dstList[k].second;

        possibleTransfers.push_back(tinfo);
      }
    }
Gilbert Lee's avatar
Gilbert Lee committed
1534
1535
  }

1536
1537
1538
  int const numPossible = (int)possibleTransfers.size();
  int maxParallelTransfers = (ev.sweepMax == 0 ? numPossible : ev.sweepMax);

Gilbert Lee's avatar
Gilbert Lee committed
1539
1540
1541
1542
1543
1544
  if (ev.sweepMin > numPossible)
  {
    printf("No valid test configurations exist\n");
    return;
  }

1545
1546
1547
1548
1549
1550
  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
1551
1552
  int numTestsRun = 0;
  int M = ev.sweepMin;
gilbertlee-amd's avatar
gilbertlee-amd committed
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
  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
1564
1565
1566
1567
1568
1569
1570
1571
1572
  // 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
1573
      M = distribution(*ev.generator);
Gilbert Lee's avatar
Gilbert Lee committed
1574
1575
1576
1577

      // Generate a random bitmask
      for (int i = 0; i < numPossible; i++)
        bitmask[i] = (i < M) ? 1 : 0;
1578
      std::shuffle(bitmask.begin(), bitmask.end(), *ev.generator);
Gilbert Lee's avatar
Gilbert Lee committed
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
    }

    // 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;
1589
1590
1591
1592
1593
1594
        transfer.srcMemType     = possibleTransfers[value].srcMemType;
        transfer.srcIndex       = possibleTransfers[value].srcIndex;
        transfer.exeMemType     = possibleTransfers[value].exeMemType;
        transfer.exeIndex       = possibleTransfers[value].exeIndex;
        transfer.dstMemType     = possibleTransfers[value].dstMemType;
        transfer.dstIndex       = possibleTransfers[value].dstIndex;
gilbertlee-amd's avatar
gilbertlee-amd committed
1595
        transfer.numBlocksToUse = IsGpuType(transfer.exeMemType) ? numBlocksToUse : ev.numCpuPerTransfer;
1596
        transfer.transferIndex  = transfers.size();
gilbertlee-amd's avatar
gilbertlee-amd committed
1597
        transfer.numBytes       = ev.sweepRandBytes ? randSize(*ev.generator) * sizeof(float) : 0;
Gilbert Lee's avatar
Gilbert Lee committed
1598
1599
1600
1601
        transfers.push_back(transfer);
      }
    }

gilbertlee-amd's avatar
gilbertlee-amd committed
1602
1603
    LogTransfers(fp, ++numTestsRun, transfers);
    ExecuteTransfers(ev, numTestsRun, numBytesPerTransfer / sizeof(float), transfers);
Gilbert Lee's avatar
Gilbert Lee committed
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634

    // 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
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
  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)",
            MemTypeStr[transfer.srcMemType], transfer.srcIndex,
            MemTypeStr[transfer.exeMemType], transfer.exeIndex,
            MemTypeStr[transfer.dstMemType], transfer.dstIndex,
            transfer.numBlocksToUse,
            transfer.numBytes);
  }
  fprintf(fp, "\n");
  fflush(fp);
Gilbert Lee's avatar
Gilbert Lee committed
1653
}