You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

gpu_profiling.cc 30 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /**
  2. * Copyright 2020-2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "profiler/device/gpu/gpu_profiling.h"
  17. #include <time.h>
  18. #include <cxxabi.h>
  19. #include <chrono>
  20. #include <cmath>
  21. #include "profiler/device/gpu/cupti_interface.h"
  22. #include "profiler/device/gpu/gpu_data_saver.h"
  23. #include "pybind_api/api_register.h"
  24. #include "utils/log_adapter.h"
  25. #include "utils/utils.h"
  26. namespace mindspore {
  27. namespace profiler {
  28. namespace gpu {
  29. #define BUF_SIZE (32 * 1024)
  30. #define ALIGN_SIZE (8)
  31. #define CHECK_CUPTI_RET_WITH_ERROR(expression, message) \
  32. if (expression != CUPTI_SUCCESS) { \
  33. const char *errstr; \
  34. CuptiGetResultString(expression, &errstr); \
  35. MS_LOG(ERROR) << "CUPTI Error:" << errstr << " function:" << message; \
  36. }
  37. #define CHECK_CUPTI_RET_WITH_EXCEPT(expression, message) \
  38. if (expression != CUPTI_SUCCESS) { \
  39. const char *errstr; \
  40. CuptiGetResultString(expression, &errstr); \
  41. MS_LOG(EXCEPTION) << "CUPTI Error:" << errstr << " function:" << message; \
  42. }
  43. #define CHECK_CUDA_RET_WITH_ERROR(expression, message) \
  44. { \
  45. cudaError_t status = (expression); \
  46. if (status != cudaSuccess) { \
  47. MS_LOG(ERROR) << "CUDA Error: " << message << " | Error Number: " << status << " " \
  48. << cudaGetErrorString(status); \
  49. } \
  50. }
  51. #define PROFILER_ERROR_IF_NULLPTR(ptr) \
  52. do { \
  53. if ((ptr) == nullptr) { \
  54. MS_LOG(ERROR) << ": The pointer[" << #ptr << "] is null."; \
  55. return; \
  56. } \
  57. } while (0)
  58. std::shared_ptr<GPUProfiler> GPUProfiler::profiler_inst_ = nullptr;
  59. int32_t GetThreadID() {
  60. uint32_t thread_id = static_cast<uint32_t>(pthread_self());
  61. return thread_id;
  62. }
  63. uint32_t GetStreamID(const CUcontext context, const void *stream) {
  64. uint32_t stream_id = 0;
  65. if (stream != nullptr) {
  66. CHECK_CUPTI_RET_WITH_ERROR(CuptiGetStreamId(context, (CUstream)stream, &stream_id), "CuptiGetStreamId");
  67. if (CuptiGetStreamId(context, (CUstream)stream, &stream_id) != CUPTI_SUCCESS) {
  68. MS_LOG(ERROR) << "Training process unexpectedly stopped, profiling data cannot be write to file"
  69. << "To obtain the profiling data, do not interrupt the training process.";
  70. }
  71. }
  72. return stream_id;
  73. }
  74. uint64_t GetCUPTITimeStamp() {
  75. uint64_t time_stamp = 0l;
  76. CHECK_CUPTI_RET_WITH_ERROR(CuptiGetTimestamp(&time_stamp), "CuptiGetTimestamp");
  77. return time_stamp;
  78. }
  79. uint64_t GetHostTimeStamp() {
  80. auto cur_sys_clock = std::chrono::system_clock::now();
  81. uint64_t cur_time_stamp =
  82. std::chrono::duration_cast<std::chrono::nanoseconds>(cur_sys_clock.time_since_epoch()).count();
  83. return cur_time_stamp;
  84. }
  85. std::string GetKernelFunc(const char *name) {
  86. char *demangledName = abi::__cxa_demangle(name, nullptr, nullptr, nullptr);
  87. if (demangledName != nullptr) {
  88. return demangledName;
  89. } else {
  90. return name;
  91. }
  92. }
  93. bool IsMemcpyAsyncEvent(CUpti_CallbackId cb_id) {
  94. switch (cb_id) {
  95. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyAsync:
  96. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyHtoDAsync_v2:
  97. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyDtoHAsync_v2:
  98. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyDtoDAsync_v2:
  99. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyAtoHAsync_v2:
  100. case CUPTI_DRIVER_TRACE_CBID_cuMemcpy2DAsync_v2:
  101. case CUPTI_DRIVER_TRACE_CBID_cuMemcpy3DAsync_v2:
  102. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyHtoAAsync_v2:
  103. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyPeerAsync:
  104. return true;
  105. }
  106. return false;
  107. }
  108. bool IsMemcpySyncEvent(CUpti_CallbackId cb_id) {
  109. switch (cb_id) {
  110. case CUPTI_DRIVER_TRACE_CBID_cuMemcpy:
  111. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyHtoD_v2:
  112. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyDtoH_v2:
  113. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyDtoD_v2:
  114. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyAtoH_v2:
  115. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyAtoD_v2:
  116. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyDtoA_v2:
  117. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyAtoA_v2:
  118. case CUPTI_DRIVER_TRACE_CBID_cuMemcpy2D_v2:
  119. case CUPTI_DRIVER_TRACE_CBID_cuMemcpy2DUnaligned_v2:
  120. case CUPTI_DRIVER_TRACE_CBID_cuMemcpy3D_v2:
  121. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyHtoA_v2:
  122. case CUPTI_DRIVER_TRACE_CBID_cuMemcpyPeer:
  123. return true;
  124. }
  125. return false;
  126. }
  127. void CUPTIApiExit(const std::shared_ptr<GPUProfiler> &gpu_profiler_inst, CUpti_CallbackId cb_id,
  128. const CUpti_CallbackData *cb_data) {
  129. uint64_t start_timestamp = *cb_data->correlationData;
  130. uint64_t end_timestamp = GetCUPTITimeStamp();
  131. switch (cb_id) {
  132. case CUPTI_DRIVER_TRACE_CBID_cuLaunchKernel:
  133. case CUPTI_DRIVER_TRACE_CBID_cuLaunchCooperativeKernel:
  134. case CUPTI_DRIVER_TRACE_CBID_cuLaunchCooperativeKernelMultiDevice:
  135. gpu_profiler_inst->EventHandleProcess(cb_id, cb_data, "cuLaunchKernel", start_timestamp, end_timestamp);
  136. break;
  137. case CUPTI_DRIVER_TRACE_CBID_cuMemAlloc:
  138. case CUPTI_DRIVER_TRACE_CBID_cuMemAlloc_v2:
  139. gpu_profiler_inst->EventHandleProcess(cb_id, cb_data, "cuMemAlloc", start_timestamp, end_timestamp);
  140. break;
  141. case CUPTI_DRIVER_TRACE_CBID_cuEventCreate:
  142. case CUPTI_DRIVER_TRACE_CBID_cuEventDestroy_v2:
  143. case CUPTI_DRIVER_TRACE_CBID_cuEventRecord:
  144. case CUPTI_DRIVER_TRACE_CBID_cuEventSynchronize:
  145. case CUPTI_DRIVER_TRACE_CBID_cuEventElapsedTime:
  146. // In some cases, the callback of cuctxsetcurrent is only exist
  147. // without entry, so this callback is ignored
  148. case CUPTI_DRIVER_TRACE_CBID_cuCtxSetCurrent:
  149. break;
  150. default:
  151. gpu_profiler_inst->EventHandleProcess(cb_id, cb_data, "others_api", start_timestamp, end_timestamp);
  152. break;
  153. }
  154. if (IsMemcpyAsyncEvent(cb_id) || IsMemcpySyncEvent(cb_id)) {
  155. gpu_profiler_inst->EventHandleProcess(cb_id, cb_data, "cuMemcpy", start_timestamp, end_timestamp);
  156. }
  157. }
  158. void CUPTICallBackFunc(void *user_data, CUpti_CallbackDomain domain, CUpti_CallbackId cb_id,
  159. const CUpti_CallbackData *cb_data) {
  160. if (domain != CUPTI_CB_DOMAIN_DRIVER_API) {
  161. return;
  162. }
  163. auto gpu_profiler_inst = GPUProfiler::GetInstance();
  164. PROFILER_ERROR_IF_NULLPTR(gpu_profiler_inst);
  165. if (!gpu_profiler_inst->GetEnableFlag()) {
  166. return;
  167. }
  168. PROFILER_ERROR_IF_NULLPTR(cb_data);
  169. if (cb_data->context == nullptr) {
  170. MS_LOG(DEBUG) << "Callback data context is null , correlation Id:" << cb_data->correlationId
  171. << " callback id:" << cb_id;
  172. return;
  173. }
  174. if (cb_data->callbackSite == CUPTI_API_ENTER) {
  175. *cb_data->correlationData = GetCUPTITimeStamp();
  176. } else if (cb_data->callbackSite == CUPTI_API_EXIT) {
  177. CUPTIApiExit(gpu_profiler_inst, cb_id, cb_data);
  178. }
  179. }
  180. std::string GetKernelFuncName(std::string kernel_name) {
  181. // remove the return type name (void) in kernel_name.
  182. std::string search_pattern("void ");
  183. auto func_name_begin_iter = kernel_name.find(search_pattern);
  184. if (func_name_begin_iter == kernel_name.npos) {
  185. func_name_begin_iter = 0;
  186. } else {
  187. func_name_begin_iter += search_pattern.length();
  188. }
  189. return kernel_name.substr(func_name_begin_iter);
  190. }
  191. std::shared_ptr<GPUProfiler> GPUProfiler::GetInstance() {
  192. if (profiler_inst_ == nullptr) {
  193. profiler_inst_ = std::shared_ptr<GPUProfiler>(new (std::nothrow) GPUProfiler());
  194. }
  195. return profiler_inst_;
  196. }
  197. void GPUProfiler::SyncEnable(const bool enable_flag) {
  198. MS_LOG(INFO) << "GPU Profiler synchronous enable flag:" << enable_flag;
  199. sync_enable_flag_ = enable_flag;
  200. }
  201. void GPUProfiler::StepProfilingEnable(const bool enable_flag) {
  202. MS_LOG(INFO) << "GPU Profiler enable flag:" << enable_flag;
  203. CHECK_CUPTI_RET_WITH_ERROR(CuptiActivityFlushAll(0), "CuptiActivityFlushAll");
  204. enable_flag_ = enable_flag;
  205. }
  206. void GPUProfiler::FixOpNameByCorrelationId(Event *event) {
  207. PROFILER_ERROR_IF_NULLPTR(event);
  208. if (event->api_type != CUPTIApiType::kActivity) {
  209. return;
  210. }
  211. auto iter = op_name_map_.find(event->correlation_id);
  212. if (iter != op_name_map_.end()) {
  213. event->op_name = std::move(iter->second);
  214. }
  215. }
  216. void GPUProfiler::AddEvent(Event &&event) {
  217. // protect callback concurrency for driver api and activity
  218. std::unique_lock<std::mutex> lock(event_mutex_);
  219. switch (event.api_type) {
  220. case CUPTIApiType::kCallback: {
  221. if (cupti_callback_events_count_ < max_cupti_callback_events_) {
  222. events_.emplace_back(std::move(event));
  223. cupti_callback_events_count_++;
  224. } else {
  225. cupti_callback_events_drop_count_++;
  226. }
  227. break;
  228. }
  229. case CUPTIApiType::kActivity: {
  230. if (cupti_activity_events_count_ < max_cupti_activity_events_) {
  231. events_.emplace_back(std::move(event));
  232. cupti_activity_events_count_++;
  233. } else {
  234. cupti_activity_events_drop_count_++;
  235. }
  236. break;
  237. }
  238. default:
  239. break;
  240. }
  241. }
  242. void GPUProfiler::EventLog(const Event &event) {
  243. MS_LOG(DEBUG) << "GPUProfiler"
  244. << ",\"kernel_name:" << event.kernel_name << "\",kernel_type:" << event.kernel_type
  245. << ",api_type:" << static_cast<int>(event.api_type) << ",start_time_stamp:" << event.start_time_stamp
  246. << ",end_time_stamp:" << event.end_time_stamp << ",cost:,"
  247. << (event.end_time_stamp - event.start_time_stamp) / kTimeUnit << ",op_name:" << event.op_name
  248. << ",device_id:" << event.device_id << ",correlation_id:" << event.correlation_id
  249. << ",thread_id:" << event.thread_id << ",context_id:" << event.context_id
  250. << ",stream_id:" << event.stream_id << ",cb_id:" << event.cb_id;
  251. }
  252. void GPUProfiler::ProcessEvents() {
  253. for (Event &event : events_) {
  254. if (event.op_name.empty()) {
  255. FixOpNameByCorrelationId(&event);
  256. }
  257. EventLog(event);
  258. if (event.op_name.empty() || event.cb_id == CUPTI_DRIVER_TRACE_CBID_cuStreamSynchronize) {
  259. continue;
  260. }
  261. auto iter = op_info_map_.find(event.op_name);
  262. if (iter != op_info_map_.end()) {
  263. switch (event.api_type) {
  264. case CUPTIApiType::kCallback: {
  265. iter->second.op_kernel_api_count += 1;
  266. // The time unit from ns to us
  267. iter->second.cupti_api_call_time += (event.end_time_stamp - event.start_time_stamp) / kTimeUnit;
  268. break;
  269. }
  270. case CUPTIApiType::kActivity: {
  271. iter->second.op_kernel_count += 1;
  272. // The time unit from ns to us
  273. iter->second.cupti_activity_time += (event.end_time_stamp - event.start_time_stamp) / kTimeUnit;
  274. break;
  275. }
  276. default:
  277. break;
  278. }
  279. }
  280. }
  281. }
  282. void GPUProfiler::OpsParser() {
  283. MS_LOG(INFO) << "Count the number of events size:" << events_.size()
  284. << " callback api:" << cupti_callback_events_count_ << " activity:" << cupti_activity_events_count_;
  285. if (cupti_activity_events_drop_count_ > 0 || cupti_callback_events_drop_count_ > 0) {
  286. MS_LOG(WARNING)
  287. << "The total number of events exceeded the profiler's processing capacity, some events were discarded."
  288. << " activity api events:" << cupti_activity_events_drop_count_
  289. << " callback api events:" << cupti_callback_events_drop_count_;
  290. }
  291. if (events_.size() == 0) {
  292. return;
  293. }
  294. ProcessEvents();
  295. MS_LOG(DEBUG) << "GPU_profiler, op_name, op_count , kernel_count, kernel_api_count,|"
  296. ",cupti_activity_total_time, cupti_api_call_total_time, op_host_cost_total_time,|"
  297. ",cupti_activity_average_time,cupti_api_call_average_time, op_host_cost_average_time"
  298. << std::endl;
  299. std::vector<std::pair<std::string, OpInfo>> order_vec(op_info_map_.begin(), op_info_map_.end());
  300. auto cmp_func = [](const std::pair<std::string, OpInfo> &a, const std::pair<std::string, OpInfo> &b) {
  301. return a.second.cupti_activity_time > b.second.cupti_activity_time;
  302. };
  303. std::sort(order_vec.begin(), order_vec.end(), cmp_func);
  304. for (auto iter = order_vec.begin(); iter != order_vec.end(); iter++) {
  305. MS_LOG(DEBUG) << "GPU_profiler"
  306. << "," << iter->first << "," << iter->second.op_count << "," << iter->second.op_kernel_count << ","
  307. << iter->second.op_kernel_api_count << ","
  308. << "|," << iter->second.cupti_activity_time << "," << iter->second.cupti_api_call_time << ","
  309. << iter->second.op_host_cost_time << ","
  310. << "|," << round(iter->second.cupti_activity_time / iter->second.op_count) << ","
  311. << round(iter->second.cupti_api_call_time / iter->second.op_count) << ","
  312. << round(iter->second.op_host_cost_time / iter->second.op_count) << std::endl;
  313. }
  314. }
  315. void GPUProfiler::EventHandleProcess(CUpti_CallbackId cbid, const CUpti_CallbackData *cbdata,
  316. const std::string &typestring, uint64_t startTimestamp, uint64_t endTimestamp) {
  317. Event event;
  318. uint32_t device_id = -1;
  319. CuptiGetDeviceId(cbdata->context, &device_id);
  320. event.kernel_name = cbdata->symbolName ? GetKernelFunc(cbdata->symbolName) : cbdata->functionName;
  321. event.kernel_name = GetKernelFuncName(event.kernel_name);
  322. event.kernel_type = typestring;
  323. event.api_type = CUPTIApiType::kCallback;
  324. event.start_time_stamp = startTimestamp;
  325. event.end_time_stamp = endTimestamp;
  326. event.op_name = op_name_;
  327. event.device_id = device_id;
  328. event.correlation_id = cbdata->correlationId;
  329. event.thread_id = GetThreadID();
  330. event.context_id = cbdata->contextUid;
  331. event.stream_id = GetStreamID(cbdata->context, stream_);
  332. event.cb_id = cbid;
  333. op_name_map_[event.correlation_id] = event.op_name;
  334. AddEvent(std::move(event));
  335. }
  336. void CUPTIAPI ActivityAllocBuffer(uint8_t **buffer, size_t *size, size_t *maxNumRecords);
  337. void CUPTIAPI ActivityProcessBuffer(CUcontext ctx, uint32_t streamId, uint8_t *buffer, size_t size, size_t validSize);
  338. void GPUProfiler::Init(const std::string &profileDataPath = "") {
  339. MS_LOG(INFO) << "Initialize GPU Profiling";
  340. if (subscriber_ != nullptr) {
  341. StopCUPTI();
  342. MS_LOG(EXCEPTION)
  343. << "Repeated initialization, Please check whether you have created the Profiler object multiple times";
  344. }
  345. CHECK_CUPTI_RET_WITH_EXCEPT(CuptiSubscribe(&subscriber_, (CUpti_CallbackFunc)CUPTICallBackFunc, this),
  346. "CuptiSubscribe");
  347. CHECK_CUPTI_RET_WITH_EXCEPT(CuptiEnableDomain(1, subscriber_, CUPTI_CB_DOMAIN_DRIVER_API), "CuptiEnableDomain");
  348. activities_enable_.emplace_back(CUPTI_ACTIVITY_KIND_MEMCPY);
  349. activities_enable_.emplace_back(CUPTI_ACTIVITY_KIND_MEMCPY2);
  350. activities_enable_.emplace_back(CUPTI_ACTIVITY_KIND_KERNEL);
  351. for (std::vector<CUpti_ActivityKind>::iterator it = activities_enable_.begin(); it != activities_enable_.end();
  352. ++it) {
  353. CHECK_CUPTI_RET_WITH_EXCEPT(CuptiActivityEnable(*it), "CuptiActivityEnable");
  354. }
  355. CHECK_CUPTI_RET_WITH_EXCEPT(CuptiActivityRegisterCallbacks(ActivityAllocBuffer, ActivityProcessBuffer),
  356. "CuptiActivityRegisterCallbacks");
  357. base_time_.gpu_start_time = GetCUPTITimeStamp();
  358. base_time_.host_start_time = GetHostTimeStamp();
  359. base_time_.host_start_monotonic_raw_time = GetHostMonoTimeStamp();
  360. profile_data_path_ = profileDataPath;
  361. MS_LOG(INFO) << "GPU start time(ns):" << base_time_.gpu_start_time
  362. << " Host start time(ns):" << base_time_.host_start_time << " profile data path: " << profile_data_path_;
  363. }
  364. void GPUProfiler::SetRunTimeData(const std::string &op_name, void *stream) {
  365. auto iter = op_info_map_.find(op_name);
  366. if (iter != op_info_map_.end()) {
  367. iter->second.op_count += 1;
  368. } else {
  369. OpInfo op_info;
  370. op_info.op_name = op_name;
  371. op_info.stream = stream;
  372. op_info.op_count = 1;
  373. op_info_map_[op_name] = op_info;
  374. }
  375. op_name_ = op_name;
  376. stream_ = stream;
  377. }
  378. void GPUProfiler::OpDataProducerBegin(const std::string op_name, void *stream) {
  379. if (sync_enable_flag_) {
  380. CHECK_CUDA_RET_WITH_ERROR(cudaEventCreate(&op_event_start_), "cudaEventCreate op event start failed");
  381. CHECK_CUDA_RET_WITH_ERROR(cudaEventCreate(&op_event_stop_), "cudaEventCreate op event stop failed");
  382. CHECK_CUDA_RET_WITH_ERROR(cudaEventRecord(op_event_start_, (CUstream)stream_),
  383. "cudaEventRecord op event start failed");
  384. op_host_time_start_ = GetHostTimeStamp();
  385. op_cupti_time_start_ = GetCUPTITimeStamp();
  386. } else {
  387. op_host_time_start_ = GetHostTimeStamp();
  388. op_cupti_time_start_ = GetCUPTITimeStamp();
  389. }
  390. SetRunTimeData(op_name, stream);
  391. }
  392. void GPUProfiler::OpDataProducerEnd() {
  393. float op_time_elapsed = 0;
  394. if (sync_enable_flag_) {
  395. CHECK_CUDA_RET_WITH_ERROR(cudaEventRecord(op_event_stop_, (CUstream)stream_),
  396. "cudaEventRecord op event stop failed");
  397. CHECK_CUDA_RET_WITH_ERROR(cudaEventSynchronize(op_event_start_), "cudaEventSynchronize op event start failed");
  398. CHECK_CUDA_RET_WITH_ERROR(cudaEventSynchronize(op_event_stop_), "cudaEventSynchronize op event stop failed");
  399. CHECK_CUDA_RET_WITH_ERROR(cudaEventElapsedTime(&op_time_elapsed, op_event_start_, op_event_stop_),
  400. "cudaEventElapsedTime failed");
  401. CHECK_CUDA_RET_WITH_ERROR(cudaEventDestroy(op_event_start_), "cudaEventDestroy op event start failed");
  402. CHECK_CUDA_RET_WITH_ERROR(cudaEventDestroy(op_event_stop_), "cudaEventDestroy op event stop failed");
  403. op_time_elapsed = op_time_elapsed * kTimeUnit;
  404. op_host_time_stop_ = GetHostTimeStamp();
  405. } else {
  406. op_host_time_stop_ = GetHostTimeStamp();
  407. op_time_elapsed = (op_host_time_stop_ - op_host_time_start_) / kTimeUnit;
  408. }
  409. MS_LOG(DEBUG) << "Host Time Elapsed(us)," << op_name_ << "," << op_time_elapsed;
  410. Profiler::SetRunTimeData(op_name_, op_time_elapsed);
  411. Profiler::SetRunTimeData(op_name_, op_cupti_time_start_, op_time_elapsed);
  412. }
  413. void GPUProfiler::StopCUPTI() {
  414. if (subscriber_ != nullptr) {
  415. CHECK_CUPTI_RET_WITH_ERROR(CuptiUnsubscribe(subscriber_), "CuptiUnsubscribe");
  416. CHECK_CUPTI_RET_WITH_ERROR(CuptiActivityFlushAll(0), "CuptiActivityFlushAll");
  417. for (std::vector<CUpti_ActivityKind>::iterator it = activities_enable_.begin(); it != activities_enable_.end();
  418. ++it) {
  419. CHECK_CUPTI_RET_WITH_ERROR(CuptiActivityDisable(*it), "CuptiActivityDisable");
  420. }
  421. subscriber_ = nullptr;
  422. }
  423. }
  424. void GPUProfiler::Stop() {
  425. MS_LOG(INFO) << "Stop GPU Profiling";
  426. StopCUPTI();
  427. OpsParser();
  428. SaveProfileData();
  429. ClearInst();
  430. }
  431. void GPUProfiler::SaveExtraProfileData() {
  432. for (auto op : profiling_op_) {
  433. op.second->SaveProfilingData();
  434. }
  435. MS_LOG(INFO) << "Save extra profiling data end.";
  436. }
  437. void GPUProfiler::SaveProfileData() {
  438. if (profile_data_path_.empty()) {
  439. MS_LOG(WARNING) << "Profile data path is empty, skip save profile data.";
  440. } else {
  441. GpuDataSaver dataSaver;
  442. dataSaver.SetStepTraceOpName(step_trace_op_name);
  443. dataSaver.ParseOpInfo(op_info_map_);
  444. dataSaver.ParseEvent(events_);
  445. dataSaver.WriteFile(profile_data_path_, base_time_);
  446. SaveExtraProfileData();
  447. }
  448. }
  449. void GPUProfiler::ClearInst() {
  450. op_info_map_.clear();
  451. op_name_map_.clear();
  452. events_.clear();
  453. activities_enable_.clear();
  454. enable_flag_ = false;
  455. sync_enable_flag_ = true;
  456. cupti_callback_events_count_ = 0l;
  457. cupti_callback_events_drop_count_ = 0l;
  458. cupti_activity_events_count_ = 0l;
  459. cupti_activity_events_drop_count_ = 0l;
  460. }
  461. void CUPTIAPI ActivityAllocBuffer(uint8_t **buffer, size_t *size, size_t *maxNumRecords) {
  462. auto gpu_profiler_inst = GPUProfiler::GetInstance();
  463. if (gpu_profiler_inst == nullptr) {
  464. MS_LOG(ERROR) << "GPU profiler instance is nullptr";
  465. return;
  466. }
  467. gpu_profiler_inst->AllocBuffer(buffer, size, maxNumRecords);
  468. }
  469. void CUPTIAPI ActivityProcessBuffer(CUcontext ctx, uint32_t streamId, uint8_t *buffer, size_t size, size_t validSize) {
  470. PROFILER_ERROR_IF_NULLPTR(buffer);
  471. GPUProfiler::GetInstance()->ProcessBuffer(ctx, streamId, buffer, size, validSize);
  472. }
  473. void ProcessActivityMemcpyRecord(Event *profilingData, CUpti_Activity *record, CUpti_ActivityMemcpy *memcpy) {
  474. switch (memcpy->copyKind) {
  475. case CUPTI_ACTIVITY_MEMCPY_KIND_HTOD:
  476. profilingData->activity_type = ActivityType::kMemcpyH2D;
  477. profilingData->kernel_name = "MemcpyH2D";
  478. break;
  479. case CUPTI_ACTIVITY_MEMCPY_KIND_DTOH:
  480. profilingData->activity_type = ActivityType::kMemcpyD2H;
  481. profilingData->kernel_name = "MemcpyD2H";
  482. break;
  483. case CUPTI_ACTIVITY_MEMCPY_KIND_HTOA:
  484. profilingData->activity_type = ActivityType::kMemcpyH2A;
  485. profilingData->kernel_name = "MemcpyH2A";
  486. break;
  487. case CUPTI_ACTIVITY_MEMCPY_KIND_ATOH:
  488. profilingData->activity_type = ActivityType::kMemcpyA2H;
  489. profilingData->kernel_name = "MemcpyA2H";
  490. break;
  491. case CUPTI_ACTIVITY_MEMCPY_KIND_ATOD:
  492. profilingData->activity_type = ActivityType::kMemcpyA2D;
  493. profilingData->kernel_name = "MemcpyA2D";
  494. break;
  495. case CUPTI_ACTIVITY_MEMCPY_KIND_DTOA:
  496. profilingData->activity_type = ActivityType::kMemcpyD2A;
  497. profilingData->kernel_name = "MemcpyD2A";
  498. break;
  499. case CUPTI_ACTIVITY_MEMCPY_KIND_DTOD:
  500. profilingData->activity_type = ActivityType::kMemcpyD2D;
  501. profilingData->kernel_name = "MemcpyD2D";
  502. break;
  503. case CUPTI_ACTIVITY_MEMCPY_KIND_HTOH:
  504. profilingData->activity_type = ActivityType::kMemcpyH2H;
  505. profilingData->kernel_name = "MemcpyH2H";
  506. break;
  507. case CUPTI_ACTIVITY_MEMCPY_KIND_PTOP:
  508. profilingData->activity_type = ActivityType::kMemcpyP2P;
  509. profilingData->kernel_name = "MemcpyP2P";
  510. break;
  511. default:
  512. profilingData->activity_type = ActivityType::kMemcpyUnknown;
  513. profilingData->kernel_name = "MemcpyUnknown";
  514. break;
  515. }
  516. }
  517. void HandleActivityMemcpyRecord(Event *profilingData, CUpti_Activity *record) {
  518. CUpti_ActivityMemcpy *memcpy = reinterpret_cast<CUpti_ActivityMemcpy *>(record);
  519. ProcessActivityMemcpyRecord(profilingData, record, memcpy);
  520. profilingData->kernel_type = "cuMemcpy";
  521. profilingData->api_type = CUPTIApiType::kActivity;
  522. profilingData->start_time_stamp = memcpy->start;
  523. profilingData->end_time_stamp = memcpy->end;
  524. profilingData->device_id = memcpy->deviceId;
  525. profilingData->context_id = memcpy->contextId;
  526. profilingData->stream_id = memcpy->streamId;
  527. profilingData->correlation_id = memcpy->correlationId;
  528. profilingData->memcpy_info.bytes = memcpy->bytes;
  529. profilingData->memcpy_info.src_kind = memcpy->srcKind;
  530. profilingData->memcpy_info.dst_kind = memcpy->dstKind;
  531. }
  532. void HandleActivityMemcpy2Record(Event *profilingData, CUpti_Activity *record) {
  533. CUpti_ActivityMemcpy2 *memcpyP2P = reinterpret_cast<CUpti_ActivityMemcpy2 *>(record);
  534. profilingData->activity_type = ActivityType::kMemcpyP2P;
  535. profilingData->kernel_name = "MemcpyP2P";
  536. profilingData->kernel_type = "cuMemcpy";
  537. profilingData->api_type = CUPTIApiType::kActivity;
  538. profilingData->start_time_stamp = memcpyP2P->start;
  539. profilingData->end_time_stamp = memcpyP2P->end;
  540. profilingData->device_id = memcpyP2P->deviceId;
  541. profilingData->context_id = memcpyP2P->contextId;
  542. profilingData->stream_id = memcpyP2P->streamId;
  543. profilingData->correlation_id = memcpyP2P->correlationId;
  544. profilingData->memcpy_info.bytes = memcpyP2P->bytes;
  545. profilingData->memcpy_info.src_kind = memcpyP2P->srcKind;
  546. profilingData->memcpy_info.dst_kind = memcpyP2P->dstKind;
  547. }
  548. void HandleActivityMemsetRecord(Event *profilingData, CUpti_Activity *record) {
  549. CUpti_ActivityMemset *memset = reinterpret_cast<CUpti_ActivityMemset *>(record);
  550. profilingData->activity_type = ActivityType::kMemset;
  551. profilingData->kernel_name = "MemorySet";
  552. profilingData->api_type = CUPTIApiType::kActivity;
  553. profilingData->start_time_stamp = memset->start;
  554. profilingData->end_time_stamp = memset->end;
  555. profilingData->device_id = memset->deviceId;
  556. profilingData->context_id = memset->contextId;
  557. profilingData->stream_id = memset->streamId;
  558. profilingData->correlation_id = memset->correlationId;
  559. profilingData->memcpy_info.bytes = memset->bytes;
  560. }
  561. void HandleActivityKernelRecord(Event *profilingData, CUpti_Activity *record) {
  562. CUpti_ActivityKernel4 *kernel = reinterpret_cast<CUpti_ActivityKernel4 *>(record);
  563. profilingData->activity_type = ActivityType::kKernel;
  564. profilingData->api_type = CUPTIApiType::kActivity;
  565. profilingData->kernel_name = GetKernelFunc(kernel->name);
  566. profilingData->kernel_name = GetKernelFuncName(profilingData->kernel_name);
  567. profilingData->kernel_type = "cuLaunchKernel";
  568. profilingData->start_time_stamp = kernel->start;
  569. profilingData->end_time_stamp = kernel->end;
  570. profilingData->device_id = kernel->deviceId;
  571. profilingData->context_id = kernel->contextId;
  572. profilingData->stream_id = kernel->streamId;
  573. profilingData->correlation_id = kernel->correlationId;
  574. profilingData->kernel_info.registers_per_thread = kernel->registersPerThread;
  575. profilingData->kernel_info.static_shared_memory = kernel->staticSharedMemory;
  576. profilingData->kernel_info.dynamic_shared_memory = kernel->dynamicSharedMemory;
  577. profilingData->kernel_info.block_x = kernel->blockX;
  578. profilingData->kernel_info.block_y = kernel->blockY;
  579. profilingData->kernel_info.block_z = kernel->blockZ;
  580. profilingData->kernel_info.grid_x = kernel->gridX;
  581. profilingData->kernel_info.grid_y = kernel->gridY;
  582. profilingData->kernel_info.grid_z = kernel->gridZ;
  583. }
  584. void GPUProfiler::HandleActivityRecord(CUpti_Activity *record) {
  585. PROFILER_ERROR_IF_NULLPTR(record);
  586. Event profilingData;
  587. profilingData.cb_id = 0;
  588. switch (record->kind) {
  589. case CUPTI_ACTIVITY_KIND_MEMCPY: {
  590. HandleActivityMemcpyRecord(&profilingData, record);
  591. break;
  592. }
  593. case CUPTI_ACTIVITY_KIND_MEMCPY2: {
  594. HandleActivityMemcpy2Record(&profilingData, record);
  595. break;
  596. }
  597. case CUPTI_ACTIVITY_KIND_MEMSET: {
  598. HandleActivityMemsetRecord(&profilingData, record);
  599. break;
  600. }
  601. case CUPTI_ACTIVITY_KIND_KERNEL:
  602. case CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL: {
  603. HandleActivityKernelRecord(&profilingData, record);
  604. break;
  605. }
  606. default:
  607. MS_LOG(WARNING) << "Unknown activity type!";
  608. return;
  609. }
  610. AddEvent(std::move(profilingData));
  611. }
  612. void GPUProfiler::SetStepTraceOpName(ProfilingTraceInfo trace_op_name) { step_trace_op_name = trace_op_name; }
  613. void GPUProfiler::RegisterProfilingOp(std::shared_ptr<ProfilingOp> node) {
  614. if (profiling_op_.find(node->Name()) != profiling_op_.end()) {
  615. return;
  616. }
  617. node->Init();
  618. profiling_op_[node->Name()] = node;
  619. }
  620. void CUPTIAPI GPUProfiler::AllocBuffer(uint8_t **buffer, size_t *size, size_t *maxNumRecords) {
  621. int stat = posix_memalign(reinterpret_cast<void **>(buffer), ALIGN_SIZE, BUF_SIZE);
  622. if (stat) {
  623. MS_LOG(ERROR) << "Out of memory, activity buffer alloc failed.";
  624. return;
  625. }
  626. MS_LOG(DEBUG) << "Alloc activity buffer, buffer size: " << BUF_SIZE;
  627. *size = BUF_SIZE;
  628. *maxNumRecords = 0;
  629. }
  630. void CUPTIAPI GPUProfiler::ProcessBuffer(CUcontext ctx, uint32_t streamId, uint8_t *buffer, size_t size,
  631. size_t validSize) {
  632. if (!enable_flag_) {
  633. MS_LOG(DEBUG) << "Profiler is not enable, skip to process activity record.";
  634. free(buffer);
  635. return;
  636. }
  637. CUptiResult status;
  638. CUpti_Activity *record = NULL;
  639. MS_LOG(DEBUG) << "Process activity buffer, valid size:" << validSize << ",Stream ID:" << streamId;
  640. if (validSize > 0) {
  641. do {
  642. status = CuptiActivityGetNextRecord(buffer, validSize, &record);
  643. if (status == CUPTI_SUCCESS) {
  644. HandleActivityRecord(record);
  645. } else if (status == CUPTI_ERROR_MAX_LIMIT_REACHED) {
  646. break;
  647. } else {
  648. CHECK_CUPTI_RET_WITH_ERROR(status, "CuptiActivityGetNextRecord");
  649. }
  650. } while (1);
  651. // report any records dropped from the queue
  652. size_t dropped;
  653. CHECK_CUPTI_RET_WITH_ERROR(CuptiActivityGetNumDroppedRecords(ctx, streamId, &dropped),
  654. "CuptiActivityGetNumDroppedRecords");
  655. if (dropped != 0) {
  656. MS_LOG(INFO) << "Dropped " << (unsigned int)dropped << " activity records\n";
  657. }
  658. }
  659. free(buffer);
  660. }
  661. REGISTER_PYBIND_DEFINE(GPUProfiler_, ([](const py::module *m) {
  662. (void)py::class_<GPUProfiler, std::shared_ptr<GPUProfiler>>(*m, "GPUProfiler")
  663. .def_static("get_instance", &GPUProfiler::GetInstance, "GPUProfiler get_instance.")
  664. .def("init", &GPUProfiler::Init, py::arg("profile_data_path"), "init")
  665. .def("stop", &GPUProfiler::Stop, "stop")
  666. .def("step_profiling_enable", &GPUProfiler::StepProfilingEnable, py::arg("enable_flag"),
  667. "enable or disable step profiling")
  668. .def("sync_enable", &GPUProfiler::SyncEnable, py::arg("enable_flag"),
  669. "enable or disable synchronization profiling");
  670. }));
  671. } // namespace gpu
  672. } // namespace profiler
  673. } // namespace mindspore