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

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