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 46 kB

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