-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpu_profiler.cpp
More file actions
1748 lines (1548 loc) · 63.3 KB
/
gpu_profiler.cpp
File metadata and controls
1748 lines (1548 loc) · 63.3 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
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
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Work flow in brief:
*
* Subscribed for all the launch callbacks and required resource callbacks
* like module and context callbacks Context created callback: Enable PC
* sampling using cuptiPCSamplingEnable() CUPTI API. Configure PC sampling for
* that context in ConfigureActivity() function. ConfigureActivity(): Get count
* of all stall reasons supported on GPU using
* cuptiPCSamplingGetNumStallReasons() CUPTI API. Get all stall reasons names
* and its indexes using cuptiPCSamplingGetStallReasons() CUPTI API. Configure
* PC sampling with provide parameters and to sample all stall reasons using
* cuptiPCSamplingSetConfigurationAttribute() CUPTI API.
* queue of buffers into the file.
* Only for first context creation, allocate memory for circular
* buffers which will hold flushed data from cupti.
*
* Launch callbacks:
* If serialized mode is enabled then every time if cupti has PC
* records then flush all records using cuptiPCSamplingGetData() and push buffer
* in queue with context info to fill the rpc reply. If continuous mode is
* enabled then if cupti has more records than size of single circular buffer
* then flush records in one circular buffer using
* cuptiPCSamplingGetData() and push it in queue with context info to fill the
* rpc reply.
*
* Module load:
* This callback covers case when module get unloaded and new module
* get loaded then cupti flush all records into the provided buffer during
* configuration. So in this callback if provided buffer during configuration
* has any records then flush all records into the circular buffers and push
* them into the queue with context info to fill them into the rpc reply.
*
* Context destroy starting:
* Disable PC sampling using cuptiPCSamplingDisable() CUPTI API
*
* AtExitHandler
* If PC sampling is not disabled for any context then disable it using
* cuptiPCSamplingDisable(). Push PC sampling buffer in queue which provided
* during configuration with context info for each context as cupti flush all
* remaining PC records into this buffer in the end. Free allocated memory for
* circular buffer, stall reason names, stall reasons indexes and PC sampling
* buffers provided during configuration.
*
* RPC server:
* A RPC server is started once the libaray is loaded. The server is
* responsible for recieving the request to perform a PC sampling for a specific
* time interval with a <Duration> parameter indicated.
*/
#include "gpu_profiler.h"
namespace {
inline void PrintUNWValue(UNWValue &val) {
// TODO(yanli): buggy? gettid == pthread_self?
pid_t pid = gettid();
pthread_t tid = pthread_self();
DEBUG_LOG("[pid=%u, tid=%u] unwinding: pc=%lx:[%s+%lx]\n", (uint32_t)pid,
(uint32_t)tid, val.pc, val.funcName.c_str(), val.offset);
}
const char *PyObj2Str(PyObject *obj) {
return (const char *)PyBytes_AS_STRING(
PyUnicode_AsEncodedString(obj, "utf-8", "~E~"));
}
std::string GetPyLine(std::string pyFileName, int pyLineNumer) {
std::fstream inFile;
std::string lineStr;
inFile.open(pyFileName);
int i = 1;
while (std::getline(inFile, lineStr) && i < pyLineNumer)
++i;
inFile.close();
lineStr.erase(std::remove(lineStr.begin(), lineStr.end(), ' '),
lineStr.end());
return lineStr;
}
} // namespace
void pyBackTrace(std::queue<UNWValue> &pyFrameQueue) {
// DEBUG_LOG("[py back trace] entered\n");
PyInterpreterState *mainInterpState = PyInterpreterState_Main();
// PyThreadState* pyState = PyInterpreterState_ThreadHead(mainInterpState);
// //PyGILState_GetThisThreadState();
PyThreadState *pyState = PyGILState_GetThisThreadState();
PyFrameObject *frame = pyState->frame;
while (frame) {
PyObject *fileNameObj = frame->f_code->co_filename;
PyObject *funcNameObj = frame->f_code->co_name;
const char *fileNameStr = PyObj2Str(fileNameObj);
const char *funcNameStr = PyObj2Str(funcNameObj);
int lineNumber = PyFrame_GetLineNumber(frame);
std::string lineContent = GetPyLine(fileNameStr, lineNumber);
// DEBUG_LOG("[py back trace] fileName: %s, funcName:%s, lineNumber:%d,
// lineContent:%s\n", fileNameStr, funcNameStr, lineNumber,
// lineContent.c_str());
pyFrameQueue.push(UNWValue(fileNameStr,
std::string(funcNameStr) + "::" + lineContent,
lineNumber));
frame = frame->f_back;
}
}
void getRSP(uint64_t *rsp) {
__asm__ __volatile__("mov %%rsp, %0" : "=m"(*rsp)::"memory");
}
namespace {
void PrintCCTMap() {
for (auto itr : g_CPUCCTMap) {
itr.second->printTree();
}
}
/**
* @brief
*
* @param q
* @param verbose
* @return CallStackStatus
*/
CallStackStatus GenerateCallStacks(std::stack<UNWValue> &q,
bool verbose = false) {
#if DEBUG
Timer *genCallStackTimer = Timer::GetGlobalTimer("gen_call_stack");
genCallStackTimer->start();
#endif
CallStackStatus status;
// Get python stack traces.
std::queue<UNWValue> pyFrameQueue;
if (GetProfilerConf()->backEnd == "TORCH") {
pyBackTrace(pyFrameQueue);
}
if (pyFrameQueue.size()) {
status = CALL_STACK_HAS_PY;
} else {
status = CALL_STACK_NOT_HAS_PY;
}
unw_cursor_t cursor;
unw_context_t context;
unw_getcontext(&context);
unw_init_local(&cursor, &context);
while (unw_step(&cursor) > 0) {
unw_word_t offset, pc;
char fname[FUNC_NAME_LENGTH];
char *outer_name;
unw_get_reg(&cursor, UNW_REG_IP, &pc);
auto getProcTimer = Timer::GetGlobalTimer("unwinding_get_proc_name");
getProcTimer->start();
unw_get_proc_name(&cursor, fname, sizeof(fname), &offset);
getProcTimer->stop();
int status_demangle = 99;
if ((outer_name = abi::__cxa_demangle(fname, nullptr, nullptr,
&status_demangle)) == 0) {
outer_name = fname;
}
// skip cupti-related stack frames
if (HasExcludePatterns(outer_name))
continue;
if (GetProfilerConf()->backEnd == "TORCH" &&
std::string(outer_name).find("_PyEval_EvalFrameDefault") !=
std::string::npos) {
UNWValue value = pyFrameQueue.front();
value.pc = pc + value.offset; // use native pc plus offset as PyFrame pc
q.push(value);
pyFrameQueue.pop();
} else {
UNWValue value(pc, offset, std::string(outer_name));
q.push(value);
}
if (verbose) {
PrintUNWValue(q.top());
}
}
#if DEBUG
genCallStackTimer->stop();
#endif
return status;
}
#define TOP2(s1, s2, val) \
do { \
if (s1.size()) \
val = s1.top(); \
else \
val = s2.top(); \
} while (0)
#define POP2(s1, s2) \
do { \
if (s1.size()) \
s1.pop(); \
else \
s2.pop(); \
} while (0)
// TODO(lpc): Complicated function. Dont understand yet.
// Maintain a CPU CCT for each thread.
void DoBackTrace(bool verbose = false) {
pthread_t tid = pthread_self();
if (g_CPUCCTMap.find(tid) == g_CPUCCTMap.end()) {
// TODO(lpc): need to comm. with yan about the difference between gettid and
// tid here.
DEBUG_LOG("new CCT, tid=%d\n", gettid());
CPUCCT *newCCT = new CPUCCT();
// Set a virtual root node.
CPUCCTNode *vRootNode = new CPUCCTNode();
// TODO(lpc): can be improved with atomic.
g_CPUCCTNodeIdMutex.lock();
vRootNode->id = g_CPUCCTNodeId;
++g_CPUCCTNodeId;
g_CPUCCTNodeIdMutex.unlock();
vRootNode->funcName = "thread:" + std::to_string(gettid()) +
"::id:" + std::to_string(vRootNode->id);
vRootNode->pc = 0;
vRootNode->offset = 0;
vRootNode->nodeType = CCTNODE_TYPE_CXX;
newCCT->setRootNode(vRootNode);
g_CPUCCTMap.insert({tid, newCCT});
}
CPUCCT *cpuCCT = g_CPUCCTMap[tid];
// If GetProfilerConf()->fakeBT is true, do not perform cpu
// call stack unwinding.
if (GetProfilerConf()->fakeBT) {
g_activeCPUPCIDMutex.lock();
if (verbose) {
DEBUG_LOG("active PC changed to %lu:%p\n", cpuCCT->root->id,
(void *)(cpuCCT->root->pc));
}
g_activeCPUPCID = cpuCCT->root->id;
g_activeCPUPCIDMutex.unlock();
return;
}
// Optimization of cpu call stack unwinding: check the rsp register first.
uint64_t rsp;
getRSP(&rsp);
if (verbose)
DEBUG_LOG("rsp=%p\n", (void *)rsp);
if (GetProfilerConf()->checkRSP &&
g_esp2pcIdMap.find(rsp) != g_esp2pcIdMap.end()) {
uint64_t pcId = g_esp2pcIdMap[rsp];
g_activeCPUPCIDMutex.lock();
g_activeCPUPCID = pcId;
g_activeCPUPCIDMutex.unlock();
if (verbose)
DEBUG_LOG("already unwound, active pc id changed to %lu\n", pcId);
return;
}
// nodes to be inserted to the cpu calling context tree
std::stack<UNWValue> toInsertUNW;
std::stack<UNWValue> toInsertUNWMain;
auto status = GenerateCallStacks(toInsertUNW, verbose);
// TODO(lpc): don't understand this part yet.
// if the backend is Pytorch, and current thread has not PyFrame
// go to the main thread for PyFrame
if (GetProfilerConf()->doPyUnwinding && status == CALL_STACK_NOT_HAS_PY) {
DEBUG_LOG("this thread has not PyFrame, going to the main thread\n");
g_genCallStack = true;
pthread_kill(GetProfilerConf()->mainThreadTid, SIGUSR1);
while (g_genCallStack) {
}
toInsertUNWMain = g_callStack;
// TODO: clear the stack or not ?
while (!g_callStack.empty()) {
g_callStack.pop();
}
}
CPUCCTNode *parentNode = cpuCCT->root;
while (!toInsertUNW.empty()) {
UNWValue value;
TOP2(toInsertUNWMain, toInsertUNW, value);
CPUCCTNode *childNode = parentNode->getChildbyPC(value.pc);
// if finding a CXX node with _PyEval_EvalFrameDefault (C2P node)
// replace it with PY node
if (childNode) {
if (childNode->nodeType == CCTNODE_TYPE_C2P) {
if (value.nodeType == CCTNODE_TYPE_PY) {
childNode->nodeType = CCTNODE_TYPE_PY;
childNode->funcName = value.funcName;
DEBUG_LOG("py node renamed in unwinding: %s\n",
value.funcName.c_str());
} else {
DEBUG_LOG("wrong cct node type matching: %d/%d\n",
childNode->nodeType, value.nodeType);
}
}
parentNode = childNode;
POP2(toInsertUNWMain, toInsertUNW);
} else {
break;
}
}
// The call path has been searched before
if (toInsertUNW.empty()) {
g_activeCPUPCIDMutex.lock();
g_activeCPUPCID = parentNode->id;
if (verbose)
DEBUG_LOG("old pc, active pc changed to %lu:%p\n", parentNode->id,
(void *)(parentNode->pc));
g_activeCPUPCIDMutex.unlock();
}
// The call path has unsearched suffix
while (!toInsertUNW.empty()) {
UNWValue value;
TOP2(toInsertUNWMain, toInsertUNW, value);
CPUCCTNode *newNode = new CPUCCTNode(value.nodeType);
newNode->pc = value.pc;
newNode->offset = value.offset;
g_CPUCCTNodeIdMutex.lock();
newNode->id = g_CPUCCTNodeId;
++g_CPUCCTNodeId;
g_CPUCCTNodeIdMutex.unlock();
if (value.nodeType == CCTNODE_TYPE_CXX) {
newNode->funcName =
value.funcName; // + "_" + std::to_string(newNode->id);
} else {
// + "_" + std::to_string(newNode->id)
newNode->funcName = value.fileName + "::" + value.funcName + "_" +
std::to_string(value.offset);
}
// leaf node
if (toInsertUNW.size() == 1) {
g_activeCPUPCIDMutex.lock();
if (verbose)
DEBUG_LOG("active pc changed to %lu:%p\n", newNode->id,
(void *)(newNode->pc));
g_activeCPUPCID = newNode->id;
g_esp2pcIdMap[rsp] = newNode->id;
g_activeCPUPCIDMutex.unlock();
}
cpuCCT->insertNode(parentNode, newNode);
parentNode = newNode;
POP2(toInsertUNWMain, toInsertUNW);
}
}
void CopyCPUCCT2ProtoCPUCCT(CPUCCT *cct, CPUCallingContextTree *&tree) {
if (!cct->root)
return;
tree->set_rootid(cct->root->id);
tree->set_rootpc(cct->root->pc);
for (auto node : cct->nodeMap) {
CPUCallingContextNode protoNode;
protoNode.set_id(node.first);
protoNode.set_pc(node.second->pc);
protoNode.set_parentid(node.second->parentID);
protoNode.set_parentpc(node.second->parentPC);
protoNode.set_offset(node.second->offset);
protoNode.set_funcname(node.second->funcName);
for (auto id2child : node.second->id2ChildNodes) {
protoNode.add_childids(id2child.first);
}
for (auto pc2child : node.second->pc2ChildNodes) {
protoNode.add_childpcs(pc2child.first);
}
(*(tree->mutable_nodemap()))[node.second->id] = protoNode;
}
}
CriticalNodeType IsCriticalNode(CPUCCTNode *node) {
std::regex torchOPRegex("at::_ops::(\\S+)::call(\\S+)");
std::regex tfOPRegex("(\\S+)Op(Kernel)?.+::Compute");
// keep python nodes
if (node->nodeType == CCTNODE_TYPE_PY) {
if (node->funcName.find("python3") == std::string::npos) {
if (node->funcName.find("backward") != std::string::npos) {
DEBUG_LOG("critical node, kind=backward, funcName=%s, id=%lu\n",
node->funcName.c_str(), node->id);
return CRITICAL_TYPE_PY_BACKWARD;
}
if (node->funcName.find(GetProfilerConf()->pyFileName) !=
std::string::npos &&
node->funcName.find("loss") != std::string::npos) {
DEBUG_LOG("critical node, kind=loss, funcName=%s, id=%lu\n",
node->funcName.c_str(), node->id);
return CRITICAL_TYPE_PY_LOSS;
}
if (node->funcName.find("forward") != std::string::npos) {
DEBUG_LOG("critical node, kind=forward, funcName=%s, id=%lu\n",
node->funcName.c_str(), node->id);
return CRITICAL_TYPE_PY_FORWARD;
}
}
}
// Pytorch OP regex
std::smatch results;
if (std::regex_search(node->funcName, results, torchOPRegex)) {
DEBUG_LOG("critical node, kind=torch regex, funcName=%s, id=%lu\n",
node->funcName.c_str(), node->id);
return CRITICAL_TYPE_TORCH_OP;
}
// TF OP regex
if (std::regex_search(node->funcName, results, tfOPRegex)) {
DEBUG_LOG("critical node, kind=tf regex, funcName=%s, id=%lu\n",
node->funcName.c_str(), node->id);
return CRITICAL_TYPE_TF_OP;
}
// leaf node
if (node->childNodes.size() == 0) {
DEBUG_LOG("critical node, kind=leaf, funcName=%s, id=%lu\n",
node->funcName.c_str(), node->id);
return CRITICAL_TYPE_LEAF;
}
return NOT_CRITICAL_NODE;
}
void PruneTreeRecursively(CPUCCT *newTree, CPUCCT *oldTree,
uint64_t currNewNodeId, uint64_t currOldNodeId) {
auto currNewNode = newTree->nodeMap[currNewNodeId];
auto currOldNode = oldTree->nodeMap[currOldNodeId];
for (auto child : currOldNode->childNodes) {
if (IsCriticalNode(child) != NOT_CRITICAL_NODE) {
// for continus op calling, keep the first one/merge them?
if (currOldNode->childNodes.size() == 1 &&
IsCriticalNode(currNewNode) == CRITICAL_TYPE_TORCH_OP &&
IsCriticalNode(child) == CRITICAL_TYPE_TORCH_OP) {
currNewNode->funcName += ("::" + child->funcName.substr(10));
PruneTreeRecursively(newTree, oldTree, currNewNodeId, child->id);
} else {
CPUCCTNode *newChild = new CPUCCTNode();
CPUCCTNode::copyNodeWithoutRelation(child, newChild);
newTree->insertNode(currNewNode, newChild, true);
PruneTreeRecursively(newTree, oldTree, newChild->id, child->id);
}
} else {
PruneTreeRecursively(newTree, oldTree, currNewNodeId, child->id);
}
}
}
void PruneCPUCCT(CCTMAP_t &cctMap) {
DEBUG_LOG("pruning cpu cct\n");
for (auto itr : g_CPUCCTMap) {
auto key = itr.first;
CPUCCT *oldCCT = itr.second;
CPUCCT *newCCT = new CPUCCT();
cctMap.insert(std::make_pair(key, newCCT));
CPUCCTNode *oldRootNode = oldCCT->root;
CPUCCTNode *newRootNode = new CPUCCTNode();
CPUCCTNode::copyNodeWithoutRelation(oldRootNode, newRootNode);
newCCT->setRootNode(newRootNode);
PruneTreeRecursively(newCCT, oldCCT, newRootNode->id, oldRootNode->id);
}
}
void CopyCPUCCT2ProtoCPUCCTV2(GPUProfilingResponse *reply) {
CCTMAP_t PrunedCPUCCTMap;
if (GetProfilerConf()->pruneCCT)
PruneCPUCCT(PrunedCPUCCTMap);
else
PrunedCPUCCTMap = g_CPUCCTMap;
for (auto itr : PrunedCPUCCTMap) {
CPUCCT *cct = itr.second;
if (!cct->root)
return;
CPUCallingContextTree *tree = reply->add_cpucallingctxtree();
tree->set_rootid(cct->root->id);
tree->set_rootpc(cct->root->pc);
for (auto node : cct->nodeMap) {
CPUCallingContextNode protoNode;
protoNode.set_id(node.first);
protoNode.set_pc(node.second->pc);
protoNode.set_parentid(node.second->parentID);
protoNode.set_parentpc(node.second->parentPC);
protoNode.set_offset(node.second->offset);
protoNode.set_samples(node.second->samples);
protoNode.set_funcname(node.second->funcName);
for (auto id2child : node.second->id2ChildNodes) {
protoNode.add_childids(id2child.first);
}
for (auto pc2child : node.second->pc2ChildNodes) {
protoNode.add_childpcs(pc2child.first);
}
(*(tree->mutable_nodemap()))[node.second->id] = protoNode;
}
}
}
void StorePCSamplesParents(CUpti_PCSamplingData *pPcSamplingData) {
for (int i = 0; i < pPcSamplingData->totalNumPcs; ++i) {
CUpti_PCSamplingPCData *pPcData = &pPcSamplingData->pPcData[i];
g_GPUPCSamplesParentCPUPCIDs[pPcData] = g_activeCPUPCID;
}
}
void GetPcSamplingDataFromCupti(
CUpti_PCSamplingGetDataParams &pcSamplingGetDataParams,
ContextInfo *contextInfo) {
CUpti_PCSamplingData *pPcSamplingData = NULL;
// Time-consuming part.
g_circularBufferMutex.lock();
while (g_bufferEmptyTrackerArray[g_put]) {
g_buffersGetUtilisedFasterThanStore = true;
}
pcSamplingGetDataParams.pcSamplingData = (void *)&g_circularBuffer[g_put];
pPcSamplingData = &g_circularBuffer[g_put];
g_bufferEmptyTrackerArray[g_put] = true;
g_put = (g_put + 1) % GetProfilerConf()->circularbufCount;
g_circularBufferMutex.unlock();
CUPTI_CALL(cuptiPCSamplingGetData(&pcSamplingGetDataParams));
g_pcSampDataQueueMutex.lock();
g_pcSampDataQueue.push(std::make_pair(pPcSamplingData, contextInfo));
StorePCSamplesParents(pPcSamplingData);
g_pcSampDataQueueMutex.unlock();
}
void CollectPCSamples() {
for (auto &itr : g_contextInfoMap) {
DEBUG_LOG("Collecting remaining CUDA PC samples in context %u\n",
itr.second->contextUid);
CUpti_PCSamplingGetDataParams pcSamplingGetDataParams = {};
pcSamplingGetDataParams.size = CUpti_PCSamplingGetDataParamsSize;
pcSamplingGetDataParams.ctx = itr.first;
while (itr.second->pcSamplingData.remainingNumPcs > 0 ||
itr.second->pcSamplingData.totalNumPcs > 0) {
DEBUG_LOG("remainingNumPcs=%lu, totoalNumPcs=%lu\n",
itr.second->pcSamplingData.remainingNumPcs,
itr.second->pcSamplingData.totalNumPcs);
GetPcSamplingDataFromCupti(pcSamplingGetDataParams, itr.second);
}
if (itr.second->pcSamplingData.totalNumPcs > 0) {
g_pcSampDataQueueMutex.lock();
// It is quite possible that after pc sampling disabled cupti fill
// remaining records collected lately from hardware in provided buffer
// during configuration.
g_pcSampDataQueue.push(
std::make_pair(&itr.second->pcSamplingData, itr.second));
g_pcSampDataQueueMutex.unlock();
}
}
DEBUG_LOG("Collecting remaining CUDA PC samples for all contexts done.\n");
}
void PreallocateBuffersForRecords() {
for (size_t buffers = 0; buffers < GetProfilerConf()->circularbufCount;
buffers++) {
g_circularBuffer[buffers].size = sizeof(CUpti_PCSamplingData);
g_circularBuffer[buffers].collectNumPcs =
GetProfilerConf()->circularbufSize;
g_circularBuffer[buffers].pPcData = (CUpti_PCSamplingPCData *)malloc(
g_circularBuffer[buffers].collectNumPcs *
sizeof(CUpti_PCSamplingPCData));
MEMORY_ALLOCATION_CALL(g_circularBuffer[buffers].pPcData);
for (size_t i = 0; i < g_circularBuffer[buffers].collectNumPcs; i++) {
g_circularBuffer[buffers].pPcData[i].stallReason =
(CUpti_PCSamplingStallReason *)malloc(
stallReasonsCount * sizeof(CUpti_PCSamplingStallReason));
MEMORY_ALLOCATION_CALL(g_circularBuffer[buffers].pPcData[i].stallReason);
}
}
}
void FreePreallocatedMemory() {
for (size_t buffers = 0; buffers < GetProfilerConf()->circularbufCount;
buffers++) {
for (size_t i = 0; i < g_circularBuffer[buffers].collectNumPcs; i++) {
free(g_circularBuffer[buffers].pPcData[i].stallReason);
}
free(g_circularBuffer[buffers].pPcData);
}
for (auto &itr : g_contextInfoMap) {
// free PC sampling buffer
for (uint32_t i = 0; i < GetProfilerConf()->pcConfigBufRecordCount; i++) {
free(itr.second->pcSamplingData.pPcData[i].stallReason);
}
free(itr.second->pcSamplingData.pPcData);
for (size_t i = 0; i < itr.second->pcSamplingStallReasons.numStallReasons;
i++) {
free(itr.second->pcSamplingStallReasons.stallReasons[i]);
}
free(itr.second->pcSamplingStallReasons.stallReasons);
free(itr.second->pcSamplingStallReasons.stallReasonIndex);
free(itr.second);
}
for (auto &itr : g_contextInfoToFreeInEndVector) {
// free PC sampling buffer
for (uint32_t i = 0; i < GetProfilerConf()->pcConfigBufRecordCount; i++) {
free(itr->pcSamplingData.pPcData[i].stallReason);
}
free(itr->pcSamplingData.pPcData);
for (size_t i = 0; i < itr->pcSamplingStallReasons.numStallReasons; i++) {
free(itr->pcSamplingStallReasons.stallReasons[i]);
}
free(itr->pcSamplingStallReasons.stallReasons);
free(itr->pcSamplingStallReasons.stallReasonIndex);
free(itr);
}
}
} // namespace
// TODO(lpc): this function is too big.
// This function seems buggys or should be simpler.
void ConfigureActivity(CUcontext cuCtx) {
auto contextStateMapItr = g_contextInfoMap.find(cuCtx);
if (contextStateMapItr == g_contextInfoMap.end()) {
std::cout << "Error : No ctx found" << std::endl;
exit(-1);
}
// Get the number of supported counters and counter names.
size_t numStallReasons = 0;
CUpti_PCSamplingGetNumStallReasonsParams numStallReasonsParams = {};
numStallReasonsParams.size = CUpti_PCSamplingGetNumStallReasonsParamsSize;
numStallReasonsParams.ctx = cuCtx;
numStallReasonsParams.numStallReasons = &numStallReasons;
// TODO(lpc): re-inspect this lock.
g_stallReasonsCountMutex.lock();
CUPTI_CALL(cuptiPCSamplingGetNumStallReasons(&numStallReasonsParams));
if (!g_collectedStallReasonsCount) {
stallReasonsCount = numStallReasons;
g_collectedStallReasonsCount = true;
}
g_stallReasonsCountMutex.unlock();
char **pStallReasons = (char **)malloc(numStallReasons * sizeof(char *));
MEMORY_ALLOCATION_CALL(pStallReasons);
for (size_t i = 0; i < numStallReasons; i++) {
pStallReasons[i] =
(char *)malloc(CUPTI_STALL_REASON_STRING_SIZE * sizeof(char));
MEMORY_ALLOCATION_CALL(pStallReasons[i]);
}
uint32_t *pStallReasonIndex =
(uint32_t *)malloc(numStallReasons * sizeof(uint32_t));
MEMORY_ALLOCATION_CALL(pStallReasonIndex);
CUpti_PCSamplingGetStallReasonsParams stallReasonsParams = {};
stallReasonsParams.size = CUpti_PCSamplingGetStallReasonsParamsSize;
stallReasonsParams.ctx = cuCtx;
stallReasonsParams.numStallReasons = numStallReasons;
stallReasonsParams.stallReasonIndex = pStallReasonIndex;
stallReasonsParams.stallReasons = pStallReasons;
CUPTI_CALL(cuptiPCSamplingGetStallReasons(&stallReasonsParams));
// User buffer to hold collected PC Sampling data in PC-To-Counter format
size_t pcSamplingDataSize = sizeof(CUpti_PCSamplingData);
contextStateMapItr->second->pcSamplingData.size = pcSamplingDataSize;
contextStateMapItr->second->pcSamplingData.collectNumPcs =
GetProfilerConf()->pcConfigBufRecordCount;
contextStateMapItr->second->pcSamplingData.pPcData =
(CUpti_PCSamplingPCData *)malloc(
GetProfilerConf()->pcConfigBufRecordCount *
sizeof(CUpti_PCSamplingPCData));
MEMORY_ALLOCATION_CALL(contextStateMapItr->second->pcSamplingData.pPcData);
for (uint32_t i = 0; i < GetProfilerConf()->pcConfigBufRecordCount; i++) {
contextStateMapItr->second->pcSamplingData.pPcData[i].stallReason =
(CUpti_PCSamplingStallReason *)malloc(
numStallReasons * sizeof(CUpti_PCSamplingStallReason));
MEMORY_ALLOCATION_CALL(
contextStateMapItr->second->pcSamplingData.pPcData[i].stallReason);
}
std::vector<CUpti_PCSamplingConfigurationInfo> pcSamplingConfigurationInfo;
CUpti_PCSamplingConfigurationInfo sampPeriodConfig = {};
sampPeriodConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_SAMPLING_PERIOD;
if (GetProfilerConf()->samplingPeriod) {
sampPeriodConfig.attributeData.samplingPeriodData.samplingPeriod =
GetProfilerConf()->samplingPeriod;
pcSamplingConfigurationInfo.push_back(sampPeriodConfig);
}
CUpti_PCSamplingConfigurationInfo scratchBufferSizeConfig = {};
scratchBufferSizeConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_SCRATCH_BUFFER_SIZE;
if (GetProfilerConf()->scratchBufSize) {
scratchBufferSizeConfig.attributeData.scratchBufferSizeData
.scratchBufferSize = GetProfilerConf()->scratchBufSize;
pcSamplingConfigurationInfo.push_back(scratchBufferSizeConfig);
}
CUpti_PCSamplingConfigurationInfo hwBufferSizeConfig = {};
hwBufferSizeConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_HARDWARE_BUFFER_SIZE;
if (GetProfilerConf()->hwBufSize) {
hwBufferSizeConfig.attributeData.hardwareBufferSizeData.hardwareBufferSize =
GetProfilerConf()->hwBufSize;
pcSamplingConfigurationInfo.push_back(hwBufferSizeConfig);
}
CUpti_PCSamplingConfigurationInfo collectionModeConfig = {};
collectionModeConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_COLLECTION_MODE;
collectionModeConfig.attributeData.collectionModeData.collectionMode =
g_pcSamplingCollectionMode;
pcSamplingConfigurationInfo.push_back(collectionModeConfig);
CUpti_PCSamplingConfigurationInfo stallReasonConfig = {};
stallReasonConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_STALL_REASON;
stallReasonConfig.attributeData.stallReasonData.stallReasonCount =
numStallReasons;
stallReasonConfig.attributeData.stallReasonData.pStallReasonIndex =
pStallReasonIndex;
pcSamplingConfigurationInfo.push_back(stallReasonConfig);
// set a buffer for each cu context to hold pc samples from cupti
CUpti_PCSamplingConfigurationInfo samplingDataBufferConfig = {};
samplingDataBufferConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_SAMPLING_DATA_BUFFER;
samplingDataBufferConfig.attributeData.samplingDataBufferData
.samplingDataBuffer = (void *)&contextStateMapItr->second->pcSamplingData;
pcSamplingConfigurationInfo.push_back(samplingDataBufferConfig);
CUpti_PCSamplingConfigurationInfo enableStartStopConfig = {};
enableStartStopConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_ENABLE_START_STOP_CONTROL;
uint32_t enableStartStopControl =
GetProfilerConf()->noRPC && !GetProfilerConf()->noSampling ? 0 : 1;
enableStartStopConfig.attributeData.enableStartStopControlData
.enableStartStopControl = enableStartStopControl;
pcSamplingConfigurationInfo.push_back(enableStartStopConfig);
CUpti_PCSamplingConfigurationInfoParams pcSamplingConfigurationInfoParams =
{};
pcSamplingConfigurationInfoParams.size =
CUpti_PCSamplingConfigurationInfoParamsSize;
pcSamplingConfigurationInfoParams.pPriv = NULL;
pcSamplingConfigurationInfoParams.ctx = cuCtx;
pcSamplingConfigurationInfoParams.numAttributes =
pcSamplingConfigurationInfo.size();
pcSamplingConfigurationInfoParams.pPCSamplingConfigurationInfo =
pcSamplingConfigurationInfo.data();
CUPTI_CALL(cuptiPCSamplingSetConfigurationAttribute(
&pcSamplingConfigurationInfoParams));
// Store all stall reasons info in context info to dump into the file.
contextStateMapItr->second->pcSamplingStallReasons.numStallReasons =
numStallReasons;
contextStateMapItr->second->pcSamplingStallReasons.stallReasons =
pStallReasons;
contextStateMapItr->second->pcSamplingStallReasons.stallReasonIndex =
pStallReasonIndex;
// Find configuration info and store it in context info to dump in file.
// TODO(lpc): comment out below, as they are defined above. Need to test
// correctness.
scratchBufferSizeConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_SCRATCH_BUFFER_SIZE;
hwBufferSizeConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_HARDWARE_BUFFER_SIZE;
enableStartStopConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_ENABLE_START_STOP_CONTROL;
CUpti_PCSamplingConfigurationInfo outputDataFormatConfig = {};
outputDataFormatConfig.attributeType =
CUPTI_PC_SAMPLING_CONFIGURATION_ATTR_TYPE_OUTPUT_DATA_FORMAT;
outputDataFormatConfig.attributeData.outputDataFormatData.outputDataFormat =
CUPTI_PC_SAMPLING_OUTPUT_DATA_FORMAT_PARSED;
// TODO(lpc): don't understand the following.
std::vector<CUpti_PCSamplingConfigurationInfo>
pcSamplingRetrieveConfigurationInfo;
pcSamplingRetrieveConfigurationInfo.push_back(collectionModeConfig);
pcSamplingRetrieveConfigurationInfo.push_back(sampPeriodConfig);
pcSamplingRetrieveConfigurationInfo.push_back(scratchBufferSizeConfig);
pcSamplingRetrieveConfigurationInfo.push_back(hwBufferSizeConfig);
pcSamplingRetrieveConfigurationInfo.push_back(enableStartStopConfig);
CUpti_PCSamplingConfigurationInfoParams getPcSamplingConfigurationInfoParams =
{};
getPcSamplingConfigurationInfoParams.size =
CUpti_PCSamplingConfigurationInfoParamsSize;
getPcSamplingConfigurationInfoParams.pPriv = NULL;
getPcSamplingConfigurationInfoParams.ctx = cuCtx;
getPcSamplingConfigurationInfoParams.numAttributes =
pcSamplingRetrieveConfigurationInfo.size();
getPcSamplingConfigurationInfoParams.pPCSamplingConfigurationInfo =
pcSamplingRetrieveConfigurationInfo.data();
CUPTI_CALL(cuptiPCSamplingGetConfigurationAttribute(
&getPcSamplingConfigurationInfoParams));
for (size_t i = 0; i < getPcSamplingConfigurationInfoParams.numAttributes;
i++) {
contextStateMapItr->second->pcSamplingConfigurationInfo.push_back(
getPcSamplingConfigurationInfoParams.pPCSamplingConfigurationInfo[i]);
}
contextStateMapItr->second->pcSamplingConfigurationInfo.push_back(
outputDataFormatConfig);
contextStateMapItr->second->pcSamplingConfigurationInfo.push_back(
stallReasonConfig);
}
namespace {
void RPCCopyTracingData(GPUProfilingResponse *reply) {
DEBUG_LOG("RPC copy started [tracing]\n");
gpuprofiling::CUptiPCSamplingData *pcSampDataProto =
reply->add_pcsamplingdata();
pcSampDataProto->set_size(sizeof(CUpti_PCSamplingData));
pcSampDataProto->set_collectnumpcs(g_tracingRecords.size());
pcSampDataProto->set_totalsamples(g_tracingRecords.size());
pcSampDataProto->set_droppedsamples(0);
pcSampDataProto->set_totalnumpcs(g_tracingRecords.size());
pcSampDataProto->set_remainingnumpcs(0);
pcSampDataProto->set_rangeid(0);
pcSampDataProto->set_nonusrkernelstotalsamples(0);
for (auto itr : g_tracingRecords) {
std::string key = itr.first;
size_t pos = key.find("::");
if (pos == std::string::npos) {
DEBUG_LOG("bad format: %s\n", key.c_str());
continue;
}
uint64_t parentCPUPCID = std::stoul(key.substr(0, pos));
// std::string funcName = key.substr(pos + 2);
auto tRecord = itr.second;
auto pcDataProto = pcSampDataProto->add_ppcdata();
pcDataProto->set_size(sizeof(CUpti_PCSamplingPCData));
pcDataProto->set_functionname(tRecord->funcName);
pcDataProto->set_cubincrc(0);
pcDataProto->set_parentcpupcid(parentCPUPCID);
pcDataProto->set_cubincrc(0);
pcDataProto->set_pcoffset(0);
pcDataProto->set_functionindex(0);
pcDataProto->set_pad(0);
pcDataProto->set_stallreasoncount(1);
auto stallResProto = pcDataProto->add_stallreason();
stallResProto->set_pcsamplingstallreasonindex(28);
uint64_t duration =
tRecord->duration; //(uint64_t)(tRecord->duration * 100000000);
stallResProto->set_samples(duration);
// DEBUG_LOG("[in tracing copy] fn: %s, duration: %lu\n",
// tRecord->funcName.c_str(), duration);
}
}
void RPCCopyPCSamplingData(GPUProfilingResponse *reply) {
bool to_break = false;
DEBUG_LOG("rpc copy thread created [sampling]\n");
while (true) {
if (!g_pcSamplingStarted) {
DEBUG_LOG("pc sampling stopped, rpc copy about to quit\n");
to_break = true;
}
g_pcSampDataQueueMutex.lock();
while (!g_pcSampDataQueue.empty()) {
CUpti_PCSamplingData *pcSampData = g_pcSampDataQueue.front().first;
gpuprofiling::CUptiPCSamplingData *pcSampDataProto =
reply->add_pcsamplingdata();
pcSampDataProto->set_size(pcSampData->size);
pcSampDataProto->set_collectnumpcs(pcSampData->collectNumPcs);
pcSampDataProto->set_totalsamples(pcSampData->totalSamples);
pcSampDataProto->set_droppedsamples(pcSampData->droppedSamples);
pcSampDataProto->set_totalnumpcs(pcSampData->totalNumPcs);
pcSampDataProto->set_remainingnumpcs(pcSampData->remainingNumPcs);
pcSampDataProto->set_rangeid(pcSampData->rangeId);
// pcSampDataProto->set_nonusrkernelstotalsamples(pcSampData->nonUsrKernelsTotalSamples);
pcSampDataProto->set_nonusrkernelstotalsamples(0);
for (int i = 0; i < pcSampData->totalNumPcs; ++i) {
gpuprofiling::CUptiPCSamplingPCData *pcDataProto =
pcSampDataProto->add_ppcdata();
CUpti_PCSamplingPCData *pcData = &pcSampData->pPcData[i];
pcDataProto->set_size(pcData->size);
pcDataProto->set_cubincrc(pcData->cubinCrc);
pcDataProto->set_pcoffset(pcData->pcOffset);
pcDataProto->set_functionindex(pcData->functionIndex);
pcDataProto->set_pad(pcData->pad);
pcDataProto->set_functionname(std::string(pcData->functionName));
pcDataProto->set_stallreasoncount(pcData->stallReasonCount);
pcDataProto->set_parentcpupcid(g_GPUPCSamplesParentCPUPCIDs[pcData]);
for (int j = 0; j < pcData->stallReasonCount; ++j) {
gpuprofiling::PCSamplingStallReason *stallResProto =
pcDataProto->add_stallreason();
CUpti_PCSamplingStallReason stallRes = pcData->stallReason[j];
stallResProto->set_pcsamplingstallreasonindex(
stallRes.pcSamplingStallReasonIndex);
stallResProto->set_samples(stallRes.samples);
}
}
g_pcSampDataQueue.pop();
g_bufferEmptyTrackerArray[g_get] = false;
g_get = (g_get + 1) % GetProfilerConf()->circularbufCount;
}
g_pcSampDataQueueMutex.unlock();
if (to_break)
break;
}
}
inline bool checkSyncMap() {
for (auto ts : g_kernelThreadSyncedMap) {
if (!ts.second)
return false;
}
return true;
}
} // namespace
void AtExitHandler() {
// Check for any error occured while PC sampling.
CUPTI_CALL(cuptiGetLastError());
if (GetProfilerConf()->noRPC) {
g_pcSamplingStarted = false;
g_tracingStarted = false;
}
if (g_pcSamplingStarted) {
DEBUG_LOG("waiting for pc sampling stopping\n");
while (g_pcSamplingStarted) {
}
}
DEBUG_LOG("profiling stopped\n");
if (!GetProfilerConf()->noSampling) {
for (auto &itr : g_contextInfoMap) {
// disable pc sampling at exit
CUpti_PCSamplingDisableParams pcSamplingDisableParams = {};
pcSamplingDisableParams.size = CUpti_PCSamplingDisableParamsSize;
pcSamplingDisableParams.ctx = itr.first;
CUPTI_CALL(cuptiPCSamplingDisable(&pcSamplingDisableParams));
DEBUG_LOG("pc sampling disabled for context %u\n",
itr.second->contextUid);
}
}
if (g_buffersGetUtilisedFasterThanStore) {
std::cout
<< "WARNING : Buffers get used faster than get stored in "
"file. Suggestion is either increase size of buffer or increase "
"number of buffers"
<< std::endl;
}
if (GetProfilerConf()->noRPC) {
if (GetProfilerConf()->enableCPUSampling) {
g_cpuSamplerCollection->DisableSampling();
if (g_cpuSamplerThreadHandle.joinable()) {
g_cpuSamplerThreadHandle.join();
}
}
if (g_rpcReplyCopyThreadHandle.joinable()) {
g_rpcReplyCopyThreadHandle.join();
}