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.

profiling_manager.cc 50 kB

5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. /**
  2. * Copyright 2020 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 "common/profiling/profiling_manager.h"
  17. #include "framework/common/debug/ge_log.h"
  18. #include "framework/common/debug/log.h"
  19. #include "framework/common/string_util.h"
  20. #include "graph/ge_context.h"
  21. #include "graph/utils/type_utils.h"
  22. #include "external/graph/types.h"
  23. #include "runtime/base.h"
  24. #include "graph/load/model_manager/davinci_model.h"
  25. #include "mmpa/mmpa_api.h"
  26. #include "graph/load/graph_loader.h"
  27. namespace {
  28. const char *const kTrainingTrace = "training_trace";
  29. const char *const kFpPoint = "fp_point";
  30. const char *const kBpPoint = "bp_point";
  31. #ifdef DAVINCI_SUPPORT_PROFILING
  32. const int32_t kMaxDeviceNum = 256;
  33. const uint32_t kInteval = 2;
  34. const std::string kConfigNumsdev = "devNums";
  35. const std::string kConfigDevIdList = "devIdList";
  36. const std::string kProfStart = "prof_start";
  37. const std::string kProfStop = "prof_stop";
  38. const std::string kProfModelSubscribe = "prof_model_subscribe";
  39. const std::string kProfModelUnsubscribe = "prof_model_cancel_subscribe";
  40. const std::string kModelName = "model_name";
  41. const std::string kModelId = "model_id";
  42. const std::string kOpNmae = "op_name";
  43. const std::string kOptype = "op_type";
  44. const std::string kBlockDim = "block_dims";
  45. const std::string kTaskId = "task_id";
  46. const std::string kStreamId = "stream_id";
  47. const std::string kThreadId = "thread_id";
  48. const std::string kIndexId = "index_id";
  49. const std::string kTimeStamp = "time_stamp";
  50. const std::string kTagId = "tag_id";
  51. const std::string kShapeType = "shape_type";
  52. const std::string kCurIterNum = "cur_iter_num";
  53. const std::string kTaskType = "task_type";
  54. const std::string kInput = "input";
  55. const std::string kOutput = "output";
  56. const std::string kFormat = "format";
  57. const std::string kDataType = "data_type";
  58. const std::string kShape = "shape";
  59. const std::string kIdx = "idx";
  60. #endif
  61. const uint32_t kDeviceListIndex = 3;
  62. const uint32_t kCommandNum = 6;
  63. const int kMaxDevNum = 64;
  64. const std::string kDeviceNums = "devNums";
  65. const std::string kDeviceIdList = "devIdList";
  66. const std::string kProfilingInit = "prof_init";
  67. const std::string kProfilingFinalize = "prof_finalize";
  68. const std::string kProfilingStart = "prof_start";
  69. const std::string kProfilingStop = "prof_stop";
  70. const std::string kProfilingModelSubscribe = "prof_model_subscribe";
  71. const std::string kProfilingModelUnsubscribe = "prof_model_cancel_subscribe";
  72. const std::string kPofilingModelId = "modelId";
  73. const std::map<ProfCommandHandleType, std::string> kProfCommandTypeMap = {
  74. {kProfCommandhandleInit, kProfilingInit},
  75. {kProfCommandhandleStart, kProfilingStart},
  76. {kProfCommandhandleStop, kProfilingStop},
  77. {kProfCommandhandleFinalize, kProfilingFinalize},
  78. {kProfCommandhandleModelSubscribe, kProfilingModelSubscribe},
  79. {kProfCommandhandleModelUnsubscribe, kProfilingModelUnsubscribe}};
  80. } // namespace
  81. namespace ge {
  82. ProfSubscribeInfo ProfilingManager::subscribe_info_ = {false, 0, 0};
  83. MsprofReporterCallback ProfilingManager::reporter_callback_ = nullptr;
  84. ProfilingManager::ProfilingManager()
  85. : is_load_profiling_(false),
  86. is_execute_profiling_(false),
  87. is_training_trace_(false),
  88. subscribe_count_(0),
  89. index_id_(UINT64_MAX) {
  90. }
  91. ProfilingManager::~ProfilingManager() {}
  92. ProfilingManager &ProfilingManager::Instance() {
  93. static ProfilingManager profiling_manager;
  94. return profiling_manager;
  95. }
  96. ge::Status ProfilingManager::InitFromOptions(const Options &options, MsprofGeOptions &prof_conf) {
  97. #ifdef DAVINCI_SUPPORT_PROFILING
  98. // enable profiling by env
  99. char env_profiling_mode[MMPA_MAX_PATH] = { 0x00 };
  100. is_execute_profiling_ = false;
  101. if (options.profiling_mode == "1" && !options.profiling_options.empty()) {
  102. // enable profiling by ge option
  103. if (strncpy_s(prof_conf.options, MSPROF_OPTIONS_DEF_LEN_MAX, options.profiling_options.c_str(),
  104. MSPROF_OPTIONS_DEF_LEN_MAX - 1) != EOK) {
  105. GELOGE(INTERNAL_ERROR, "[copy][ProfilingOptions]Failed, options %s",
  106. options.profiling_options.c_str());
  107. REPORT_CALL_ERROR("E19999", "Copy profiling_options %s failed",
  108. options.profiling_options.c_str());
  109. return INTERNAL_ERROR;
  110. }
  111. is_execute_profiling_ = true;
  112. GELOGI("The profiling in options is %s, %s. origin option: %s", options.profiling_mode.c_str(), prof_conf.options,
  113. options.profiling_options.c_str());
  114. } else {
  115. (void)mmGetEnv("PROFILING_MODE", env_profiling_mode, MMPA_MAX_PATH);
  116. (void)mmGetEnv("PROFILING_OPTIONS", prof_conf.options, MSPROF_OPTIONS_DEF_LEN_MAX);
  117. // The env is invalid
  118. if ((strcmp("true", env_profiling_mode) != 0) || (strcmp(prof_conf.options, "\0") == 0)) {
  119. return SUCCESS;
  120. }
  121. // enable profiling by env
  122. is_execute_profiling_ = true;
  123. GELOGI("The profiling in env is %s, %s", env_profiling_mode, prof_conf.options);
  124. }
  125. if (!is_execute_profiling_) {
  126. return SUCCESS;
  127. }
  128. // Parse json str for bp fp
  129. Status ret = ParseOptions(prof_conf.options);
  130. if (ret != ge::SUCCESS) {
  131. GELOGE(ge::PARAM_INVALID, "[Parse][Options]Parse training trace param %s failed, error_code %u",
  132. prof_conf.options, ret);
  133. REPORT_CALL_ERROR("E19999", "Parse training trace param %s failed, error_code %u",
  134. prof_conf.options, ret);
  135. return ge::PARAM_INVALID;
  136. }
  137. if (strncpy_s(prof_conf.jobId, MSPROF_OPTIONS_DEF_LEN_MAX, options.job_id.c_str(), MSPROF_OPTIONS_DEF_LEN_MAX - 1) !=
  138. EOK) {
  139. GELOGE(INTERNAL_ERROR, "[Copy][JobId]Failed, original job_id %s", options.job_id.c_str());
  140. REPORT_CALL_ERROR("E19999", "Copy job_id %s failed", options.job_id.c_str());
  141. return INTERNAL_ERROR;
  142. }
  143. GELOGI("Job id: %s, original job id: %s.", prof_conf.jobId, options.job_id.c_str());
  144. #endif
  145. return ge::SUCCESS;
  146. }
  147. ge::Status ProfilingManager::ParseOptions(const std::string &options) {
  148. if (options.empty()) {
  149. GELOGE(ge::PARAM_INVALID, "[Check][Param]Profiling options is empty");
  150. REPORT_INNER_ERROR("E19999", "Profiling options is empty");
  151. return ge::PARAM_INVALID;
  152. }
  153. try {
  154. Json prof_options = Json::parse(options);
  155. if (options.find(kTrainingTrace) == std::string::npos) {
  156. return ge::SUCCESS;
  157. }
  158. std::string training_trace;
  159. if (prof_options.contains(kTrainingTrace)) {
  160. training_trace = prof_options[kTrainingTrace];
  161. }
  162. if (training_trace.empty()) {
  163. GELOGI("Training trace will not take effect.");
  164. return ge::SUCCESS;
  165. }
  166. GELOGI("GE profiling training trace:%s", training_trace.c_str());
  167. if (training_trace != "on") {
  168. GELOGE(ge::PARAM_INVALID, "[Check][Param]Training trace param:%s is invalid.",
  169. training_trace.c_str());
  170. REPORT_INNER_ERROR("E19999", "Training trace param:%s is invalid.", training_trace.c_str());
  171. return ge::PARAM_INVALID;
  172. }
  173. if (prof_options.contains(kFpPoint)) {
  174. fp_point_ = prof_options[kFpPoint];
  175. }
  176. if (prof_options.contains(kBpPoint)) {
  177. bp_point_ = prof_options[kBpPoint];
  178. }
  179. if (!fp_point_.empty() && !bp_point_.empty()) {
  180. GELOGI("Training trace bp fp is set, bp_point:%s, fp_point:%s.", bp_point_.c_str(), fp_point_.c_str());
  181. }
  182. is_training_trace_ = true;
  183. } catch (...) {
  184. GELOGE(FAILED, "[Check][Param]Json prof_conf options is invalid");
  185. REPORT_INNER_ERROR("E19999", "Json prof_conf options is invalid");
  186. return ge::PARAM_INVALID;
  187. }
  188. return ge::SUCCESS;
  189. }
  190. void ProfilingManager::ProfilingOpInputOutInfo(const TaskDescInfo &task, Json &task_json) {
  191. #ifdef DAVINCI_SUPPORT_PROFILING
  192. for (size_t i = 0; i < task.input_format.size(); i++) {
  193. Json tmp_input;
  194. tmp_input[kIdx] = i;
  195. Format format = task.input_format[i];
  196. tmp_input[kFormat] = TypeUtils::FormatToSerialString(format);
  197. DataType data_type = task.input_data_type[i];
  198. tmp_input[kDataType] = TypeUtils::DataTypeToSerialString(data_type);
  199. tmp_input[kShape] = task.input_shape[i];
  200. task_json[kInput] += tmp_input;
  201. }
  202. for (size_t i = 0; i < task.output_format.size(); i++) {
  203. Json tmp_output;
  204. tmp_output[kIdx] = i;
  205. Format format = task.output_format[i];
  206. tmp_output[kFormat] = TypeUtils::FormatToSerialString(format);
  207. DataType data_type = task.output_data_type[i];
  208. tmp_output[kDataType] = TypeUtils::DataTypeToSerialString(data_type);
  209. tmp_output[kShape] = task.output_shape[i];
  210. task_json[kOutput] += tmp_output;
  211. }
  212. #endif
  213. }
  214. void ProfilingManager::ProfilingTaskDescInfo(uint32_t model_id, const std::vector<TaskDescInfo> &task_desc_info,
  215. const int32_t &device_id) {
  216. #ifdef DAVINCI_SUPPORT_PROFILING
  217. for (const auto &task : task_desc_info) {
  218. Json task_info;
  219. task_info[kModelName] = task.model_name;
  220. task_info[kModelId] = model_id;
  221. task_info[kOpNmae] = task.op_name;
  222. task_info[kOptype] = task.op_type;
  223. task_info[kBlockDim] = task.block_dim;
  224. task_info[kTaskType] = task.task_type;
  225. task_info[kTaskId] = task.task_id;
  226. task_info[kStreamId] = task.stream_id;
  227. task_info[kCurIterNum] = task.cur_iter_num;
  228. task_info[kShapeType] = task.shape_type;
  229. ProfilingOpInputOutInfo(task, task_info);
  230. std::string reported_data;
  231. try {
  232. reported_data = task_info.dump(kInteval, ' ', false, Json::error_handler_t::ignore);
  233. } catch (std::exception &e) {
  234. GELOGE(FAILED, "[Convert][ReportData]Failed to convert json to string, reason %s.",
  235. e.what());
  236. REPORT_CALL_ERROR("E19999", "Failed to convert reported_data from json to string, reason %s",
  237. e.what());
  238. return ;
  239. } catch (...) {
  240. GELOGE(FAILED, "[Convert][ReportedData]Failed to convert JSON to string");
  241. REPORT_CALL_ERROR("E19999", "Failed to convert reported data from json to string");
  242. return;
  243. }
  244. reported_data.append(",")
  245. .append("\n");
  246. ReportData(device_id, reported_data, "task_desc_info");
  247. }
  248. #endif
  249. }
  250. Status ProfilingManager::ProfileStepInfo(uint64_t index_id, uint64_t model_id, uint16_t tag_id, rtStream_t stream,
  251. int32_t device_id) {
  252. #ifdef DAVINCI_SUPPORT_PROFILING
  253. if (!is_load_profiling_ && subscribe_count_ == 0) {
  254. GELOGD("Profiling is not turned on, no need to profile step info.");
  255. return SUCCESS;
  256. }
  257. GELOGD("Profiling Step Info TraceTask execute async start, index_id = %lu, model_id = %lu, tag_id = %u",
  258. index_id, model_id, tag_id);
  259. rtError_t rt_ret = rtProfilerTraceEx(index_id, model_id, tag_id, stream);
  260. if (rt_ret != RT_ERROR_NONE) {
  261. GELOGE(RT_FAILED, "[Call][rtProfilerTraceEx]Failed, ret 0x%X", rt_ret);
  262. REPORT_CALL_ERROR("E19999", "Call rtProfilerTraceEx failed, ret 0x%X", rt_ret);
  263. return RT_ERROR_TO_GE_STATUS(rt_ret);
  264. }
  265. GELOGD("Profiling Step Info TraceTask execute async success, index_id = %lu, model_id = %lu, tag_id = %u",
  266. index_id, model_id, tag_id);
  267. mmTimespec timespec = mmGetTickCount();
  268. // 1000 ^ 3 converts second to nanosecond
  269. int64_t time = timespec.tv_sec * 1000 * 1000 * 1000 + timespec.tv_nsec;
  270. uint32_t task_id = 0;
  271. uint32_t stream_id = 0;
  272. rt_ret = rtGetTaskIdAndStreamID(&task_id, &stream_id);
  273. if (rt_ret != RT_ERROR_NONE) {
  274. GELOGE(RT_FAILED, "[Get][RtsInfo]Task_id and stream_id failed, ret 0x%X", rt_ret);
  275. REPORT_CALL_ERROR("E19999", "Get task_id and stream_id failed, ret 0x%X", rt_ret);
  276. return RT_ERROR_TO_GE_STATUS(rt_ret);
  277. }
  278. GELOGD("Get profiling args, task_id[%u], stream_id[%u]", task_id, stream_id);
  279. Json step_info;
  280. step_info[kIndexId] = index_id;
  281. step_info[kModelId] = model_id;
  282. step_info[kTimeStamp] = time;
  283. step_info[kTagId] = tag_id;
  284. step_info[kTaskId] = task_id;
  285. step_info[kStreamId] = stream_id;
  286. step_info[kThreadId] = mmGetTid();
  287. std::string reported_data;
  288. try {
  289. reported_data = step_info.dump(kInteval, ' ', false, Json::error_handler_t::ignore);
  290. } catch (std::exception &e) {
  291. GELOGE(FAILED, "Failed to convert JSON to string, reason: %s.", e.what());
  292. GELOGE(FAILED, "[Convert][ReportedData]Failed to convert from json to string, reason: %s",
  293. e.what());
  294. REPORT_CALL_ERROR("E19999", "Failed to convert reported data from json to string, reason: %s",
  295. e.what());
  296. } catch (...) {
  297. GELOGE(FAILED, "[Convert][ReportedData]Failed to convert from json to string");
  298. REPORT_CALL_ERROR("E19999", "Failed to convert reported data from json to string");
  299. }
  300. reported_data.append(",")
  301. .append("\n");
  302. ReportData(device_id, reported_data, "step_info");
  303. #endif
  304. return SUCCESS;
  305. }
  306. void ProfilingManager::ReportData(const int32_t &device_id, const string &data, const string &tag_name) {
  307. #ifdef DAVINCI_SUPPORT_PROFILING
  308. ReporterData reporter_data{};
  309. int ret = -1;
  310. int32_t cb_ret = -1;
  311. size_t report_max_len = reporter_max_len_;
  312. size_t index = data.size() / report_max_len;
  313. if (index >= 1) {
  314. reporter_data.deviceId = device_id;
  315. ret = memcpy_s(reporter_data.tag, MSPROF_ENGINE_MAX_TAG_LEN + 1, tag_name.c_str(), tag_name.size());
  316. GE_IF_BOOL_EXEC(ret != EOK, GELOGE(ret, "Report data tag [%s] memcpy error!", tag_name.c_str()); return;);
  317. std::lock_guard<std::mutex> lock(mutex_report_);
  318. for (size_t i = 0; i < index; ++i) {
  319. reporter_data.data = (unsigned char *)data.c_str() + report_max_len * i;
  320. reporter_data.dataLen = report_max_len;
  321. cb_ret = CallMsprofReport(reporter_data);
  322. GE_IF_BOOL_EXEC(cb_ret != 0, GELOGE(cb_ret, "Reporter data [%s] failed, ret:%d", tag_name.c_str(), cb_ret);
  323. return;);
  324. }
  325. reporter_data.dataLen = data.size() - report_max_len * index;
  326. if (reporter_data.dataLen != 0) {
  327. reporter_data.data = (unsigned char *)data.c_str() + report_max_len * index;
  328. cb_ret = CallMsprofReport(reporter_data);
  329. GE_IF_BOOL_EXEC(cb_ret != 0, GELOGE(cb_ret, "Reporter data [%s] failed, ret:%d", tag_name.c_str(), cb_ret);
  330. return;);
  331. }
  332. } else {
  333. reporter_data.deviceId = device_id;
  334. reporter_data.data = (unsigned char *)data.c_str();
  335. reporter_data.dataLen = data.size();
  336. ret = memcpy_s(reporter_data.tag, MSPROF_ENGINE_MAX_TAG_LEN + 1, tag_name.c_str(), tag_name.size());
  337. GE_IF_BOOL_EXEC(ret != EOK, GELOGE(ret, "Report data tag [%s] memcpy error!", tag_name.c_str()); return;);
  338. std::lock_guard<std::mutex> lock(mutex_report_);
  339. cb_ret = CallMsprofReport(reporter_data);
  340. GE_IF_BOOL_EXEC(cb_ret != 0, GELOGE(cb_ret, "Reporter data [%s] failed, ret:%d", tag_name.c_str(), cb_ret);
  341. return;);
  342. }
  343. #endif
  344. }
  345. void ProfilingManager::ReportProfilingData(uint32_t model_id, const std::vector<TaskDescInfo> &task_desc_info) {
  346. #ifdef DAVINCI_SUPPORT_PROFILING
  347. int32_t logic_device_id = 0;
  348. rtError_t rt_ret = rtGetDevice(&logic_device_id);
  349. if (rt_ret != RT_ERROR_NONE) {
  350. GELOGE(rt_ret, "[Get][LogicDeviceId]Failed, ret 0x%X", rt_ret);
  351. REPORT_CALL_ERROR("E19999", "Get logic device id failed, ret 0x%X", rt_ret);
  352. return;
  353. }
  354. GELOGD("current logic_device_id:%d", logic_device_id);
  355. GELOGD("start ProfilingTaskDescInfo.");
  356. ProfilingTaskDescInfo(model_id, task_desc_info, logic_device_id);
  357. GELOGD("Report profiling data for GE end.");
  358. #endif
  359. }
  360. uint64_t ProfilingManager::GetProfilingModule() {
  361. uint64_t module = PROF_MODEL_EXECUTE_MASK |
  362. PROF_RUNTIME_API_MASK |
  363. PROF_RUNTIME_TRACE_MASK |
  364. PROF_SCHEDULE_TIMELINE_MASK |
  365. PROF_SCHEDULE_TRACE_MASK |
  366. PROF_TASK_TIME_MASK |
  367. PROF_SUBTASK_TIME_MASK |
  368. PROF_AICPU_TRACE_MASK |
  369. PROF_AICORE_METRICS_MASK |
  370. PROF_AIVECTORCORE_METRICS_MASK |
  371. PROF_MODEL_LOAD_MASK;
  372. return module;
  373. }
  374. void ProfilingManager::UpdateSubscribeDeviceModuleMap(std::string prof_type, uint32_t device_id, uint64_t module) {
  375. #ifdef DAVINCI_SUPPORT_PROFILING
  376. if (prof_type == kProfModelSubscribe) {
  377. if (subs_dev_module_.find(device_id) != subs_dev_module_.end()) {
  378. subs_dev_module_[device_id].subscribe_count++;
  379. } else {
  380. DeviceSubsInfo dev_info;
  381. dev_info.module = module;
  382. dev_info.subscribe_count = 1;
  383. subs_dev_module_[device_id] = dev_info;
  384. }
  385. } else if (prof_type == kProfModelUnsubscribe) {
  386. auto iter = subs_dev_module_.find(device_id);
  387. if (iter != subs_dev_module_.end()) {
  388. if (iter->second.subscribe_count > 0) {
  389. iter->second.subscribe_count--;
  390. }
  391. if (iter->second.subscribe_count == 0) {
  392. subs_dev_module_.erase(iter);
  393. }
  394. }
  395. } else {
  396. GELOGI("No need to update device_id module map.");
  397. }
  398. #endif
  399. }
  400. Status ProfilingManager::ProfModelSubscribe(uint64_t module, void *model) {
  401. #ifdef DAVINCI_SUPPORT_PROFILING
  402. std::lock_guard<std::mutex> lock(mutex_);
  403. uint64_t model_load_mask = module & PROF_MODEL_LOAD_MASK;
  404. if ((subscribe_count_ == 0) && (model_load_mask == PROF_MODEL_LOAD_MASK)) {
  405. // register framework to profiling
  406. // register Framework to profiling
  407. int32_t cb_ret = PluginInit();
  408. if (cb_ret != 0) {
  409. GELOGE(cb_ret, "[Init][ProfilingPlugin]Failed, ret %d", cb_ret);
  410. REPORT_CALL_ERROR("E19999", "Init profiling plugin failed, ret %d", cb_ret);
  411. return cb_ret;
  412. }
  413. GELOGI("Prof subscribe: model load profiling on.");
  414. }
  415. subscribe_count_++;
  416. auto davinci_model = static_cast<DavinciModel *>(model);
  417. int32_t device_num = 1;
  418. uint32_t device[1];
  419. device[0] = davinci_model->GetDeviceId();
  420. rtError_t rt_ret = rtProfilerStart(module, device_num, device);
  421. if (rt_ret != RT_ERROR_NONE) {
  422. GELOGE(FAILED, "[Start][Profiler]Malloc buffer failed, ret 0x%X", rt_ret);
  423. REPORT_CALL_ERROR("E19999", "Malloc buffer failed when start profiling, ret 0x%X", rt_ret);
  424. return FAILED;
  425. }
  426. UpdateSubscribeDeviceModuleMap(kProfModelSubscribe, device[0], module);
  427. // Report profiling data
  428. Status p_ret = davinci_model->ReportProfilingData();
  429. if (p_ret != SUCCESS) {
  430. GELOGE(p_ret, "[Report][ProfilingData]Failed, ret %u", p_ret);
  431. REPORT_CALL_ERROR("E19999", "Report profiling data failed, ret %u", p_ret);
  432. return p_ret;
  433. }
  434. #endif
  435. return SUCCESS;
  436. }
  437. Status ProfilingManager::ProfModelUnsubscribe(void *model) {
  438. #ifdef DAVINCI_SUPPORT_PROFILING
  439. std::lock_guard<std::mutex> lock(mutex_);
  440. if (subscribe_count_ == 0) {
  441. GELOGW("The profiler has not been subscribed, you do not need to cannel the subscription.");
  442. return SUCCESS;
  443. }
  444. auto davinci_model = static_cast<DavinciModel *>(model);
  445. int32_t dev_num = 1;
  446. uint32_t device[1];
  447. device[0] = davinci_model->GetDeviceId();
  448. auto iter = subs_dev_module_.find(device[0]);
  449. if (iter != subs_dev_module_.end()) {
  450. if (subs_dev_module_[device[0]].subscribe_count == 1) {
  451. // The same device_id, only stop at last time
  452. rtError_t rt_ret = rtProfilerStop(subs_dev_module_[device[0]].module, dev_num, device);
  453. if (rt_ret != RT_ERROR_NONE) {
  454. GELOGE(FAILED, "[Stop][Profiler]Malloc buffer Failed, ret %d", rt_ret);
  455. REPORT_CALL_ERROR("E19999", "Malloc buffer failed when stop profiling, ret %d", rt_ret);
  456. return FAILED;
  457. }
  458. }
  459. UpdateSubscribeDeviceModuleMap(kProfModelUnsubscribe, device[0], subs_dev_module_[device[0]].module);
  460. } else {
  461. GELOGE(FAILED, "[Cancel][DeviceId]The device_id %u has not been subscribed, "
  462. "do not need to cancel", device[0]);
  463. REPORT_CALL_ERROR("E19999", "The device_id %u has not been subscribed, do not need to cancel",
  464. device[0]);
  465. return FAILED;
  466. }
  467. subscribe_count_--;
  468. if (subscribe_count_ == 0) {
  469. // profiling plugin uninit at last subscription
  470. PluginUnInit();
  471. }
  472. #endif
  473. return SUCCESS;
  474. }
  475. Status ProfilingManager::ProfInit(uint64_t module) {
  476. #ifdef DAVINCI_SUPPORT_PROFILING
  477. std::lock_guard<std::mutex> lock(mutex_);
  478. uint64_t model_load_mask = module & PROF_MODEL_LOAD_MASK;
  479. if (model_load_mask == PROF_MODEL_LOAD_MASK) {
  480. // register Framework to profiling
  481. int32_t cb_ret = PluginInit();
  482. if (cb_ret != 0) {
  483. GELOGE(cb_ret, "[Init][ProfilingPlugin]Failed, ret %d", cb_ret);
  484. REPORT_CALL_ERROR("E19999", "Init profiling plugin failed, ret %d", cb_ret);
  485. return cb_ret;
  486. }
  487. int32_t device_num = -1;
  488. rtError_t rt_ret = rtProfilerStart(model_load_mask, device_num, nullptr);
  489. if (rt_ret != RT_ERROR_NONE) {
  490. GELOGE(FAILED, "[Start][Profiler]Malloc buffer failed, ret 0x%X", rt_ret);
  491. REPORT_CALL_ERROR("E19999", "Malloc buffer failed when start profiling, ret 0x%X", rt_ret);
  492. return FAILED;
  493. }
  494. is_load_profiling_ = true;
  495. GELOGI("Prof init: model load profiling on.");
  496. }
  497. uint64_t training_trace_mask = module & PROF_TRAINING_TRACE_MASK;
  498. if (training_trace_mask == PROF_TRAINING_TRACE_MASK) {
  499. is_training_trace_ = true;
  500. }
  501. GELOGI("Prof init success.");
  502. #endif
  503. return SUCCESS;
  504. }
  505. Status ProfilingManager::ProfFinalize() {
  506. #ifdef DAVINCI_SUPPORT_PROFILING
  507. std::lock_guard<std::mutex> lock(mutex_);
  508. is_load_profiling_ = false;
  509. is_training_trace_ = false;
  510. is_execute_profiling_ = false;
  511. index_id_ = UINT64_MAX;
  512. // profiling plugin uninit
  513. PluginUnInit();
  514. CleanSubscribeInfo();
  515. int32_t dev_num = -1;
  516. rtError_t rt_ret = rtProfilerStop(PROF_MODEL_LOAD_MASK, dev_num, nullptr);
  517. if (rt_ret != RT_ERROR_NONE) {
  518. GELOGE(FAILED, "[Stop][Profiler]Malloc buffer failed, ret 0x%X", rt_ret);
  519. REPORT_CALL_ERROR("E19999", "Malloc buffer failed when stop profiling, ret 0x%X", rt_ret);
  520. return FAILED;
  521. }
  522. for (auto device_id_module : device_id_module_map_) {
  523. if (device_id_module.second != 0) {
  524. uint32_t device_id = static_cast<uint32_t>(device_id_module.first);
  525. GELOGI("Prof finalize: device_id: %u, module: 0x%lx.", device_id, device_id_module.second);
  526. rt_ret = rtProfilerStop(device_id_module.second, 1, &device_id);
  527. if (rt_ret != RT_ERROR_NONE) {
  528. GELOGE(FAILED, "[Stop][Profiler]Failed, device_id %d, ret 0x%X", device_id, rt_ret);
  529. REPORT_CALL_ERROR("E19999", "Stop runtime profiler failed, device_id %d, ret 0x%X",
  530. device_id,rt_ret);
  531. return FAILED;
  532. }
  533. }
  534. }
  535. device_id_module_map_.clear();
  536. device_id_.clear();
  537. device_id_map_.clear();
  538. model_id_map_.clear();
  539. GELOGI("Prof finalize success.");
  540. #endif
  541. return SUCCESS;
  542. }
  543. Status ProfilingManager::ProfParseDeviceId(const std::map<std::string, std::string> &config_para,
  544. vector<int32_t> &device_list) {
  545. #ifdef DAVINCI_SUPPORT_PROFILING
  546. auto iter = config_para.find(kConfigDevIdList);
  547. if (iter != config_para.end()) {
  548. std::string device_id_list = iter->second;
  549. std::string temp;
  550. vector<std::string> decvice_id;
  551. for (uint32_t i = 0; i < device_id_list.size(); i++) {
  552. if (isdigit(device_id_list[i])) {
  553. temp.append(1, device_id_list[i]);
  554. } else {
  555. if (!temp.empty()) {
  556. decvice_id.emplace_back(temp);
  557. }
  558. temp.clear();
  559. }
  560. }
  561. if (!temp.empty()) {
  562. decvice_id.emplace_back(temp);
  563. }
  564. for (uint32_t i = 0; i < decvice_id.size(); i++) {
  565. try {
  566. int32_t dev_id = std::stoi(decvice_id[i]);
  567. device_list.push_back(dev_id);
  568. } catch (std::invalid_argument &) {
  569. GELOGE(FAILED, "[Parse][DeviceId]Failed, it is invalid, %s", decvice_id[i].c_str());
  570. REPORT_CALL_ERROR("E19999", "Parse device id %s failed, it is invalid",
  571. decvice_id[i].c_str());
  572. return FAILED;
  573. } catch (std::out_of_range &) {
  574. GELOGE(FAILED, "[Parse][DeviceId]Failed, it is out of range, %s", decvice_id[i].c_str());
  575. REPORT_CALL_ERROR("E19999", "Parse device id %s failed, it is out of range",
  576. decvice_id[i].c_str());
  577. return FAILED;
  578. } catch (...) {
  579. GELOGE(FAILED, "[Parse][DeviceId]Faield, it cannot change to int, %s",
  580. decvice_id[i].c_str());
  581. REPORT_CALL_ERROR("E19999", "Parse device id %s failed, it cannot change to int",
  582. decvice_id[i].c_str());
  583. return FAILED;
  584. }
  585. }
  586. } else {
  587. GELOGE(FAILED, "[Parse][DeviceId]Config para not contain device id list");
  588. REPORT_CALL_ERROR("E19999", "Parse device id failed, config para not contain device id list");
  589. return FAILED;
  590. }
  591. #endif
  592. return SUCCESS;
  593. }
  594. Status ProfilingManager::ProfParseParam(const std::map<std::string, std::string> &config_para, int32_t &device_num,
  595. vector<int32_t> &device_list) {
  596. #ifdef DAVINCI_SUPPORT_PROFILING
  597. // device num
  598. auto iter = config_para.find(kConfigNumsdev);
  599. if (iter != config_para.end()) {
  600. try {
  601. device_num = std::stoi(iter->second);
  602. } catch (std::invalid_argument &) {
  603. GELOGE(FAILED, "[Parse][Param]Failed, device num %s is invalid", iter->second.c_str());
  604. REPORT_CALL_ERROR("E19999", "Parse param failed, device num %s is invalid",
  605. iter->second.c_str());
  606. return FAILED;
  607. } catch (std::out_of_range &) {
  608. GELOGE(FAILED, "[Parse][Param]Failed, device num %s cannot change to int",
  609. iter->second.c_str());
  610. REPORT_CALL_ERROR("E19999", "Parse param failed, device num %s cannot change to int",
  611. iter->second.c_str());
  612. return FAILED;
  613. } catch (...) {
  614. GELOGE(FAILED, "[Parse][Param]Failed, device num %s cannot change to int",
  615. iter->second.c_str());
  616. REPORT_CALL_ERROR("E19999", "Parse param failed, device num %s cannot change to int",
  617. iter->second.c_str());
  618. return FAILED;
  619. }
  620. } else {
  621. GELOGE(FAILED, "[Parse][Param]Config para not contain device num %s", iter->second.c_str());
  622. REPORT_CALL_ERROR("E19999", "Parse param failed, config para not contain device num %s",
  623. iter->second.c_str());
  624. return FAILED;
  625. }
  626. // device id
  627. if (ProfParseDeviceId(config_para, device_list) != SUCCESS) {
  628. GELOGE(FAILED, "[Parse][DeviceId]Failed");
  629. REPORT_CALL_ERROR("E19999", "Parse device id failed");
  630. return FAILED;
  631. }
  632. if (device_num == 0 || device_num > kMaxDeviceNum || device_num != static_cast<int32_t>(device_list.size())) {
  633. GELOGE(FAILED, "[Parse][Param]Failed, config para device num %d not equal to "
  634. "device list size %zu", device_num, device_list.size());
  635. REPORT_INNER_ERROR("E19999", "[Parse][Param]Failed, config para device num %d "
  636. "not equal to device list size %zu", device_num, device_list.size());
  637. return FAILED;
  638. }
  639. #endif
  640. return SUCCESS;
  641. }
  642. Status ProfilingManager::ProfStartProfiling(uint64_t module, const std::map<std::string, std::string> &config_para) {
  643. #ifdef DAVINCI_SUPPORT_PROFILING
  644. std::lock_guard<std::mutex> lock(mutex_);
  645. uint64_t training_trace_mask = module & PROF_TRAINING_TRACE_MASK;
  646. if (training_trace_mask == PROF_TRAINING_TRACE_MASK) {
  647. is_training_trace_ = true;
  648. }
  649. int32_t device_num = 0;
  650. vector<int32_t> device_list;
  651. if (ProfParseParam(config_para, device_num, device_list) != SUCCESS) {
  652. GELOGE(FAILED, "[Parse][Param]Prof start parse param failed, device num %d, "
  653. "device list size %zu", device_num, device_list.size());
  654. REPORT_CALL_ERROR("E19999", "Prof start parse param failed, device num %d, "
  655. "device list size %zu", device_num, device_list.size());
  656. return FAILED;
  657. }
  658. auto device_id_ptr = std::unique_ptr<uint32_t[]>(new (std::nothrow) uint32_t[device_num]);
  659. if (device_id_ptr == nullptr) {
  660. GELOGE(FAILED, "[Start][Profiling]Malloc buffer failed when start profiling, device num %d",
  661. device_num);
  662. REPORT_CALL_ERROR("E19999", "Malloc buffer failed when start profiling, device num %d",
  663. device_num);
  664. return FAILED;
  665. }
  666. for (int32_t i = 0; i < device_num; i++) {
  667. device_id_ptr[i] = static_cast<uint32_t>(device_list[i]);
  668. }
  669. GELOGI("Runtime config param: 0x%lx, device num: %d.", module, device_num);
  670. rtError_t rt_ret = rtProfilerStart(module, device_num, device_id_ptr.get());
  671. if (rt_ret != RT_ERROR_NONE) {
  672. GELOGE(FAILED, "[Start][Profiler]Runtime profiler config proc failed, config param 0x%lx, "
  673. "device num %d, ret 0x%X", module, device_num, rt_ret);
  674. REPORT_CALL_ERROR("E19999", "Runtime profiler config proc failed, config param 0x%lx, "
  675. "device num %d, ret 0x%X", module, device_num, rt_ret);
  676. return FAILED;
  677. }
  678. if ((module & PROF_MODEL_EXECUTE_MASK) == PROF_MODEL_EXECUTE_MASK) {
  679. for (int32_t i = 0; i < device_num; i++) {
  680. if (std::find(device_id_.begin(), device_id_.end(), device_list[i]) == device_id_.end()) {
  681. device_id_.push_back(device_list[i]);
  682. }
  683. }
  684. GELOGI("Prof start: ge execute model start profiling.");
  685. }
  686. if ((module & PROF_MODEL_LOAD_MASK) == PROF_MODEL_LOAD_MASK) {
  687. GELOGW("Prof start: load model module is invalid.");
  688. }
  689. UpdateDeviceIdModuleMap(kProfStart, module, device_list);
  690. GELOGI("Prof start profiling success.");
  691. #endif
  692. return SUCCESS;
  693. }
  694. Status ProfilingManager::ProfStopProfiling(uint64_t module, const std::map<std::string, std::string> &config_para) {
  695. #ifdef DAVINCI_SUPPORT_PROFILING
  696. std::lock_guard<std::mutex> lock(mutex_);
  697. int32_t device_num = 0;
  698. vector<int32_t> device_list;
  699. if (ProfParseParam(config_para, device_num, device_list) != SUCCESS) {
  700. GELOGE(FAILED, "[Stop][Profiling]Prof stop parse param failed, device num %d, "
  701. "device list size %zu", device_num, device_list.size());
  702. REPORT_CALL_ERROR("E19999", "Prof stop parse param failed, device num %d, device list size %zu",
  703. device_num, device_list.size());
  704. return FAILED;
  705. }
  706. auto device_id_ptr = std::unique_ptr<uint32_t[]>(new (std::nothrow) uint32_t[device_num]);
  707. if (device_id_ptr == nullptr) {
  708. GELOGE(FAILED, "[Stop][Profiling]Malloc buffer failed when stop profiling, device num %d",
  709. device_num);
  710. REPORT_CALL_ERROR("E19999", "Malloc buffer failed when stop profiling, device num %d",
  711. device_num);
  712. return FAILED;
  713. }
  714. for (int32_t i = 0; i < device_num; i++) {
  715. device_id_ptr[i] = static_cast<uint32_t>(device_list[i]);
  716. }
  717. GELOGI("Prof stop: runtime config param: 0x%lx, device num: %d", module, device_num);
  718. rtError_t rt_ret = rtProfilerStop(module, device_num, device_id_ptr.get());
  719. if (rt_ret != RT_ERROR_NONE) {
  720. GELOGE(FAILED, "[Stop][Profiler]Runtime profiler config proc failed, config param 0x%lx, "
  721. "device num: %d, ret 0x%X", module, device_num, rt_ret);
  722. REPORT_CALL_ERROR("E19999", "Runtime profiler config proc failed, config param 0x%lx, "
  723. "device num %d, ret 0x%X", module, device_num, rt_ret);
  724. return FAILED;
  725. }
  726. uint64_t execute_model_mask = module & PROF_MODEL_EXECUTE_MASK;
  727. if (execute_model_mask == PROF_MODEL_EXECUTE_MASK) {
  728. for (int32_t i = 0; i < device_num; i++) {
  729. auto iter = std::find(device_id_.begin(), device_id_.end(), device_list[i]);
  730. if (iter != device_id_.end()) {
  731. device_id_.erase(iter);
  732. }
  733. }
  734. GELOGI("Prof stop: ge execute model stop profiling.");
  735. }
  736. if ((module & PROF_MODEL_LOAD_MASK) == PROF_MODEL_LOAD_MASK) {
  737. GELOGW("Prof stop: load model module is invalid.");
  738. }
  739. UpdateDeviceIdModuleMap(kProfStop, module, device_list);
  740. GELOGI("Prof stop profiling success.");
  741. #endif
  742. return SUCCESS;
  743. }
  744. void ProfilingManager::UpdateDeviceIdModuleMap(string prof_type, uint64_t module, const vector<int32_t> &device_list) {
  745. #ifdef DAVINCI_SUPPORT_PROFILING
  746. if (prof_type == kProfStart) {
  747. for (uint32_t i = 0; i < device_list.size(); i++) {
  748. auto iter = device_id_module_map_.find(device_list[i]);
  749. if (iter != device_id_module_map_.end()) {
  750. uint64_t prof_on_module = device_id_module_map_[device_list[i]];
  751. // save all profiling on module of device
  752. device_id_module_map_[device_list[i]] = prof_on_module | module;
  753. } else {
  754. device_id_module_map_[device_list[i]] = module;
  755. }
  756. }
  757. } else if (prof_type == kProfStop) {
  758. for (uint32_t i = 0; i < device_list.size(); i++) {
  759. auto iter = device_id_module_map_.find(device_list[i]);
  760. if (iter != device_id_module_map_.end()) {
  761. uint64_t prof_on_module = device_id_module_map_[device_list[i]];
  762. uint64_t prof_off_module = prof_on_module & module;
  763. uint64_t prof_on_left_module = prof_on_module & (~prof_off_module);
  764. // stop profiling on module of device
  765. device_id_module_map_[device_list[i]] = prof_on_left_module;
  766. }
  767. }
  768. } else {
  769. GELOGI("No need to update device_id module map.");
  770. }
  771. #endif
  772. }
  773. bool ProfilingManager::ProfilingModelExecuteOn() const {
  774. int32_t logic_device_id = 0;
  775. rtError_t rt_ret = rtGetDevice(&logic_device_id);
  776. if (rt_ret != RT_ERROR_NONE) {
  777. GELOGE(rt_ret, "[Get][LogicDeviceId]Failed, ret 0x%X", rt_ret);
  778. REPORT_CALL_ERROR("E19999", "Get logic device id failed, ret 0x%X", rt_ret);
  779. }
  780. GELOGI("Current logic_device_id:%d", logic_device_id);
  781. bool execute_model_prof_on = false;
  782. auto iter = std::find(device_id_.begin(), device_id_.end(), logic_device_id);
  783. if (iter != device_id_.end()) {
  784. execute_model_prof_on = true;
  785. }
  786. GELOGI("Flag is_execute_profiling: %d, execute_model_prof_on: %d", is_execute_profiling_, execute_model_prof_on);
  787. return execute_model_prof_on;
  788. }
  789. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::PluginInit() {
  790. if (reporter_callback_ == nullptr) {
  791. GELOGE(ge::PARAM_INVALID, "[Check][Param]MsprofReporterCallback callback is nullptr");
  792. REPORT_INNER_ERROR("E19999", "MsprofReporterCallback callback is nullptr");
  793. return ge::PARAM_INVALID;
  794. }
  795. int32_t cb_ret = reporter_callback_(
  796. static_cast<uint32_t>(MsprofReporterModuleId::MSPROF_MODULE_FRAMEWORK),
  797. static_cast<uint32_t>(MsprofReporterCallbackType::MSPROF_REPORTER_INIT),
  798. nullptr, 0);
  799. if (cb_ret != MSPROF_ERROR_NONE) {
  800. REPORT_CALL_ERROR("E19999", "Profiling reporter init failed, ret 0x%X", cb_ret);
  801. GELOGE(INTERNAL_ERROR, "[Init][ProfilingReporter]Failed, ret 0x%X", cb_ret);
  802. return INTERNAL_ERROR;
  803. }
  804. cb_ret = reporter_callback_(
  805. static_cast<uint32_t>(MsprofReporterModuleId::MSPROF_MODULE_FRAMEWORK),
  806. static_cast<uint32_t>(MsprofReporterCallbackType::MSPROF_REPORTER_DATA_MAX_LEN),
  807. &reporter_max_len_, sizeof(uint32_t));
  808. if (cb_ret != MSPROF_ERROR_NONE) {
  809. REPORT_CALL_ERROR("E19999", "Get profiling reporter data max len failed, ret 0x%X", cb_ret);
  810. GELOGE(INTERNAL_ERROR, "[Get][ProfilingDataMaxLen]Failed, ret 0x%X", cb_ret);
  811. return INTERNAL_ERROR;
  812. }
  813. return SUCCESS;
  814. }
  815. void ProfilingManager::PluginUnInit() const {
  816. #ifdef DAVINCI_SUPPORT_PROFILING
  817. if (reporter_callback_ == nullptr) {
  818. GELOGE(ge::PARAM_INVALID, "[Check][Param]MsprofReporterCallback callback is nullptr");
  819. REPORT_INNER_ERROR("E19999", "MsprofReporterCallback callback is nullptr");
  820. return;
  821. }
  822. int32_t cb_ret = reporter_callback_(
  823. static_cast<uint32_t>(MsprofReporterModuleId::MSPROF_MODULE_FRAMEWORK),
  824. static_cast<uint32_t>(MsprofReporterCallbackType::MSPROF_REPORTER_UNINIT),
  825. nullptr, 0);
  826. if (cb_ret != 0) {
  827. GELOGW("profiling plugin uninit failed, ret:%d", cb_ret);
  828. }
  829. #endif
  830. }
  831. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::CallMsprofReport(
  832. ReporterData &reporter_data) const {
  833. if (reporter_callback_ == nullptr) {
  834. GELOGE(ge::PARAM_INVALID, "[Check][Param]MsprofReporterCallback callback is nullptr");
  835. REPORT_INNER_ERROR("E19999", "MsprofReporterCallback callback is nullptr");
  836. return ge::PARAM_INVALID;
  837. }
  838. return reporter_callback_(
  839. static_cast<uint32_t>(MsprofReporterModuleId::MSPROF_MODULE_FRAMEWORK),
  840. static_cast<uint32_t>(MsprofReporterCallbackType::MSPROF_REPORTER_REPORT),
  841. static_cast<void *>(&reporter_data), sizeof(ReporterData));
  842. }
  843. void ProfilingManager::GetOpInputInfo(const OpDescPtr &op, TaskDescInfo &task_desc_info) const {
  844. std::vector<Format> input_format;
  845. std::vector<std::vector<int64_t>> input_shape;
  846. std::vector<DataType> input_data_type;
  847. for (size_t i = 0; i < op->GetAllInputsSize(); ++i) {
  848. GeTensorDescPtr input_tensor_desc = op->MutableInputDesc(i);
  849. if (input_tensor_desc == nullptr) {
  850. continue;
  851. }
  852. input_format.emplace_back(input_tensor_desc->GetFormat());
  853. input_shape.emplace_back(input_tensor_desc->GetShape().GetDims());
  854. input_data_type.emplace_back(input_tensor_desc->GetDataType());
  855. }
  856. std::vector<Format> format_default = { FORMAT_NULL };
  857. std::vector<std::vector<int64_t>> shape_default = { {0} };
  858. std::vector<DataType> data_type_default = { DT_UNDEFINED };
  859. task_desc_info.input_format = input_format.empty() ? format_default : input_format;
  860. task_desc_info.input_shape = input_shape.empty() ? shape_default : input_shape;
  861. task_desc_info.input_data_type = input_data_type.empty() ? data_type_default : input_data_type;
  862. }
  863. void ProfilingManager::GetOpOutputInfo(const OpDescPtr &op, TaskDescInfo &task_desc_info) const {
  864. std::vector<Format> output_format;
  865. std::vector<std::vector<int64_t>> output_shape;
  866. std::vector<DataType> output_data_type;
  867. for (size_t j = 0; j < op->GetOutputsSize(); ++j) {
  868. GeTensorDescPtr output_tensor_desc = op->MutableOutputDesc(j);
  869. if (output_tensor_desc == nullptr) {
  870. continue;
  871. }
  872. output_format.emplace_back(output_tensor_desc->GetFormat());
  873. output_shape.emplace_back(output_tensor_desc->GetShape().GetDims());
  874. output_data_type.emplace_back(output_tensor_desc->GetDataType());
  875. }
  876. std::vector<Format> format_default = { FORMAT_NULL };
  877. std::vector<std::vector<int64_t>> shape_default = { {0} };
  878. std::vector<DataType> data_type_default = { DT_UNDEFINED };
  879. task_desc_info.output_format = output_format.empty() ? format_default : output_format;
  880. task_desc_info.output_shape = output_shape.empty() ? shape_default : output_shape;
  881. task_desc_info.output_data_type = output_data_type.empty() ? data_type_default : output_data_type;
  882. }
  883. void ProfilingManager::GetOpInputOutputInfo(const OpDescPtr &op, TaskDescInfo &task_desc_info) const {
  884. GetOpInputInfo(op, task_desc_info);
  885. GetOpOutputInfo(op, task_desc_info);
  886. }
  887. void ProfilingManager::GetFpBpPoint(std::string &fp_point, std::string &bp_point) {
  888. // Env or options mode, fp_point_/bp_point_ have initiliazed on profiling init
  889. if (!fp_point_.empty() && !bp_point_.empty()) {
  890. fp_point = fp_point_;
  891. bp_point = bp_point_;
  892. GELOGI("Bp Fp have been initialized in env or options. bp_point: %s, fp_point: %s", bp_point.c_str(),
  893. fp_point.c_str());
  894. return;
  895. }
  896. // ProfApi mode and training trace is set
  897. // Parse options first
  898. char env_profiling_options[MSPROF_OPTIONS_DEF_LEN_MAX] = {0x00};
  899. bool is_profiling_valid = false;
  900. std::string profiling_options;
  901. if (ge::GetContext().GetOption(OPTION_EXEC_PROFILING_OPTIONS, profiling_options) == SUCCESS &&
  902. !profiling_options.empty()) {
  903. is_profiling_valid = true;
  904. } else {
  905. INT32 ret = mmGetEnv("PROFILING_OPTIONS", env_profiling_options, MSPROF_OPTIONS_DEF_LEN_MAX);
  906. if (ret != EN_OK) {
  907. GELOGI("PROFILING_OPTIONS env is not exist.");
  908. return;
  909. }
  910. GELOGI("Parse env PROFILING_OPTIONS:%s.", env_profiling_options);
  911. profiling_options = env_profiling_options;
  912. is_profiling_valid = true;
  913. }
  914. if (is_profiling_valid) {
  915. try {
  916. Json prof_options = Json::parse(profiling_options);
  917. if (prof_options.contains(kFpPoint)) {
  918. fp_point_ = prof_options[kFpPoint];
  919. }
  920. if (prof_options.contains(kBpPoint)) {
  921. bp_point_ = prof_options[kBpPoint];
  922. }
  923. fp_point = fp_point_;
  924. bp_point = bp_point_;
  925. if (!fp_point_.empty() && !bp_point_.empty()) {
  926. GELOGI("Training trace bp fp is set, bp_point:%s, fp_point:%s.", bp_point_.c_str(), fp_point_.c_str());
  927. }
  928. } catch (...) {
  929. GELOGW("Json prof options is invalid.");
  930. return;
  931. }
  932. }
  933. return;
  934. }
  935. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::GetDeviceIdFromGraph(
  936. uint32_t graph_id, uint32_t &device_id) {
  937. auto iter = device_id_map_.find(graph_id);
  938. if (iter != device_id_map_.end()) {
  939. device_id = iter->second;
  940. return SUCCESS;
  941. }
  942. REPORT_CALL_ERROR("E19999", "graph_id:%u does not exist!", graph_id);
  943. GELOGE(PARAM_INVALID, "[Check][GraphId]graph_id:%u does not exist!", graph_id);
  944. return FAILED;
  945. }
  946. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void ProfilingManager::SetSubscribeInfo(
  947. uint64_t prof_switch, uint32_t model_id, bool is_subscribe) {
  948. subscribe_info_.is_subscribe = is_subscribe;
  949. subscribe_info_.prof_switch = prof_switch;
  950. subscribe_info_.graph_id = model_id;
  951. }
  952. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void ProfilingManager::CleanSubscribeInfo() {
  953. subscribe_info_.is_subscribe = false;
  954. subscribe_info_.prof_switch = 0;
  955. subscribe_info_.graph_id = 0;
  956. }
  957. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::GetModelIdFromGraph(
  958. uint32_t graph_id, uint32_t &model_id) {
  959. auto iter = model_id_map_.find(graph_id);
  960. if (iter != model_id_map_.end()) {
  961. model_id = iter->second;
  962. return SUCCESS;
  963. }
  964. REPORT_CALL_ERROR("E19999", "graph_id:%u does not exist!", graph_id);
  965. GELOGE(PARAM_INVALID, "[Check][GraphId]graph_id:%u does not exist!", graph_id);
  966. return FAILED;
  967. }
  968. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::SetDeviceByModelId(
  969. uint32_t model_id, uint32_t &device_id) {
  970. auto ret = rtSetDeviceIdByModelIdx(model_id, device_id);
  971. if (ret != RT_ERROR_NONE) {
  972. REPORT_CALL_ERROR("E19999", "set device id by model_id:%u failed!", model_id);
  973. GELOGE(FAILED, "[Check][ModelId]set device id by model_id:%u failed!", model_id);
  974. return FAILED;
  975. }
  976. return SUCCESS;
  977. }
  978. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::UnsetDeviceByModelId(
  979. uint32_t model_id, uint32_t &device_id) {
  980. auto ret = rtUnsetDeviceIdByModelIdx(model_id, device_id);
  981. if (ret != RT_ERROR_NONE) {
  982. REPORT_CALL_ERROR("E19999", "unset device id by model_id:%u failed!", model_id);
  983. GELOGE(FAILED, "[Check][ModelId]unset device id by model_id:%u failed!", model_id);
  984. return FAILED;
  985. }
  986. return SUCCESS;
  987. }
  988. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ProfilingManager::isProfTypeValid(uint32_t type) {
  989. if (type < 0 || type >= kCommandNum) {
  990. GELOGE(ge::PARAM_INVALID, "[Check][Type]Type %u is invalid", type);
  991. return false;
  992. }
  993. GELOGD("Type is %u", type);
  994. return true;
  995. }
  996. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ProfilingManager::isProfConfigValid(
  997. const uint32_t *deviceid_list, uint32_t device_nums) {
  998. if (deviceid_list == nullptr) {
  999. GELOGE(ge::PARAM_INVALID, "[Check][DeviceIDList]Invalid, it is nullptr");
  1000. REPORT_INNER_ERROR("E19999", "Device id list is nullptr");
  1001. return false;
  1002. }
  1003. if (device_nums == 0 || device_nums > kMaxDevNum) {
  1004. GELOGE(ge::PARAM_INVALID, "[Check][DeviceNums]Invalid, device nums: %u", device_nums);
  1005. REPORT_INNER_ERROR("E19999", "DeviceNums %u check invalid", device_nums);
  1006. return false;
  1007. }
  1008. // real device num
  1009. int32_t dev_count = 0;
  1010. rtError_t rt_err = rtGetDeviceCount(&dev_count);
  1011. if (rt_err != RT_ERROR_NONE) {
  1012. GELOGE(ge::INTERNAL_ERROR, "[Get][DeviceCount]Failed, error_code %d", rt_err);
  1013. REPORT_CALL_ERROR("E19999", "Get device count failed, error_code %d", rt_err);
  1014. return false;
  1015. }
  1016. if (device_nums > static_cast<uint32_t>(dev_count)) {
  1017. GELOGE(ge::PARAM_INVALID, "[Check][Param]Device num %u is not in range [1,%d]",
  1018. device_nums, dev_count);
  1019. REPORT_INNER_ERROR("E19999", "Device num %u check invalid, it is not in range [1,%d]",
  1020. device_nums, dev_count);
  1021. return false;
  1022. }
  1023. std::set<uint32_t> record;
  1024. for (size_t i = 0; i < device_nums; ++i) {
  1025. uint32_t dev_id = deviceid_list[i];
  1026. if (dev_id >= static_cast<uint32_t>(dev_count)) {
  1027. GELOGE(ge::PARAM_INVALID, "[Check][DeviceId]Device id %u is not in range [0,%d)",
  1028. dev_id, dev_count);
  1029. REPORT_CALL_ERROR("E19999", "Device id %u is not in range [0,%d)", dev_id, dev_count);
  1030. return false;
  1031. }
  1032. if (record.count(dev_id) > 0) {
  1033. GELOGE(ge::PARAM_INVALID, "[Check][DeviceId]Device id %u is duplicatedly set", dev_id);
  1034. REPORT_CALL_ERROR("E19999", "Device id %u is not unique, duplicatedly set", dev_id);
  1035. return false;
  1036. }
  1037. record.insert(dev_id);
  1038. }
  1039. return true;
  1040. }
  1041. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ProfilingManager::TransProfConfigToParam(
  1042. const rtProfCommandHandle &profCommand, vector<string> &prof_config_params) {
  1043. prof_config_params.clear();
  1044. prof_config_params.emplace_back(kDeviceNums);
  1045. prof_config_params.emplace_back(std::to_string(profCommand.devNums));
  1046. prof_config_params.emplace_back(kDeviceIdList);
  1047. std::string devID = "";
  1048. if (profCommand.devNums == 0) {
  1049. GELOGW("The device num is invalid.");
  1050. return false;
  1051. }
  1052. for (uint32_t i = 0; i < profCommand.devNums; i++) {
  1053. devID.append(std::to_string(profCommand.devList[i]));
  1054. if (i != profCommand.devNums - 1) {
  1055. devID.append(",");
  1056. }
  1057. }
  1058. prof_config_params.push_back(devID);
  1059. return true;
  1060. }
  1061. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status ProfilingManager::NeedUnsubscribe(
  1062. ProfCommandHandleType type, bool is_subscribe, uint32_t graph_id, vector<string> &prof_params) {
  1063. if (type == kProfCommandhandleModelUnsubscribe && is_subscribe) {
  1064. prof_params.clear();
  1065. prof_params.emplace_back(kPofilingModelId);
  1066. uint32_t model_id = 0;
  1067. auto ret = GetModelIdFromGraph(graph_id, model_id);
  1068. if (ret != ge::SUCCESS) {
  1069. GELOGE(ret, "graph_id:%u not not found", graph_id);
  1070. return ret;
  1071. }
  1072. prof_params.emplace_back(std::to_string(model_id));
  1073. }
  1074. return ge::SUCCESS;
  1075. }
  1076. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY rtError_t ProfilingManager::CommandHandle(
  1077. rtProfCtrlType_t rt_type, void *data, uint32_t len) {
  1078. if (data == nullptr) {
  1079. GELOGE(ge::PARAM_INVALID, "The prof comand is invalid.");
  1080. return ge::FAILED;
  1081. }
  1082. if (rt_type == RT_PROF_CTRL_REPORTER) {
  1083. reporter_callback_ = reinterpret_cast<MsprofReporterCallback>(data);
  1084. GELOGD("return with MsprofReporterCallback");
  1085. return ge::SUCCESS;
  1086. }
  1087. else if (rt_type == RT_PROF_CTRL_SWITCH) {
  1088. rtProfCommandHandle_t *prof_config_param = reinterpret_cast<rtProfCommandHandle_t *>(data);
  1089. if (!isProfTypeValid(prof_config_param->type)) {
  1090. GELOGE(ge::PARAM_INVALID, "The prof comand is invalid.");
  1091. return ge::FAILED;
  1092. }
  1093. auto type = static_cast<ProfCommandHandleType>(prof_config_param->type);
  1094. if (type != kProfCommandhandleFinalize) {
  1095. GE_CHECK_NOTNULL(data);
  1096. }
  1097. auto iter = kProfCommandTypeMap.find(type);
  1098. if (iter == kProfCommandTypeMap.end()) {
  1099. GELOGW("The prof comand type is invalid.");
  1100. return ge::PARAM_INVALID;
  1101. }
  1102. std::vector<string> prof_params;
  1103. if (type == kProfCommandhandleStart || type == kProfCommandhandleStop) {
  1104. if (!isProfConfigValid(prof_config_param->devList, prof_config_param->devNums)) {
  1105. return ge::FAILED;
  1106. }
  1107. if (!TransProfConfigToParam(*prof_config_param, prof_params)) {
  1108. GELOGE(ge::PARAM_INVALID, "[Check][Param]Transfer profilerConfig to string vector failed");
  1109. REPORT_CALL_ERROR("E19999", "Transfer profilerConfig to string vector failed");
  1110. return ge::PARAM_INVALID;
  1111. }
  1112. }
  1113. auto is_train = domi::GetContext().train_flag;
  1114. if (type == kProfCommandhandleModelSubscribe && is_train) {
  1115. SetSubscribeInfo(prof_config_param->profSwitch, prof_config_param->modelId, true);
  1116. return ge::SUCCESS;
  1117. }
  1118. auto is_subscribe = subscribe_info_.is_subscribe;
  1119. // GraphId is actually stored in prof_config_param
  1120. auto graph_id = prof_config_param->modelId;
  1121. ge::Status ret = NeedUnsubscribe(type, is_subscribe, graph_id, prof_params);
  1122. if (ret != ge::SUCCESS) {
  1123. GELOGE(ret, "graph_id:%u not not found", graph_id);
  1124. REPORT_INPUT_ERROR("E10001", std::vector<std::string>({"value", "parameter", "reason"}),
  1125. std::vector<std::string>({std::to_string(graph_id),
  1126. "GraphToModelMap",
  1127. "graph_id does not exist!"}));
  1128. return ge::FAILED;
  1129. }
  1130. GraphLoader graph_loader;
  1131. Command command;
  1132. command.cmd_params.clear();
  1133. command.cmd_type = iter->second;
  1134. command.cmd_params = prof_params;
  1135. if (type != kProfCommandhandleFinalize) {
  1136. command.module_index = prof_config_param->profSwitch;
  1137. }
  1138. GELOGI("GE commandhandle execute, Command Type: %s, data type config: 0x%lx", iter->second.c_str(),
  1139. command.module_index);
  1140. if (type == kProfCommandhandleStart || type == kProfCommandhandleStop) {
  1141. GELOGI("Profiling device nums:%s , deviceID:[%s]", prof_params[0].c_str(), prof_params[kDeviceListIndex].c_str());
  1142. }
  1143. ret = graph_loader.CommandHandle(command);
  1144. if (ret != ge::SUCCESS) {
  1145. GELOGE(ret, "[Handle][Command]Handle profiling command failed, command type %s, error_code %u",
  1146. iter->second.c_str(), ret);
  1147. REPORT_CALL_ERROR("E19999", "Handle profiling command failed, command type %s, error_code %u",
  1148. iter->second.c_str(), ret);
  1149. return ge::FAILED;
  1150. }
  1151. GELOGI("Successfully execute profiling command type: %d, command 0x%lx.", type, command.module_index);
  1152. return ge::SUCCESS;
  1153. }
  1154. return ge::FAILED;
  1155. }
  1156. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示