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.

debugger.cc 47 kB

4 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
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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 <dirent.h>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <tuple>
  20. #include <vector>
  21. #include <algorithm>
  22. #include <iostream>
  23. #include <cstring>
  24. #include <utility>
  25. #include <map>
  26. #include <regex>
  27. #include "debug/debugger/debugger.h"
  28. #include "debug/data_dump/dump_json_parser.h"
  29. #include "pipeline/jit/pipeline.h"
  30. #include "backend/session/anf_runtime_algorithm.h"
  31. #include "runtime/device/kernel_runtime_manager.h"
  32. #include "runtime/device/kernel_runtime.h"
  33. #include "debug/data_dump/e2e_dump.h"
  34. #include "utils/config_manager.h"
  35. #include "debug/env_config_parser.h"
  36. using debugger::Chunk;
  37. using debugger::EventReply;
  38. using debugger::GraphProto;
  39. using debugger::ModelProto;
  40. using debugger::TensorProto;
  41. using debugger::WatchCondition;
  42. using debugger::WatchCondition_Condition_inf;
  43. using debugger::WatchCondition_Condition_nan;
  44. using debugger::WatchCondition_Parameter;
  45. using debugger::WatchNode;
  46. using debugger::WatchpointHit;
  47. namespace mindspore {
  48. static constexpr auto g_chunk_size = 1024 * 1024 * 3;
  49. DebuggerPtr Debugger::debugger_ = nullptr;
  50. std::mutex Debugger::instance_lock_;
  51. Debugger::Debugger()
  52. : grpc_client_(nullptr),
  53. debug_services_(nullptr),
  54. device_id_(0),
  55. device_target_(""),
  56. num_step_(0),
  57. debugger_enabled_(false),
  58. run_level_(""),
  59. node_name_(""),
  60. cur_name_(""),
  61. training_done_(false),
  62. is_dataset_graph_(false),
  63. partial_memory_(false),
  64. last_overflow_bin_(0),
  65. initial_suspend_(true),
  66. not_dataset_graph_sum_(0),
  67. version_("") {
  68. CheckDebuggerEnabledParam();
  69. auto ms_context = MsContext::GetInstance();
  70. MS_EXCEPTION_IF_NULL(ms_context);
  71. std::string device_target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  72. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  73. if (device_target == kCPUDevice) {
  74. MS_LOG(WARNING) << "Not enabling debugger. Debugger does not support CPU.";
  75. } else if (CheckDebuggerEnabled()) {
  76. // configure partial memory reuse
  77. partial_memory_ = CheckDebuggerPartialMemoryEnabled();
  78. // switch memory reuse on or off
  79. EnvConfigParser::GetInstance().SetSysMemreuse(partial_memory_);
  80. // print some message about memory reuse to user
  81. if (partial_memory_) {
  82. MS_LOG(WARNING)
  83. << "Partial Memory Reuse is enabled. Note: 1. Please only set watchpoints before running the first "
  84. "step. 2. Tensor values are only available for nodes that are watched by any watchpoint.";
  85. } else {
  86. MS_LOG(WARNING)
  87. << "Memory Reuse is disabled. Set environment variable MS_DEBUGGER_PARTIAL_MEM=1 to reduce memory "
  88. "usage for large models.";
  89. }
  90. }
  91. }
  92. void Debugger::Init(const uint32_t device_id, const std::string device_target) {
  93. // access lock for public method
  94. std::lock_guard<std::mutex> a_lock(access_lock_);
  95. // save device_id
  96. MS_LOG(INFO) << "Debugger got device_id: " << device_id;
  97. device_id_ = device_id;
  98. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  99. device_target_ = device_target;
  100. version_ = "1.2.0";
  101. }
  102. bool IsTypeDebuggerSupported(TypeId type) {
  103. if (type < TypeId::kNumberTypeEnd && type > TypeId::kNumberTypeBegin && type != kNumberTypeComplex64) {
  104. return true;
  105. } else {
  106. MS_LOG(WARNING) << "Debugger does not support type id: " << type;
  107. return false;
  108. }
  109. }
  110. void Debugger::EnableDebugger() {
  111. // reset some of the class members
  112. num_step_ = 0;
  113. debugger_enabled_ = false;
  114. partial_memory_ = false;
  115. grpc_client_ = nullptr;
  116. debug_services_ = nullptr;
  117. // see if dump using debugger backend is enabled
  118. bool dump_enabled = CheckDebuggerDumpEnabled();
  119. MS_LOG(INFO) << "dump using debugger backend = " << dump_enabled;
  120. // check if debugger enabled
  121. debugger_enabled_ = CheckDebuggerEnabled();
  122. MS_LOG(INFO) << "debugger_enabled_ = " << debugger_enabled_;
  123. if (!debugger_enabled_ && !dump_enabled) {
  124. MS_LOG(INFO) << "Not enabling debugger. Set environment variable ENABLE_MS_DEBUGGER=1 to enable debugger.";
  125. return;
  126. }
  127. if (debugger_enabled_) {
  128. // configure grpc host
  129. std::string env_host_str = common::GetEnv("MS_DEBUGGER_HOST");
  130. std::string host;
  131. if (!env_host_str.empty()) {
  132. if (CheckIp(env_host_str)) {
  133. MS_LOG(INFO) << "Getenv MS_DEBUGGER_HOST: " << env_host_str;
  134. host = env_host_str;
  135. } else {
  136. debugger_enabled_ = false;
  137. MS_EXCEPTION(ValueError) << "Environment variable MS_DEBUGGER_HOST isn't a valid IP address. "
  138. "Please set environment variable MS_DEBUGGER_HOST=x.x.x.x to a valid IP";
  139. }
  140. } else {
  141. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_HOST doesn't exist. Using default debugger host: localhost";
  142. host = "localhost";
  143. }
  144. // configure grpc port
  145. std::string env_port_str = common::GetEnv("MS_DEBUGGER_PORT");
  146. std::string port;
  147. if (!env_port_str.empty()) {
  148. if (CheckPort(env_port_str)) {
  149. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PORT: " << env_port_str;
  150. port = env_port_str;
  151. } else {
  152. debugger_enabled_ = false;
  153. MS_EXCEPTION(ValueError) << "Environment variable MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to "
  154. "65535";
  155. }
  156. } else {
  157. port = "50051";
  158. if (!CheckPort(port)) {
  159. MS_EXCEPTION(ValueError) << "Default MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to 65535";
  160. }
  161. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_PORT doesn't exist. Using default debugger port: 50051";
  162. }
  163. // initialize grpc client
  164. grpc_client_ = std::make_unique<GrpcClient>(host, port);
  165. }
  166. debug_services_ = std::make_unique<DebugServices>();
  167. }
  168. void Debugger::SetOpOverflowBinPath(uint32_t graph_id) {
  169. #ifdef ENABLE_D
  170. // set operation overflow info
  171. overflow_bin_path_.insert(std::pair<uint32_t, std::string>(
  172. graph_id, DumpJsonParser::GetInstance().GetOpOverflowBinPath(graph_id, device_id_)));
  173. // new overflow dump files will have a timestamp greater than last_overflow_bin_
  174. auto overflow_bin_path = overflow_bin_path_.find(graph_id)->second;
  175. MS_LOG(INFO) << "overflow_bin_path = " << overflow_bin_path;
  176. DIR *d = opendir(overflow_bin_path.c_str());
  177. if (d != nullptr) {
  178. struct dirent *dir;
  179. while ((dir = readdir(d)) != nullptr) {
  180. if (dir->d_type == DT_REG) {
  181. std::string file_path = overflow_bin_path;
  182. file_path.append(dir->d_name);
  183. std::size_t found = file_path.find_last_of(".");
  184. if (found == std::string::npos) {
  185. continue;
  186. }
  187. std::string overflow_time = file_path.substr(found + 1);
  188. if (stod(overflow_time) <= last_overflow_bin_) {
  189. MS_LOG(INFO) << "Old op overflow bin folder" << file_path;
  190. continue;
  191. }
  192. last_overflow_bin_ = stod(overflow_time);
  193. }
  194. }
  195. MS_LOG(INFO) << "last op overflow bin folder" << last_overflow_bin_;
  196. closedir(d);
  197. }
  198. #endif
  199. }
  200. void Debugger::CheckDatasetSinkMode() {
  201. if (CheckDebuggerDumpEnabled() && ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  202. MS_EXCEPTION(NotSupportError)
  203. << "e2e_dump not supported on GPU with dataset_sink_mode=True. Please set dataset_sink_mode=False";
  204. }
  205. if (CheckDebuggerEnabled() && ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  206. MS_EXCEPTION(NotSupportError)
  207. << "Debugger is not supported with dataset_sink_mode=True. Please set dataset_sink_mode=False";
  208. }
  209. }
  210. bool Debugger::CheckDebuggerDumpEnabled() const {
  211. // see if dump is enabled
  212. if (device_target_ == kGPUDevice) {
  213. return device::KernelRuntime::DumpDataEnabled();
  214. }
  215. return false;
  216. }
  217. bool Debugger::CheckDebuggerEnabled() const {
  218. // get env variables to configure debugger
  219. const char *env_enable_char = std::getenv("ENABLE_MS_DEBUGGER");
  220. if (env_enable_char != nullptr) {
  221. std::string env_enable_str = env_enable_char;
  222. (void)std::transform(env_enable_str.begin(), env_enable_str.end(), env_enable_str.begin(), ::tolower);
  223. if ((env_enable_str == "1" || env_enable_str == "true") && device_target_ != kCPUDevice) {
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. void Debugger::CheckDebuggerEnabledParam() const {
  230. // check the value of env variable ENABLE_MS_DEBUGGER
  231. const char *env_enable_char = std::getenv("ENABLE_MS_DEBUGGER");
  232. if (env_enable_char != nullptr) {
  233. std::string env_enable_str = env_enable_char;
  234. (void)std::transform(env_enable_str.begin(), env_enable_str.end(), env_enable_str.begin(), ::tolower);
  235. if (env_enable_str != "0" && env_enable_str != "1" && env_enable_str != "false" && env_enable_str != "true") {
  236. MS_LOG(WARNING) << "Env variable ENABLE_MS_DEBUGGER should be True/False/1/0 (case insensitive), but get: "
  237. << env_enable_str;
  238. }
  239. }
  240. }
  241. bool Debugger::CheckDebuggerPartialMemoryEnabled() const {
  242. const char *env_partial_mem_str = std::getenv("MS_DEBUGGER_PARTIAL_MEM");
  243. if (env_partial_mem_str != nullptr) {
  244. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PARTIAL_MEM: " << env_partial_mem_str;
  245. if (std::strcmp(env_partial_mem_str, "1") == 0) {
  246. return true;
  247. }
  248. }
  249. return false;
  250. }
  251. bool Debugger::DebuggerBackendEnabled() const { return CheckDebuggerDumpEnabled() || CheckDebuggerEnabled(); }
  252. void Debugger::Reset() {
  253. // access lock for public method
  254. std::lock_guard<std::mutex> a_lock(access_lock_);
  255. // reset components
  256. device_id_ = 0;
  257. device_target_ = "";
  258. num_step_ = 0;
  259. debugger_enabled_ = false;
  260. is_dataset_graph_ = false;
  261. partial_memory_ = false;
  262. graph_ptr_ = nullptr;
  263. grpc_client_ = nullptr;
  264. debug_services_ = nullptr;
  265. last_overflow_bin_ = 0;
  266. overflow_bin_path_.clear();
  267. stream_task_to_opname_.clear();
  268. graph_proto_list_.clear();
  269. graph_ptr_list_.clear();
  270. }
  271. void Debugger::PreExecute(const KernelGraphPtr &graph_ptr, uint32_t graph_sum) {
  272. // access lock for public method
  273. std::lock_guard<std::mutex> a_lock(access_lock_);
  274. CheckDatasetSinkMode();
  275. auto graph_id = graph_ptr->graph_id();
  276. // collect rungrap_ids to update step number in multigraph case
  277. if (!rungraph_id_list_.size()) {
  278. rungraph_id_list_.push_back(graph_id);
  279. } else {
  280. if (std::find(rungraph_id_list_.begin(), rungraph_id_list_.end(), graph_id) == rungraph_id_list_.end()) {
  281. rungraph_id_list_.push_back(graph_id);
  282. }
  283. }
  284. // check and save graph_ptr, suspend if graph is new
  285. MS_LOG(INFO) << "total number graph: " << graph_sum;
  286. // multiple graphs
  287. if (graph_sum > 1) {
  288. // there are more than one graphs are not dataset_graph
  289. if (not_dataset_graph_sum_ > 0) {
  290. // only try to enable debugger if they are not all dataset graphs
  291. if (!debugger_enabled_) {
  292. EnableDebugger();
  293. }
  294. if (debugger_enabled_) {
  295. if (graph_proto_list_.size()) {
  296. // only send compiled graphs once.
  297. auto dbg_graph_ptr = graph_ptr_;
  298. // use current graph ptr to load parameters
  299. graph_ptr_ = graph_ptr;
  300. LoadParametersAndConst();
  301. // revert graph ptr to original value
  302. graph_ptr_ = dbg_graph_ptr;
  303. SendMultiGraphsAndSuspend(graph_proto_list_);
  304. graph_proto_list_.clear();
  305. } else if (graph_id == rungraph_id_list_.front() && device_target_ == kGPUDevice) {
  306. // stop only when receive the first sub run graph for each step
  307. // if we have stopped for the last kernel before, no need to stop again
  308. if (!(run_level_ == "node" && suspended_at_last_kernel_)) {
  309. CommandLoop();
  310. }
  311. debug_services_->ResetLoadedTensors();
  312. }
  313. }
  314. }
  315. } else if (graph_proto_list_.size() == 1) {
  316. if (device_target_ == kGPUDevice && num_step_ != 0) {
  317. if (debugger_enabled_ && !(run_level_ == "node" && suspended_at_last_kernel_)) {
  318. CommandLoop();
  319. }
  320. debug_services_->ResetLoadedTensors();
  321. }
  322. // In single graph case, reset graph_ptr_ to be nullptr for the initial step
  323. if (num_step_ == 0) {
  324. graph_ptr_ = nullptr;
  325. CheckGraphPtr(graph_ptr);
  326. }
  327. }
  328. // resets for the new graph
  329. suspended_at_last_kernel_ = 0;
  330. }
  331. void Debugger::PostExecute() {
  332. // access lock for public method
  333. std::lock_guard<std::mutex> a_lock(access_lock_);
  334. if (pipeline::ExecutorPy::GetDebugTerminate()) {
  335. return;
  336. }
  337. if (debugger_->DebuggerBackendEnabled()) {
  338. // analyze tensor data and send the watchpoints been hit
  339. if (debugger_enabled_ && !is_dataset_graph_) {
  340. if (device_target_ != kGPUDevice) {
  341. num_step_++;
  342. }
  343. SendWatchpoints(CheckWatchpoints());
  344. // no need to suspend at each graph for GPU, suspension happens in preExecute
  345. if (device_target_ != kGPUDevice) {
  346. CommandLoop();
  347. }
  348. }
  349. // Only keep parameters in the current map
  350. // GPU ResetLoadedTensors happens in preExecute
  351. if (device_target_ != kGPUDevice) {
  352. debug_services_->ResetLoadedTensors();
  353. }
  354. }
  355. }
  356. bool Debugger::ReadNodeDataRequired(const CNodePtr &kernel) const {
  357. if (debugger_enabled_ && !is_dataset_graph_) {
  358. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  359. // if node has a watchpoint on it, is next_to node, or continue_to node then read the kernel tensor data
  360. if (is_watchpoint || (run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_))) {
  361. return true;
  362. }
  363. }
  364. return false;
  365. }
  366. void Debugger::PostExecuteNode(const CNodePtr &kernel, bool last_kernel) {
  367. // access lock for public method
  368. std::lock_guard<std::mutex> a_lock(access_lock_);
  369. if (pipeline::ExecutorPy::GetDebugTerminate()) {
  370. return;
  371. }
  372. if (debugger_enabled_ && !is_dataset_graph_) {
  373. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  374. // if kernel is watchpoint,and get hit. suspend.
  375. bool hit_empty_flag = true;
  376. if (is_watchpoint) {
  377. auto hits = CheckWatchpoints(cur_name_, kernel);
  378. if (!hits.empty()) {
  379. SendWatchpoints(hits);
  380. CommandLoop();
  381. hit_empty_flag = false;
  382. }
  383. }
  384. if (hit_empty_flag && run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_)) {
  385. // if kernel is not watchpoint and is next_to or continue_to node, suspend
  386. // sets a bool to be checked in preExecute to avoid double stopping at last kernel in the last graph
  387. if (last_kernel) {
  388. suspended_at_last_kernel_ = 1;
  389. }
  390. CommandLoop();
  391. }
  392. return;
  393. }
  394. }
  395. void Debugger::PostDebugOp() {
  396. // access lock for public method
  397. std::lock_guard<std::mutex> a_lock(access_lock_);
  398. // suspend if debugger is enabled
  399. if (debugger_enabled_ && !is_dataset_graph_) {
  400. MS_LOG(INFO) << "Debugger suspend at debug_op";
  401. CommandLoop();
  402. }
  403. }
  404. void Debugger::SetStreamTaskToOpnameMap(const std::map<std::pair<uint32_t, uint32_t>, std::string> &mapping) {
  405. MS_LOG(INFO) << "SetStreamTaskToOpnameMap start";
  406. for (auto const &item : mapping) {
  407. MS_LOG(INFO) << "stream = " << item.first.first << ", task = " << item.first.second
  408. << ", op_name = " << item.second << std::endl;
  409. }
  410. MS_LOG(INFO) << "SetStreamTaskToOpnameMap end";
  411. stream_task_to_opname_ = mapping;
  412. }
  413. void Debugger::LoadGraphs(const KernelGraphPtr &graph_ptr) {
  414. if (graph_ptr_ != graph_ptr) {
  415. MS_LOG(INFO) << "LoadGraphs Debugger got new graph: " << graph_ptr->graph_id();
  416. // save new graph_ptr
  417. graph_ptr_ = graph_ptr;
  418. CheckDatasetGraph();
  419. if (!is_dataset_graph_) {
  420. // get proto for new graph_ptr
  421. auto graph_proto = GetGraphProto(graph_ptr);
  422. // add new graph proto to graph_proto_list_
  423. graph_proto_list_.push_back(graph_proto);
  424. graph_ptr_list_.push_back(graph_ptr);
  425. #ifdef ENABLE_D
  426. SetOpOverflowBinPath(graph_ptr->graph_id());
  427. #endif
  428. not_dataset_graph_sum_++;
  429. }
  430. // reset is_dataset_graph to be false
  431. is_dataset_graph_ = false;
  432. }
  433. }
  434. // In single graph cases, check single graph ptr
  435. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  436. if (graph_ptr_ != graph_ptr) {
  437. MS_LOG(INFO) << "CheckGraphPtr Debugger got new graph: " << graph_ptr->graph_id();
  438. // save new graph_ptr
  439. graph_ptr_ = graph_ptr;
  440. if (!is_dataset_graph_) {
  441. // only try to enable debugger if it is not a dataset graph
  442. EnableDebugger();
  443. if (debugger_enabled_) {
  444. LoadParametersAndConst();
  445. // get graph proto and send to Mindinsight
  446. auto graph_proto = graph_proto_list_.front();
  447. SendGraphAndSuspend(graph_proto);
  448. }
  449. }
  450. }
  451. }
  452. void Debugger::CheckDatasetGraph() {
  453. // print parameter node names
  454. const auto &params = graph_ptr_->inputs();
  455. for (const auto &param : params) {
  456. MS_LOG(INFO) << "param: " << param->fullname_with_scope();
  457. }
  458. // check if there is GetNext or InitDataSetQueue node
  459. const auto &nodes = graph_ptr_->execution_order();
  460. for (const auto &node : nodes) {
  461. auto node_name = AnfAlgo::GetCNodeName(node);
  462. MS_LOG(INFO) << "node: " << node->fullname_with_scope();
  463. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  464. MS_LOG(INFO) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  465. << node_name;
  466. is_dataset_graph_ = true;
  467. return;
  468. }
  469. }
  470. is_dataset_graph_ = false;
  471. }
  472. GraphProto Debugger::GetGraphProto(const KernelGraphPtr &graph_ptr) const {
  473. // convert kernel graph to debugger modelproto
  474. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr);
  475. return model.graph();
  476. }
  477. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  478. if (SendMetadata(true)) {
  479. // send graph to Mindinsight server
  480. EventReply reply = grpc_client_->SendGraph(graph_proto);
  481. if (reply.status() != reply.OK) {
  482. MS_LOG(ERROR) << "Error: SendGraph failed";
  483. }
  484. // enter command loop, wait and process commands
  485. CommandLoop();
  486. }
  487. }
  488. bool Debugger::SendMetadata(bool version_check) {
  489. // prepare metadata
  490. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  491. Metadata metadata;
  492. metadata.set_device_name(device_name);
  493. metadata.set_cur_step(num_step_);
  494. metadata.set_backend(device_target_);
  495. metadata.set_cur_node(cur_name_);
  496. metadata.set_training_done(training_done_);
  497. metadata.set_ms_version(version_);
  498. MS_LOG(INFO) << "Is training done?" << training_done_;
  499. // set graph munber to not_dataset_graph_sum_
  500. metadata.set_graph_num(not_dataset_graph_sum_);
  501. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  502. bool ret = false;
  503. if (reply_metadata.status() == reply_metadata.OK) {
  504. if (version_check) {
  505. // get type of the command in meta data reply, it should be version matched
  506. DebuggerCommand cmd = GetCommand(reply_metadata);
  507. if (cmd != DebuggerCommand::kVersionMatchedCMD) {
  508. MS_LOG(ERROR) << "MindInsight version is too old, Mindspore version is " << version_;
  509. Exit();
  510. } else {
  511. if (GetMiVersionMatched(reply_metadata)) {
  512. MS_LOG(INFO) << "MindSpore version is " << version_ << " matches MindInsight version.";
  513. ret = true;
  514. } else {
  515. MS_LOG(ERROR) << "MindSpore version " << version_ << ", did not match MindInsight version.";
  516. CommandLoop();
  517. }
  518. }
  519. } else {
  520. // version check is done before so we can just return true here
  521. ret = true;
  522. }
  523. } else {
  524. MS_LOG(ERROR) << "Error: SendMetadata failed";
  525. }
  526. return ret;
  527. }
  528. void Debugger::SendMultiGraphsAndSuspend(const std::list<GraphProto> &graph_proto_list) {
  529. if (!SendMetadata(true)) {
  530. return;
  531. }
  532. // send multiple graphs to mindinght server
  533. // split graph into chunks if one graph is larger than chunk size
  534. std::list<Chunk> chunked_graph_proto_list;
  535. Chunk chunk;
  536. for (auto graph : graph_proto_list) {
  537. std::string str = graph.SerializeAsString();
  538. auto graph_size = graph.ByteSize();
  539. if (graph_size > g_chunk_size) {
  540. auto sub_graph_str = grpc_client_->ChunkString(str, graph_size);
  541. for (unsigned int i = 0; i < sub_graph_str.size(); i++) {
  542. chunk.set_buffer(sub_graph_str[i]);
  543. chunked_graph_proto_list.push_back(chunk);
  544. if (i < sub_graph_str.size() - 1) {
  545. chunk.set_finished(false);
  546. } else {
  547. chunk.set_finished(true);
  548. chunked_graph_proto_list.push_back(chunk);
  549. }
  550. }
  551. } else {
  552. chunk.set_buffer(str);
  553. chunk.set_finished(true);
  554. chunked_graph_proto_list.push_back(chunk);
  555. }
  556. }
  557. EventReply reply = grpc_client_->SendMultiGraphs(chunked_graph_proto_list);
  558. if (reply.status() != reply.OK) {
  559. MS_LOG(ERROR) << "Error: SendGraph failed";
  560. }
  561. // enter command loop, wait and process commands
  562. CommandLoop();
  563. }
  564. void Debugger::CommandLoop() {
  565. // prepare metadata
  566. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  567. Metadata metadata;
  568. metadata.set_device_name(device_name);
  569. metadata.set_cur_step(num_step_);
  570. metadata.set_backend(device_target_);
  571. metadata.set_cur_node(cur_name_);
  572. metadata.set_training_done(training_done_);
  573. // loop exit flag
  574. bool run = false;
  575. int num_wait_fail = 0;
  576. const int max_num_wait_fail = 5;
  577. while (!run) {
  578. // wait for command
  579. EventReply reply = grpc_client_->WaitForCommand(metadata);
  580. if (reply.status() != reply.OK) {
  581. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  582. num_wait_fail++;
  583. if (num_wait_fail > max_num_wait_fail) {
  584. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session.";
  585. MS_LOG(ERROR) << "Failed to connect to MindInsight debugger server. Please check the config "
  586. "of debugger host and port.";
  587. Exit();
  588. run = true;
  589. } else {
  590. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  591. << num_wait_fail << "s";
  592. std::this_thread::sleep_for(std::chrono::seconds(num_wait_fail));
  593. }
  594. continue;
  595. }
  596. // get type of the command in reply
  597. DebuggerCommand cmd = GetCommand(reply);
  598. if (cmd == DebuggerCommand::kUnknownCMD) {
  599. MS_LOG(DEBUG) << "Debug: debugger received unknown command";
  600. continue;
  601. }
  602. MS_LOG(INFO) << "received command: ";
  603. switch (cmd) {
  604. case DebuggerCommand::kUnknownCMD:
  605. MS_LOG(INFO) << "UnknownCMD";
  606. break;
  607. case DebuggerCommand::kExitCMD:
  608. MS_LOG(INFO) << "ExitCMD";
  609. Exit();
  610. // Used for debugger termination
  611. run = true;
  612. break;
  613. case DebuggerCommand::kRunCMD:
  614. ProcessRunCMD(reply);
  615. if (GetRunLevel(reply) != "recheck") {
  616. // exit loop
  617. run = true;
  618. }
  619. break;
  620. case DebuggerCommand::kSetCMD:
  621. ProcessKSetCMD(reply);
  622. break;
  623. case DebuggerCommand::kViewCMD:
  624. ProcessKViewCMD(reply);
  625. break;
  626. case DebuggerCommand::kVersionMatchedCMD:
  627. MS_LOG(ERROR) << "Received unexpected Version Matched CMD from Mindinsight.";
  628. Exit();
  629. break;
  630. default:
  631. MS_LOG(ERROR) << "Received unknown CMD from Mindinsight";
  632. Exit();
  633. break;
  634. }
  635. }
  636. }
  637. void Debugger::ProcessRunCMD(const EventReply &reply) {
  638. MS_LOG(INFO) << "RunCMD";
  639. if (GetRunLevel(reply) == "recheck") {
  640. MS_LOG(INFO) << "rechecking all watchpoints";
  641. SendWatchpoints(CheckWatchpoints("", nullptr, true));
  642. } else {
  643. // no longer the initial suspension.
  644. initial_suspend_ = false;
  645. // print run cmd content
  646. // get run_level and node_name
  647. run_level_ = GetRunLevel(reply);
  648. node_name_ = GetNodeName(reply);
  649. MS_LOG(INFO) << "run_level: " << run_level_;
  650. MS_LOG(INFO) << "node_name_: " << node_name_;
  651. }
  652. }
  653. void Debugger::ProcessKSetCMD(const EventReply &reply) {
  654. MS_LOG(INFO) << "SetCMD";
  655. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  656. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  657. if (GetWatchpointDelete(reply)) {
  658. MS_LOG(INFO) << "Deleting watchpoint";
  659. RemoveWatchpoint(GetWatchpointID(reply));
  660. } else {
  661. MS_LOG(INFO) << "Setting watchpoint";
  662. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  663. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  664. for (const auto &node : recieved_nodes) {
  665. MS_LOG(INFO) << "node name: " << node.node_name();
  666. MS_LOG(INFO) << "node type: " << node.node_type();
  667. }
  668. ProtoVector<WatchCondition_Parameter> parameters = GetParameters(reply);
  669. for (const auto &parameter : parameters) {
  670. MS_LOG(INFO) << "parameter name: " << parameter.name();
  671. MS_LOG(INFO) << "parameter is disabled: " << parameter.disabled();
  672. MS_LOG(INFO) << "parameter value: " << parameter.value();
  673. }
  674. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply), GetParameters(reply));
  675. }
  676. }
  677. void Debugger::ProcessKViewCMD(const EventReply &reply) {
  678. MS_LOG(INFO) << "ViewCMD";
  679. // print view cmd content
  680. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  681. for (auto received_tensor : received_tensors) {
  682. MS_LOG(INFO) << "tensor node name: " << received_tensor.node_name();
  683. MS_LOG(INFO) << "tensor slot: " << received_tensor.slot();
  684. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << received_tensor.finished() << std::noboolalpha;
  685. MS_LOG(INFO) << "tensor iter: " << received_tensor.iter();
  686. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << received_tensor.truncate() << std::noboolalpha;
  687. }
  688. MS_LOG(INFO) << "Sending tensors";
  689. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  690. // print view cmd reply
  691. for (auto tensor : tensors) {
  692. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  693. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  694. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  695. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  696. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  697. MS_LOG(INFO) << "tensor dims: ";
  698. for (auto dim : tensor.dims()) {
  699. MS_LOG(INFO) << dim << ",";
  700. }
  701. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  702. }
  703. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  704. if (send_tensors_reply.status() != send_tensors_reply.OK) {
  705. MS_LOG(ERROR) << "Error: SendTensors failed";
  706. }
  707. }
  708. void AddTensorProtoInfo(TensorProto *tensor_item, const TensorProto &tensor) {
  709. tensor_item->set_node_name(tensor.node_name());
  710. tensor_item->set_slot(tensor.slot());
  711. tensor_item->set_iter(tensor.iter());
  712. tensor_item->set_truncate(tensor.truncate());
  713. tensor_item->clear_tensor_content();
  714. tensor_item->clear_data_type();
  715. tensor_item->clear_dims();
  716. }
  717. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id,
  718. const ProtoVector<WatchCondition_Parameter> &parameters) {
  719. std::vector<std::tuple<std::string, bool>> check_node_list;
  720. std::vector<DebugServices::parameter_t> parameter_list;
  721. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  722. [](const WatchNode &node) -> std::tuple<std::string, bool> {
  723. return make_tuple(node.node_name(), node.node_type() == "scope");
  724. });
  725. std::transform(
  726. parameters.begin(), parameters.end(), std::back_inserter(parameter_list),
  727. [](const WatchCondition_Parameter &parameter) -> DebugServices::parameter_t {
  728. return DebugServices::parameter_t{parameter.name(), parameter.disabled(), parameter.value(), parameter.hit()};
  729. });
  730. debug_services_->AddWatchpoint(id, condition.condition(), condition.value(), check_node_list, parameter_list);
  731. }
  732. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  733. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  734. std::vector<std::string> name;
  735. std::vector<std::string> ret_name;
  736. std::vector<char *> data_ptr;
  737. std::vector<ssize_t> data_size;
  738. std::vector<unsigned int> dtype;
  739. std::vector<std::vector<int64_t>> shape;
  740. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  741. // ret_name will contain tensor names that are found in TensorLoader
  742. // items in ret_name will be in the same order with tensors if found
  743. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  744. std::list<TensorProto> tensor_list;
  745. unsigned int result_index = 0;
  746. for (auto tensor : tensors) {
  747. ssize_t size_iter = 0;
  748. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  749. TensorProto tensor_item;
  750. tensor_item.set_finished(true);
  751. AddTensorProtoInfo(&tensor_item, tensor);
  752. tensor_list.push_back(tensor_item);
  753. continue;
  754. }
  755. ssize_t tensor_size = data_size[result_index];
  756. while (size_iter < tensor_size) {
  757. ssize_t chunk_size = g_chunk_size;
  758. TensorProto tensor_item;
  759. tensor_item.set_finished(false);
  760. if (tensor_size - size_iter <= g_chunk_size) {
  761. chunk_size = tensor_size - size_iter;
  762. tensor_item.set_finished(true);
  763. }
  764. AddTensorProtoInfo(&tensor_item, tensor);
  765. // return empty tensor if didn't find the requested tensor
  766. tensor_item.set_tensor_content(data_ptr[result_index] + size_iter, chunk_size);
  767. tensor_item.set_data_type((debugger::DataType)dtype[result_index]);
  768. for (auto &elem : shape[result_index]) {
  769. tensor_item.add_dims(elem);
  770. }
  771. // add tensor to result list and increment result_index to check next item in ret_name
  772. tensor_list.push_back(tensor_item);
  773. size_iter += g_chunk_size;
  774. }
  775. result_index++;
  776. }
  777. return tensor_list;
  778. }
  779. void Debugger::Exit() {
  780. // clear resource before exit
  781. // debugger will notify main thread to exit because main thread can only exit at step boundary
  782. pipeline::ExecutorPy::DebugTerminate(true);
  783. }
  784. std::list<WatchpointHit> Debugger::CheckWatchpoints(const std::string &watchnode, const CNodePtr &kernel,
  785. bool recheck) {
  786. std::vector<std::string> name;
  787. std::vector<std::string> slot;
  788. std::vector<int> condition;
  789. std::vector<unsigned int> watchpoint_id;
  790. std::vector<std::string> overflow_ops;
  791. std::vector<std::vector<DebugServices::parameter_t>> parameters;
  792. std::vector<int32_t> error_codes;
  793. #ifdef ENABLE_D
  794. overflow_ops = CheckOpOverflow();
  795. for (auto const &item : overflow_ops) {
  796. MS_LOG(DEBUG) << "overflow_ops item = " << item << std::endl;
  797. }
  798. #endif
  799. std::vector<std::shared_ptr<TensorData>> tensor_list;
  800. if (watchnode.empty()) {
  801. tensor_list = debug_services_->GetTensor();
  802. } else {
  803. tensor_list = debug_services_->GetNodeTensor(kernel);
  804. }
  805. std::vector<std::string> file_list;
  806. debug_services_->CheckWatchpoints(&name, &slot, &condition, &watchpoint_id, &parameters, &error_codes, overflow_ops,
  807. file_list, &tensor_list, initial_suspend_, watchnode.empty(), recheck);
  808. std::list<WatchpointHit> hits;
  809. for (unsigned int i = 0; i < name.size(); i++) {
  810. WatchpointHit hit;
  811. std::vector<DebugServices::parameter_t> &parameter = parameters[i];
  812. hit.set_id(watchpoint_id[i]);
  813. hit.set_error_code(error_codes[i]);
  814. // here TensorProto act as a tensor indicator, not sending tensor content
  815. TensorProto *tensor_item = hit.mutable_tensor();
  816. tensor_item->set_node_name(name[i]);
  817. tensor_item->set_slot(slot[i]);
  818. tensor_item->set_finished(true);
  819. WatchCondition *condition_item = hit.mutable_watch_condition();
  820. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  821. for (const auto &p : parameter) {
  822. auto x = condition_item->mutable_params()->Add();
  823. x->set_name(p.name);
  824. x->set_disabled(p.disabled);
  825. x->set_value(p.value);
  826. x->set_hit(p.hit);
  827. x->set_actual_value(p.actual_value);
  828. }
  829. hits.push_back(hit);
  830. }
  831. return hits;
  832. }
  833. void Debugger::SendWatchpoints(const std::list<WatchpointHit> &points) {
  834. // send info about watchpoint
  835. if (!points.empty()) {
  836. EventReply reply = grpc_client_->SendWatchpointHits(points);
  837. if (reply.status() != reply.OK) {
  838. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  839. }
  840. }
  841. }
  842. bool Debugger::DumpTensorToFile(const std::string &tensor_name, bool trans_flag, const std::string &filepath,
  843. const std::string &host_fmt, const std::vector<int64_t> &host_shape, TypeId host_type,
  844. TypeId device_type, const std::string &addr_format, size_t slot) const {
  845. return debug_services_.get()->DumpTensorToFile(tensor_name, trans_flag, filepath, host_fmt, host_shape, host_type,
  846. device_type, addr_format, slot);
  847. }
  848. bool Debugger::DebugServicesIsWatchPoint(const std::string &kernel_name, const CNodePtr &kernel) const {
  849. return debug_services_.get()->IsWatchPoint(kernel_name, kernel);
  850. }
  851. void Debugger::EmptyTensor() { debug_services_.get()->EmptyTensor(); }
  852. void Debugger::SetTensorLoaderIterNum(uint32_t iter_num) { debug_services_.get()->SetTensorLoaderIterNum(iter_num); }
  853. void Debugger::EmptyPrevTensor() { debug_services_.get()->EmptyPrevTensor(); }
  854. uint32_t Debugger::GetTensorLoaderIterNum() const { return debug_services_.get()->GetTensorLoaderIterNum(); }
  855. bool Debugger::LoadNewTensor(const std::shared_ptr<TensorData> &tensor, bool keep_prev) {
  856. return debug_services_.get()->LoadNewTensor(tensor, keep_prev);
  857. }
  858. bool Debugger::debugger_enabled() const { return debugger_enabled_; }
  859. DebuggerCommand GetCommand(const EventReply &reply) {
  860. DebuggerCommand cmd = DebuggerCommand::kUnknownCMD;
  861. switch (reply.cmd_case()) {
  862. case debugger::EventReply::CmdCase::kExit:
  863. cmd = DebuggerCommand::kExitCMD;
  864. break;
  865. case debugger::EventReply::CmdCase::kRunCmd:
  866. cmd = DebuggerCommand::kRunCMD;
  867. break;
  868. case debugger::EventReply::CmdCase::kSetCmd:
  869. cmd = DebuggerCommand::kSetCMD;
  870. break;
  871. case debugger::EventReply::CmdCase::kViewCmd:
  872. cmd = DebuggerCommand::kViewCMD;
  873. break;
  874. case debugger::EventReply::CmdCase::kVersionMatched:
  875. cmd = DebuggerCommand::kVersionMatchedCMD;
  876. break;
  877. default:
  878. MS_LOG(DEBUG) << "Debug: UnknownCMD";
  879. break;
  880. }
  881. return cmd;
  882. }
  883. ProtoVector<WatchCondition_Parameter> GetParameters(const EventReply &reply) {
  884. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  885. MS_LOG(ERROR) << "Error: Can not get Parameters from command. Returning default value: ProtoVector<Parameter>().";
  886. return ProtoVector<WatchCondition_Parameter>();
  887. }
  888. return reply.set_cmd().watch_condition().params();
  889. }
  890. ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply) {
  891. if (!reply.has_set_cmd()) {
  892. MS_LOG(ERROR) << "Error: Not SetCMD, can not get WatchNodes. Returning default value: ProtoVector<WatchNode>().";
  893. return ProtoVector<WatchNode>();
  894. }
  895. return reply.set_cmd().watch_nodes();
  896. }
  897. std::string GetRunLevel(const EventReply &reply) {
  898. if (!reply.has_run_cmd()) {
  899. MS_LOG(ERROR) << "Error: Not RunCMD, can not get RunLevel. Returning default value: "
  900. "";
  901. return "";
  902. }
  903. return reply.run_cmd().run_level();
  904. }
  905. std::string GetNodeName(const EventReply &reply) {
  906. if (!reply.has_run_cmd()) {
  907. MS_LOG(ERROR) << "Error: Not RunCMD, can not get NodeName. Returning default value: "
  908. "";
  909. return "";
  910. }
  911. return reply.run_cmd().node_name();
  912. }
  913. WatchCondition GetWatchcondition(const EventReply &reply) {
  914. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  915. MS_LOG(ERROR) << "Error: Can not get WatchCondition from command. Returning default value: WatchCondition().";
  916. return WatchCondition();
  917. }
  918. return reply.set_cmd().watch_condition();
  919. }
  920. int32_t GetWatchpointID(const EventReply &reply) {
  921. if (!reply.has_set_cmd()) {
  922. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint ID. Returning default value: 0.";
  923. return 0;
  924. }
  925. return reply.set_cmd().id();
  926. }
  927. bool GetWatchpointDelete(const EventReply &reply) {
  928. if (!reply.has_set_cmd()) {
  929. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint delete flag. Returning default value: false.";
  930. return false;
  931. }
  932. return reply.set_cmd().delete_();
  933. }
  934. ProtoVector<TensorProto> GetTensors(const EventReply &reply) {
  935. if (!reply.has_view_cmd()) {
  936. MS_LOG(ERROR) << "Error: Not ViewCMD, can not get Tensors. Returning default value: ProtoVector<TensorProto>().";
  937. return ProtoVector<TensorProto>();
  938. }
  939. return reply.view_cmd().tensors();
  940. }
  941. std::string GetTensorFullName(const TensorProto &tensor) {
  942. string node_name = tensor.node_name();
  943. if (tensor.truncate()) {
  944. // scopes in node name are separated by '/'
  945. // use the name without scope if truncate is true
  946. std::size_t found = node_name.find_last_of("/");
  947. node_name = node_name.substr(found + 1);
  948. }
  949. return node_name + ":" + tensor.slot() + (tensor.iter() == "" ? "" : ":" + tensor.iter());
  950. }
  951. bool GetMiVersionMatched(const EventReply &reply) { return reply.version_matched(); }
  952. bool Debugger::partial_memory() const { return partial_memory_; }
  953. void Debugger::SetCurNode(const std::string &cur_name) {
  954. // access lock for public method
  955. std::lock_guard<std::mutex> a_lock(access_lock_);
  956. cur_name_ = cur_name;
  957. }
  958. std::string Debugger::run_level() const { return run_level_; }
  959. void Debugger::SetStepNum(int32_t cur_num_step) {
  960. // access lock for public method
  961. std::lock_guard<std::mutex> a_lock(access_lock_);
  962. num_step_ = cur_num_step;
  963. }
  964. int32_t Debugger::step_num() const { return num_step_; }
  965. uint64_t BytestoInt64(const std::vector<char> &buffer) {
  966. uint64_t ret = (uint64_t)buffer[0];
  967. const int SHIFT = 8;
  968. const int MAX_INDEX = 8;
  969. for (int i = 1; i < MAX_INDEX; i++) {
  970. ret = ((uint64_t)buffer[i] << (i * SHIFT)) | ret;
  971. }
  972. return ret;
  973. }
  974. std::vector<std::string> Debugger::CheckOpOverflow() {
  975. std::vector<double> bin_list;
  976. std::vector<std::string> op_names;
  977. for (const auto &[graph_id, overflow_bin_path] : overflow_bin_path_) {
  978. DIR *d = opendir(overflow_bin_path.c_str());
  979. MS_LOG(INFO) << "processing bin file path " << overflow_bin_path << ", graph id " << graph_id;
  980. if (d != nullptr) {
  981. struct dirent *dir = nullptr;
  982. while ((dir = readdir(d)) != nullptr) {
  983. if (dir->d_type == DT_REG) {
  984. std::string file_path = overflow_bin_path;
  985. file_path.append(dir->d_name);
  986. std::string file_name = dir->d_name;
  987. std::size_t found = file_name.find_last_of(".");
  988. if (found == std::string::npos) {
  989. continue;
  990. }
  991. std::string overflow_time = file_name.substr(found + 1);
  992. if (stod(overflow_time) <= last_overflow_bin_) {
  993. MS_LOG(INFO) << "File already processed " << file_name;
  994. continue;
  995. }
  996. bin_list.push_back(stod(overflow_time));
  997. std::fstream infile;
  998. infile.open(file_path.c_str(), std::ios::binary | std::ios::in);
  999. if (!infile.is_open()) {
  1000. MS_LOG(ERROR) << "Failed to open overflow bin file " << file_name;
  1001. continue;
  1002. }
  1003. MS_LOG(INFO) << "Open overflow bin file " << file_name;
  1004. const uint32_t offset = 313;
  1005. infile.seekg(offset, std::ios::beg);
  1006. std::vector<char> buffer;
  1007. const size_t buf_size = 256;
  1008. buffer.resize(buf_size);
  1009. infile.read(buffer.data(), buf_size);
  1010. const uint8_t stream_id_offset = 8;
  1011. const uint8_t task_id_offset = 16;
  1012. uint64_t stream_id = BytestoInt64(std::vector<char>(buffer.begin() + stream_id_offset, buffer.end()));
  1013. uint64_t task_id = BytestoInt64(std::vector<char>(buffer.begin() + task_id_offset, buffer.end()));
  1014. MS_LOG(INFO) << "Overflow stream_id " << stream_id << ", task_id " << task_id << ".";
  1015. auto op = debugger_->stream_task_to_opname_.find(std::make_pair(stream_id, task_id));
  1016. if (op != debugger_->stream_task_to_opname_.end()) {
  1017. MS_LOG(ERROR) << "Overflow detected on node " << op->second << std::endl;
  1018. op_names.push_back(op->second);
  1019. } else {
  1020. MS_LOG(INFO) << "No overflow is detected " << std::endl;
  1021. }
  1022. infile.close();
  1023. }
  1024. }
  1025. } else {
  1026. MS_LOG(INFO) << "OverFlow bin directory does not exist!";
  1027. }
  1028. closedir(d);
  1029. }
  1030. if (!op_names.empty()) {
  1031. MS_LOG(ERROR) << "These operation overflows are detected " << op_names;
  1032. }
  1033. for (auto &i : bin_list) {
  1034. if (i > last_overflow_bin_) {
  1035. last_overflow_bin_ = i;
  1036. }
  1037. }
  1038. auto iter_op_names = overflow_ops_.find(num_step_);
  1039. if (iter_op_names == overflow_ops_.end()) {
  1040. overflow_ops_.insert(std::pair<uint32_t, std::vector<std::string>>(num_step_, op_names));
  1041. return op_names;
  1042. }
  1043. iter_op_names->second.insert(std::end(iter_op_names->second), std::begin(op_names), std::end(op_names));
  1044. return iter_op_names->second;
  1045. }
  1046. void Debugger::SetTrainingDone(bool training_done) { training_done_ = training_done; }
  1047. bool Debugger::CheckPort(const std::string &port) const {
  1048. int num = 0;
  1049. const int min_port_num = 1;
  1050. const int max_port_num = 65535;
  1051. if (port[0] == '0' && port[1] != '\0') return false;
  1052. int i = 0;
  1053. while (port[i] != '\0') {
  1054. if (port[i] < '0' || port[i] > '9') return false;
  1055. num = num * 10 + (port[i] - '0');
  1056. if (num > max_port_num) return false;
  1057. i++;
  1058. }
  1059. if (num < min_port_num) return false;
  1060. return true;
  1061. }
  1062. bool Debugger::CheckIp(const std::string &host) const {
  1063. std::regex reg_ip(
  1064. "(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"
  1065. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  1066. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  1067. "[.](25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])");
  1068. std::smatch smat;
  1069. std::string host_str = host;
  1070. return std::regex_match(host_str, smat, reg_ip);
  1071. }
  1072. uint32_t Debugger::GetFirstRunGraphId() const { return rungraph_id_list_.front(); }
  1073. void Debugger::LoadSingleAnfnode(const AnfNodePtr &anf_node, const size_t output_index) {
  1074. MS_EXCEPTION_IF_NULL(anf_node);
  1075. if (!anf_node->isa<Parameter>() && !anf_node->isa<ValueNode>()) {
  1076. return;
  1077. }
  1078. // for parameters and value nodes, set its execution order to be 0;
  1079. int exec_order = 0;
  1080. std::string node_name = anf_node->fullname_with_scope();
  1081. GetFileKernelName(NOT_NULL(&node_name));
  1082. // check if output adde exists, if not, return;
  1083. if (!AnfAlgo::OutputAddrExist(anf_node, output_index)) {
  1084. return;
  1085. }
  1086. auto addr = AnfAlgo::GetOutputAddr(anf_node, output_index);
  1087. MS_EXCEPTION_IF_NULL(addr);
  1088. auto type = AnfAlgo::GetOutputInferDataType(anf_node, output_index);
  1089. if (!IsTypeDebuggerSupported(type)) {
  1090. return;
  1091. }
  1092. auto format = kOpFormat_DEFAULT;
  1093. string tensor_name = node_name + ':' + "0";
  1094. ShapeVector int_shapes = trans::GetRuntimePaddingShape(anf_node, output_index);
  1095. bool keep_prev;
  1096. if (anf_node->isa<Parameter>()) {
  1097. keep_prev = true;
  1098. debug_services_->MoveTensorCurrentToPrev(tensor_name);
  1099. } else {
  1100. keep_prev = false;
  1101. }
  1102. bool ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, 0, keep_prev);
  1103. if (!ret) {
  1104. MS_LOG(ERROR) << "LoadMemToHost:"
  1105. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1106. }
  1107. }
  1108. void Debugger::LoadParametersAndConst() {
  1109. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  1110. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1111. // load parameters
  1112. MS_LOG(INFO) << "Start to load Parameters!";
  1113. const auto &parameters = graph_ptr_->inputs();
  1114. for (auto &item : parameters) {
  1115. LoadSingleAnfnode(item, PARAMETER_OUTPUT_INDEX);
  1116. }
  1117. // load value nodes
  1118. // get all constant avlues from the graph
  1119. MS_LOG(INFO) << "Start to load value nodes!";
  1120. const auto value_nodes = graph_ptr_->graph_value_nodes();
  1121. for (auto &item : value_nodes) {
  1122. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX);
  1123. }
  1124. }
  1125. void Debugger::LoadGraphOutputs() {
  1126. if (!(debugger_enabled() && device_target_ == kAscendDevice)) return;
  1127. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1128. const auto &apply_kernels = graph_ptr_->execution_order();
  1129. // for kernels, execution order starts from 1
  1130. int exec_order = 1;
  1131. for (const auto &node : apply_kernels) {
  1132. MS_EXCEPTION_IF_NULL(node);
  1133. std::string kernel_name = node->fullname_with_scope();
  1134. auto output_size = AnfAlgo::GetOutputTensorNum(node);
  1135. if (partial_memory_) {
  1136. if (!debug_services_->IsWatchPoint(kernel_name, node)) {
  1137. continue;
  1138. }
  1139. }
  1140. for (size_t j = 0; j < output_size; ++j) {
  1141. if (!AnfAlgo::OutputAddrExist(node, j)) {
  1142. MS_LOG(INFO) << "Cannot find output addr for slot " << j << " for " << node->fullname_with_scope();
  1143. continue;
  1144. }
  1145. auto addr = AnfAlgo::GetOutputAddr(node, j);
  1146. MS_EXCEPTION_IF_NULL(addr);
  1147. auto type = AnfAlgo::GetOutputInferDataType(node, j);
  1148. if (!IsTypeDebuggerSupported(type)) {
  1149. continue;
  1150. }
  1151. auto format = kOpFormat_DEFAULT;
  1152. string tensor_name = kernel_name + ':' + std::to_string(j);
  1153. ShapeVector int_shapes = trans::GetRuntimePaddingShape(node, j);
  1154. auto ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, j, false);
  1155. if (!ret) {
  1156. MS_LOG(ERROR) << "LoadMemToHost:"
  1157. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1158. }
  1159. }
  1160. exec_order = exec_order + 1;
  1161. }
  1162. }
  1163. void Debugger::UpdateStepNum(const session::KernelGraph *graph) {
  1164. // update step number if we are processing the first graph (to support multigraph)
  1165. if (device_target_ == kGPUDevice && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration()) &&
  1166. (graph->graph_id() == debugger_->GetFirstRunGraphId())) {
  1167. // access lock for public method
  1168. std::lock_guard<std::mutex> a_lock(access_lock_);
  1169. ++num_step_;
  1170. }
  1171. }
  1172. void Debugger::ClearCurrentData() {
  1173. if (device_target_ == kGPUDevice && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration()))
  1174. debug_services_->EmptyCurrentTensor();
  1175. }
  1176. bool Debugger::TensorExistsInCurrent(const std::string &tensor_name) {
  1177. return debug_services_->TensorExistsInCurrent(tensor_name);
  1178. }
  1179. } // namespace mindspore