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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. using debugger::EventReply;
  34. using debugger::GraphProto;
  35. using debugger::ModelProto;
  36. using debugger::TensorProto;
  37. using debugger::WatchCondition;
  38. using debugger::WatchCondition_Condition_inf;
  39. using debugger::WatchCondition_Condition_nan;
  40. using debugger::WatchNode;
  41. using debugger::WatchpointHit;
  42. #define CHUNK_SIZE 1024 * 1024 * 3
  43. namespace mindspore {
  44. DebuggerPtr Debugger::debugger_ = nullptr;
  45. std::mutex Debugger::instance_lock_;
  46. static const size_t PRAMATER_OUTPUT_INDEX = 0;
  47. Debugger::Debugger()
  48. : grpc_client_(nullptr),
  49. debug_services_(nullptr),
  50. device_id_(0),
  51. device_target_(""),
  52. num_step_(0),
  53. debugger_enabled_(false),
  54. run_level_(""),
  55. node_name_(""),
  56. cur_name_(""),
  57. training_done_(false),
  58. is_dataset_graph_(false),
  59. partial_memory_(false),
  60. last_overflow_bin_(0),
  61. overflow_bin_path_("") {
  62. if (CheckDebuggerEnabled()) {
  63. // configure partial memory reuse
  64. partial_memory_ = CheckDebuggerPartialMemoryEnabled();
  65. // switch memory reuse on or off
  66. auto context_ptr = MsContext::GetInstance();
  67. MS_EXCEPTION_IF_NULL(context_ptr);
  68. context_ptr->set_param<bool>(MS_CTX_ENABLE_MEM_REUSE, partial_memory_);
  69. // print some message about memory reuse to user
  70. if (partial_memory_) {
  71. MS_LOG(WARNING)
  72. << "Partial Memory Reuse is enabled. Note: 1. Please only set watchpoints before running the first "
  73. "step. 2. Tensor values are only available for nodes that are watched by any watchpoint.";
  74. } else {
  75. MS_LOG(INFO) << "Memory Reuse is disabled. Set environment variable MS_DEBUGGER_PARTIAL_MEM=1 to reduce memory "
  76. "usage for large models.";
  77. }
  78. }
  79. }
  80. void Debugger::Init(const uint32_t device_id, const std::string device_target) {
  81. // access lock for public method
  82. std::lock_guard<std::mutex> a_lock(access_lock_);
  83. // save device_id
  84. MS_LOG(INFO) << "Debugger got device_id: " << device_id;
  85. device_id_ = device_id;
  86. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  87. device_target_ = device_target;
  88. }
  89. void Debugger::EnableDebugger() {
  90. // reset some of the class members
  91. num_step_ = 0;
  92. debugger_enabled_ = false;
  93. partial_memory_ = false;
  94. grpc_client_ = nullptr;
  95. debug_services_ = nullptr;
  96. // see if dump using debugger backend is enabled
  97. bool dump_enabled = CheckDebuggerDumpEnabled();
  98. MS_LOG(INFO) << "dump using debugger backend = " << dump_enabled;
  99. // check if debugger enabled
  100. debugger_enabled_ = CheckDebuggerEnabled();
  101. MS_LOG(INFO) << "debugger_enabled_ = " << debugger_enabled_;
  102. if (!debugger_enabled_ && !dump_enabled) {
  103. MS_LOG(INFO) << "Not enabling debugger. Set environment variable ENABLE_MS_DEBUGGER=1 to enable debugger.";
  104. return;
  105. }
  106. // configure grpc host
  107. const char *env_host_str = std::getenv("MS_DEBUGGER_HOST");
  108. std::string host;
  109. if (env_host_str != nullptr) {
  110. std::regex reg_ip(
  111. "(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"
  112. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  113. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  114. "[.](25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])");
  115. std::smatch smat;
  116. std::string host_str = std::string(env_host_str);
  117. if (std::regex_match(host_str, smat, reg_ip)) {
  118. MS_LOG(INFO) << "Getenv MS_DEBUGGER_HOST: " << env_host_str;
  119. host = std::string(env_host_str);
  120. } else {
  121. MS_LOG(ERROR) << "Environment variable MS_DEBUGGER_HOST isn't a valid IP address. "
  122. "Please set environment variable MS_DEBUGGER_HOST=x.x.x.x to a valid IP";
  123. debugger_enabled_ = false;
  124. }
  125. } else {
  126. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_HOST doesn't exist. Using default debugger host: localhost";
  127. host = "localhost";
  128. }
  129. // configure grpc port
  130. const char *env_port_str = std::getenv("MS_DEBUGGER_PORT");
  131. std::string port;
  132. if (env_port_str != nullptr) {
  133. if (CheckPort(env_port_str)) {
  134. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PORT: " << env_port_str;
  135. port = std::string(env_port_str);
  136. } else {
  137. MS_LOG(ERROR) << "Environment variable MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to 65535";
  138. debugger_enabled_ = false;
  139. }
  140. } else {
  141. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_PORT doesn't exist. Using default debugger port: 50051";
  142. port = "50051";
  143. }
  144. #ifdef ENABLE_D
  145. // set operation overflow info
  146. overflow_bin_path_ = DumpJsonParser::GetInstance().GetOpOverflowBinPath(graph_ptr_->graph_id(), device_id_);
  147. // new overflow dump files will have a timestamp greater than last_overflow_bin_
  148. last_overflow_bin_ = 0;
  149. DIR *d;
  150. d = opendir(overflow_bin_path_.c_str());
  151. if (d != nullptr) {
  152. struct dirent *dir;
  153. while ((dir = readdir(d)) != NULL) {
  154. if (dir->d_type == DT_REG) {
  155. std::string file_path = overflow_bin_path_;
  156. file_path.append(dir->d_name);
  157. std::size_t found = file_path.find_last_of(".");
  158. if (found == std::string::npos) {
  159. continue;
  160. }
  161. std::string overflow_time = file_path.substr(found + 1);
  162. if (stod(overflow_time) <= last_overflow_bin_) {
  163. MS_LOG(INFO) << "Old op overflow bin folder" << file_path;
  164. continue;
  165. }
  166. last_overflow_bin_ = stod(overflow_time);
  167. }
  168. }
  169. MS_LOG(INFO) << "last op overflow bin folder" << last_overflow_bin_;
  170. closedir(d);
  171. }
  172. #endif
  173. // initialize grpc client
  174. if (debugger_enabled_) {
  175. grpc_client_ = std::make_unique<GrpcClient>(host, port);
  176. }
  177. debug_services_ = std::make_unique<DebugServices>();
  178. }
  179. bool Debugger::CheckDebuggerDumpEnabled() {
  180. // see if dump is enabled
  181. if (device_target_ == kGPUDevice) {
  182. return device::KernelRuntime::DumpDataEnabled();
  183. }
  184. return false;
  185. }
  186. bool Debugger::CheckDebuggerEnabled() {
  187. // get env variables to configure debugger
  188. const char *env_enable_str = std::getenv("ENABLE_MS_DEBUGGER");
  189. if (env_enable_str != nullptr) {
  190. if (std::strcmp(env_enable_str, "1") == 0) {
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. bool Debugger::CheckDebuggerPartialMemoryEnabled() {
  197. const char *env_partial_mem_str = std::getenv("MS_DEBUGGER_PARTIAL_MEM");
  198. if (env_partial_mem_str != nullptr) {
  199. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PARTIAL_MEM: " << env_partial_mem_str;
  200. if (std::strcmp(env_partial_mem_str, "1") == 0) {
  201. return true;
  202. }
  203. }
  204. return false;
  205. }
  206. bool Debugger::DebuggerBackendEnabled() { return CheckDebuggerDumpEnabled() || CheckDebuggerEnabled(); }
  207. void Debugger::Reset() {
  208. // access lock for public method
  209. std::lock_guard<std::mutex> a_lock(access_lock_);
  210. // reset components
  211. device_id_ = 0;
  212. device_target_ = "";
  213. num_step_ = 0;
  214. debugger_enabled_ = false;
  215. is_dataset_graph_ = false;
  216. partial_memory_ = false;
  217. graph_ptr_ = nullptr;
  218. grpc_client_ = nullptr;
  219. debug_services_ = nullptr;
  220. last_overflow_bin_ = 0;
  221. overflow_bin_path_ = "";
  222. stream_task_to_opname_.clear();
  223. }
  224. void Debugger::PreExecute(const KernelGraphPtr &graph_ptr) {
  225. // access lock for public method
  226. std::lock_guard<std::mutex> a_lock(access_lock_);
  227. if (debugger_->DebuggerBackendEnabled()) {
  228. // check and save graph_ptr, suspend if graph is new
  229. CheckGraphPtr(graph_ptr);
  230. }
  231. }
  232. void Debugger::PostExecute() {
  233. // access lock for public method
  234. std::lock_guard<std::mutex> a_lock(access_lock_);
  235. if (debugger_->DebuggerBackendEnabled()) {
  236. // analyze tensor data and send the watchpoints been hit
  237. if (run_level_ == "node") {
  238. MS_LOG(INFO) << "Debugger is in node level mode ";
  239. return;
  240. }
  241. if (debugger_enabled_ && !is_dataset_graph_) {
  242. if (device_target_ != kGPUDevice) {
  243. num_step_++;
  244. MS_LOG(INFO) << "Debugger suspend at end of step; number of steps executed: " << num_step_;
  245. SendWatchpointsAndSuspend(CheckWatchpoints());
  246. } else {
  247. CommandLoop();
  248. }
  249. }
  250. }
  251. }
  252. bool Debugger::ReadNodeDataRequired() {
  253. if (debugger_enabled_ && !is_dataset_graph_) {
  254. auto watchpoint_table = debug_services_->GetWatchpointTable();
  255. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, watchpoint_table);
  256. // if node has a watchpoint on it, is next_to node, or continue_to node then read the kernel tensor data
  257. if (is_watchpoint || (run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_))) {
  258. return true;
  259. }
  260. }
  261. return false;
  262. }
  263. void Debugger::PostExecuteNode() {
  264. // access lock for public method
  265. std::lock_guard<std::mutex> a_lock(access_lock_);
  266. if (debugger_enabled_ && !is_dataset_graph_) {
  267. auto watchpoint_table = debug_services_->GetWatchpointTable();
  268. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, watchpoint_table);
  269. // if kernel is watchpoint,and get hit. suspend.
  270. bool hit_empty_flag = true;
  271. if (is_watchpoint) {
  272. auto hits = CheckWatchpoints(cur_name_);
  273. if (!hits.empty()) {
  274. SendWatchpointsAndSuspend(hits);
  275. hit_empty_flag = false;
  276. }
  277. }
  278. if (hit_empty_flag && run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_)) {
  279. // if kernel is not watchpoint and is next_to or continue_to node, suspend
  280. CommandLoop();
  281. }
  282. return;
  283. }
  284. }
  285. void Debugger::PostDebugOp() {
  286. // access lock for public method
  287. std::lock_guard<std::mutex> a_lock(access_lock_);
  288. // suspend if debugger is enabled
  289. if (debugger_enabled_ && !is_dataset_graph_) {
  290. MS_LOG(INFO) << "Debugger suspend at debug_op";
  291. CommandLoop();
  292. }
  293. }
  294. void Debugger::SetStreamTaskToOpnameMap(const std::map<std::pair<uint32_t, uint32_t>, std::string> &mapping) {
  295. stream_task_to_opname_ = mapping;
  296. }
  297. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  298. if (graph_ptr_ != graph_ptr) {
  299. MS_LOG(INFO) << "Debugger got new graph: " << graph_ptr->graph_id();
  300. // save new graph_ptr
  301. graph_ptr_ = graph_ptr;
  302. // check if it is dataset graph
  303. CheckDatasetGraph();
  304. if (!is_dataset_graph_) {
  305. // only try to enable debugger if it is not a dataset graph
  306. EnableDebugger();
  307. if (debugger_enabled_) {
  308. LoadParameters();
  309. // get graph proto and send to mindinsight
  310. SendGraphAndSuspend(GetGraphProto());
  311. }
  312. }
  313. }
  314. }
  315. void Debugger::CheckDatasetGraph() {
  316. // print parameter node names
  317. const auto &params = graph_ptr_->inputs();
  318. for (const auto &param : params) {
  319. MS_LOG(INFO) << "param: " << param->fullname_with_scope();
  320. }
  321. // check if there is GetNext or InitDataSetQueue node
  322. const auto &nodes = graph_ptr_->execution_order();
  323. for (const auto &node : nodes) {
  324. auto node_name = AnfAlgo::GetCNodeName(node);
  325. MS_LOG(INFO) << "node: " << node->fullname_with_scope();
  326. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  327. MS_LOG(INFO) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  328. << node_name;
  329. is_dataset_graph_ = true;
  330. return;
  331. }
  332. }
  333. is_dataset_graph_ = false;
  334. }
  335. GraphProto Debugger::GetGraphProto() const {
  336. // convert kernel graph to debugger modelproto
  337. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr_);
  338. return model.graph();
  339. }
  340. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  341. SendMetadata();
  342. // send graph to mindinght server
  343. EventReply reply = grpc_client_->SendGraph(graph_proto);
  344. if (reply.status() != reply.OK) {
  345. MS_LOG(ERROR) << "Error: SendGraph failed";
  346. }
  347. // enter command loop, wait and process commands
  348. CommandLoop();
  349. }
  350. void Debugger::SendMetadata() {
  351. // prepare metadata
  352. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  353. Metadata metadata;
  354. metadata.set_device_name(device_name);
  355. metadata.set_cur_step(num_step_);
  356. metadata.set_backend(device_target_);
  357. metadata.set_cur_node(cur_name_);
  358. metadata.set_training_done(training_done_);
  359. MS_LOG(INFO) << "Is training done?" << training_done_;
  360. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  361. if (reply_metadata.status() != reply_metadata.OK) {
  362. MS_LOG(ERROR) << "Error: SendMetadata failed";
  363. }
  364. }
  365. void Debugger::CommandLoop() {
  366. // prepare metadata
  367. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  368. Metadata metadata;
  369. metadata.set_device_name(device_name);
  370. metadata.set_cur_step(num_step_);
  371. metadata.set_backend(device_target_);
  372. metadata.set_cur_node(cur_name_);
  373. metadata.set_training_done(training_done_);
  374. // loop exit flag
  375. bool run = false;
  376. int num_wait_fail = 0;
  377. const int max_num_wait_fail = 5;
  378. while (!run) {
  379. // wait for command
  380. EventReply reply = grpc_client_->WaitForCommand(metadata);
  381. if (reply.status() != reply.OK) {
  382. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  383. num_wait_fail++;
  384. if (num_wait_fail > max_num_wait_fail) {
  385. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session.";
  386. MS_LOG(ERROR) << "Failed to connect to MindInsight debugger server. Please check the config "
  387. "of debugger host and port.";
  388. Exit();
  389. }
  390. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  391. << num_wait_fail << "s";
  392. std::this_thread::sleep_for(std::chrono::milliseconds(1000 * num_wait_fail));
  393. continue;
  394. }
  395. // get type of the command in reply
  396. DebuggerCommand cmd = GetCommand(reply);
  397. if (cmd == DebuggerCommand::kUnknownCMD) {
  398. MS_LOG(DEBUG) << "Debug: debugger received unknown command";
  399. continue;
  400. }
  401. MS_LOG(INFO) << "received command: ";
  402. switch (cmd) {
  403. case DebuggerCommand::kUnknownCMD:
  404. MS_LOG(INFO) << "UnknownCMD";
  405. break;
  406. case DebuggerCommand::kExitCMD:
  407. MS_LOG(INFO) << "ExitCMD";
  408. Exit();
  409. // Used for debugger termination
  410. run = true;
  411. break;
  412. case DebuggerCommand::kRunCMD:
  413. MS_LOG(INFO) << "RunCMD";
  414. {
  415. // print run cmd content
  416. // get run_level and node_name
  417. run_level_ = GetRunLevel(reply);
  418. node_name_ = GetNodeName(reply);
  419. MS_LOG(INFO) << "run_level: " << run_level_;
  420. MS_LOG(INFO) << "node_name_: " << node_name_;
  421. }
  422. // exit loop
  423. run = true;
  424. break;
  425. case DebuggerCommand::kSetCMD:
  426. MS_LOG(INFO) << "SetCMD";
  427. {
  428. // print set cmd content
  429. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  430. for (auto node : recieved_nodes) {
  431. MS_LOG(INFO) << "node name: " << node.node_name();
  432. MS_LOG(INFO) << "node type: " << node.node_type();
  433. }
  434. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  435. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  436. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  437. }
  438. MS_LOG(INFO) << "Setting watchpoint";
  439. if (GetWatchpointDelete(reply)) {
  440. RemoveWatchpoint(GetWatchpointID(reply));
  441. } else {
  442. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply));
  443. }
  444. break;
  445. case DebuggerCommand::kViewCMD:
  446. MS_LOG(INFO) << "ViewCMD";
  447. {
  448. // print view cmd content
  449. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  450. for (auto tensor : received_tensors) {
  451. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  452. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  453. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  454. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  455. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  456. }
  457. }
  458. MS_LOG(INFO) << "Sending tensors";
  459. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  460. {
  461. // print view cmd reply
  462. for (auto tensor : tensors) {
  463. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  464. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  465. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  466. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  467. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  468. MS_LOG(INFO) << "tensor dims: ";
  469. for (auto dim : tensor.dims()) {
  470. MS_LOG(INFO) << dim << ",";
  471. }
  472. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  473. }
  474. }
  475. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  476. if (send_tensors_reply.status() != send_tensors_reply.OK) {
  477. MS_LOG(ERROR) << "Error: SendTensors failed";
  478. }
  479. break;
  480. }
  481. }
  482. }
  483. void AddTensorProtoInfo(TensorProto *tensor_item, TensorProto tensor) {
  484. tensor_item->set_node_name(tensor.node_name());
  485. tensor_item->set_slot(tensor.slot());
  486. tensor_item->set_iter(tensor.iter());
  487. tensor_item->set_truncate(tensor.truncate());
  488. tensor_item->clear_tensor_content();
  489. tensor_item->clear_data_type();
  490. tensor_item->clear_dims();
  491. }
  492. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id) {
  493. std::vector<std::tuple<std::string, bool>> check_node_list;
  494. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  495. [](WatchNode node) -> std::tuple<std::string, bool> {
  496. return make_tuple(node.node_name(), node.node_type() == "scope");
  497. });
  498. debug_services_->AddWatchpoint(id, condition.condition(), condition.value(), check_node_list);
  499. }
  500. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  501. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  502. std::vector<std::string> name;
  503. std::vector<std::string> ret_name;
  504. std::vector<char *> data_ptr;
  505. std::vector<unsigned int> data_size;
  506. std::vector<TypePtr> dtype;
  507. std::vector<std::vector<int>> shape;
  508. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  509. // ret_name will contain tensor names that are found in TensorLoader
  510. // items in ret_name will be in the same order with tensors if found
  511. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  512. std::list<TensorProto> tensor_list;
  513. unsigned int result_index = 0;
  514. for (auto tensor : tensors) {
  515. int size_iter = 0;
  516. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  517. TensorProto tensor_item;
  518. tensor_item.set_finished(true);
  519. AddTensorProtoInfo(&tensor_item, tensor);
  520. tensor_list.push_back(tensor_item);
  521. continue;
  522. }
  523. int tensor_size = data_size[result_index];
  524. while (size_iter < tensor_size) {
  525. int chunk_size = CHUNK_SIZE;
  526. TensorProto tensor_item;
  527. tensor_item.set_finished(false);
  528. if (tensor_size - size_iter <= CHUNK_SIZE) {
  529. chunk_size = tensor_size - size_iter;
  530. tensor_item.set_finished(true);
  531. }
  532. AddTensorProtoInfo(&tensor_item, tensor);
  533. // return empty tensor if didn't find the requested tensor
  534. tensor_item.set_tensor_content(data_ptr[result_index] + size_iter, chunk_size);
  535. tensor_item.set_data_type(GetDebuggerNumberDataType(dtype[result_index]));
  536. for (auto &elem : shape[result_index]) {
  537. tensor_item.add_dims(elem);
  538. }
  539. // add tensor to result list and increment result_index to check next item in ret_name
  540. tensor_list.push_back(tensor_item);
  541. size_iter += CHUNK_SIZE;
  542. }
  543. result_index++;
  544. }
  545. return tensor_list;
  546. }
  547. void Debugger::Exit() {
  548. // clear resource before exit
  549. // For node level, debugger has to exit itself because main thread can only exit in step bundary;
  550. // For step level, debugger will notify main thread to exit;
  551. if (run_level_ == "node") {
  552. pipeline::ClearResAtexit();
  553. exit(1);
  554. } else if (run_level_ == "step") {
  555. // Notify main thread to terminate
  556. pipeline::ExecutorPy::DebugTerminate(true);
  557. } else {
  558. pipeline::ClearResAtexit();
  559. exit(1);
  560. }
  561. }
  562. std::list<WatchpointHit> Debugger::CheckWatchpoints(const std::string &watchnode) {
  563. std::vector<std::string> name;
  564. std::vector<std::string> slot;
  565. std::vector<int> condition;
  566. std::vector<unsigned int> watchpoint_id;
  567. std::vector<std::string> overflow_ops;
  568. #ifdef ENABLE_D
  569. overflow_ops = CheckOpOverflow();
  570. #endif
  571. auto tensor_loader = debug_services_->tensor_loader();
  572. std::vector<std::shared_ptr<TensorData>> tensor_list;
  573. if (watchnode.empty()) {
  574. tensor_list = tensor_loader->GetTensor();
  575. } else {
  576. tensor_list = tensor_loader->GetNodeTensorMap(watchnode);
  577. }
  578. debug_services_->CheckWatchpoints(&name, &slot, &condition, &watchpoint_id, overflow_ops, tensor_list);
  579. std::list<WatchpointHit> hits;
  580. for (unsigned int i = 0; i < name.size(); i++) {
  581. WatchpointHit hit;
  582. hit.set_id(watchpoint_id[i]);
  583. // here TensorProto act as a tensor indicator, not sending tensor content
  584. TensorProto *tensor_item = hit.mutable_tensor();
  585. tensor_item->set_node_name(name[i]);
  586. tensor_item->set_slot(slot[i]);
  587. tensor_item->set_finished(true);
  588. WatchCondition *condition_item = hit.mutable_watch_condition();
  589. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  590. hits.push_back(hit);
  591. }
  592. return hits;
  593. }
  594. void Debugger::SendWatchpointsAndSuspend(const std::list<WatchpointHit> &points) {
  595. // send info about watchpoint
  596. if (!points.empty()) {
  597. EventReply reply = grpc_client_->SendWatchpointHits(points);
  598. if (reply.status() != reply.OK) {
  599. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  600. }
  601. }
  602. // enter command loop
  603. CommandLoop();
  604. }
  605. DebugServices *Debugger::debug_services() const { return debug_services_.get(); }
  606. bool Debugger::debugger_enabled() const { return debugger_enabled_; }
  607. DebuggerCommand GetCommand(const EventReply &reply) {
  608. DebuggerCommand cmd = DebuggerCommand::kUnknownCMD;
  609. switch (reply.cmd_case()) {
  610. case debugger::EventReply::CmdCase::kExit:
  611. cmd = DebuggerCommand::kExitCMD;
  612. break;
  613. case debugger::EventReply::CmdCase::kRunCmd:
  614. cmd = DebuggerCommand::kRunCMD;
  615. break;
  616. case debugger::EventReply::CmdCase::kSetCmd:
  617. cmd = DebuggerCommand::kSetCMD;
  618. break;
  619. case debugger::EventReply::CmdCase::kViewCmd:
  620. cmd = DebuggerCommand::kViewCMD;
  621. break;
  622. default:
  623. MS_LOG(DEBUG) << "Debug: UnknownCMD";
  624. break;
  625. }
  626. return cmd;
  627. }
  628. ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply) {
  629. if (!reply.has_set_cmd()) {
  630. MS_LOG(ERROR) << "Error: Not SetCMD, can not get WatchNodes. Returning default value: ProtoVector<WatchNode>().";
  631. return ProtoVector<WatchNode>();
  632. }
  633. return reply.set_cmd().watch_nodes();
  634. }
  635. std::string GetRunLevel(const EventReply &reply) {
  636. if (!reply.has_run_cmd()) {
  637. MS_LOG(ERROR) << "Error: Not RunCMD, can not get RunLevel. Returning default value: "
  638. "";
  639. return "";
  640. }
  641. return reply.run_cmd().run_level();
  642. }
  643. std::string GetNodeName(const EventReply &reply) {
  644. if (!reply.has_run_cmd()) {
  645. MS_LOG(ERROR) << "Error: Not RunCMD, can not get NodeName. Returning default value: "
  646. "";
  647. return "";
  648. }
  649. return reply.run_cmd().node_name();
  650. }
  651. WatchCondition GetWatchcondition(const EventReply &reply) {
  652. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  653. MS_LOG(ERROR) << "Error: Can not get WatchCondition from command. Returning default value: WatchCondition().";
  654. return WatchCondition();
  655. }
  656. return reply.set_cmd().watch_condition();
  657. }
  658. int32_t GetWatchpointID(const EventReply &reply) {
  659. if (!reply.has_set_cmd()) {
  660. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint ID. Returning default value: 0.";
  661. return 0;
  662. }
  663. return reply.set_cmd().id();
  664. }
  665. bool GetWatchpointDelete(const EventReply &reply) {
  666. if (!reply.has_set_cmd()) {
  667. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint delete flag. Returning default value: false.";
  668. return false;
  669. }
  670. return reply.set_cmd().delete_();
  671. }
  672. ProtoVector<TensorProto> GetTensors(const EventReply &reply) {
  673. if (!reply.has_view_cmd()) {
  674. MS_LOG(ERROR) << "Error: Not ViewCMD, can not get Tensors. Returning default value: ProtoVector<TensorProto>().";
  675. return ProtoVector<TensorProto>();
  676. }
  677. return reply.view_cmd().tensors();
  678. }
  679. std::string GetTensorFullName(const TensorProto &tensor) {
  680. string node_name = tensor.node_name();
  681. if (tensor.truncate()) {
  682. // scopes in node name are seperated by '/'
  683. // use the name without scope if truncate is true
  684. std::size_t found = node_name.find_last_of("/");
  685. node_name = node_name.substr(found + 1);
  686. }
  687. return node_name + ":" + tensor.slot() + (tensor.iter() == "" ? "" : ":" + tensor.iter());
  688. }
  689. bool Debugger::partial_memory() { return partial_memory_; }
  690. void Debugger::SetCurNode(std::string cur_name) {
  691. // access lock for public method
  692. std::lock_guard<std::mutex> a_lock(access_lock_);
  693. cur_name_ = cur_name;
  694. }
  695. std::string Debugger::run_level() const { return run_level_; }
  696. void Debugger::SetStepNum(int32_t cur_num_step) {
  697. // access lock for public method
  698. std::lock_guard<std::mutex> a_lock(access_lock_);
  699. num_step_ = cur_num_step;
  700. }
  701. int32_t Debugger::step_num() const { return num_step_; }
  702. uint64_t BytestoInt64(const std::vector<char> &buffer) {
  703. uint64_t ret;
  704. ret = ((uint64_t)buffer[7] << 56) | ((uint64_t)buffer[6] << 48) | ((uint64_t)buffer[5] << 40) |
  705. ((uint64_t)buffer[4] << 32) | ((uint64_t)buffer[3] << 24) | ((uint64_t)buffer[2] << 16) |
  706. ((uint64_t)buffer[1] << 8) | ((uint64_t)buffer[0]);
  707. return ret;
  708. }
  709. #define BUF_SIZ 256
  710. std::vector<std::string> Debugger::CheckOpOverflow() {
  711. std::vector<double> bin_list;
  712. std::vector<std::string> op_names;
  713. DIR *d;
  714. struct dirent *dir = nullptr;
  715. d = opendir(overflow_bin_path_.c_str());
  716. if (d != nullptr) {
  717. while ((dir = readdir(d)) != NULL) {
  718. if (dir->d_type == DT_REG) {
  719. std::string file_path = overflow_bin_path_;
  720. file_path.append(dir->d_name);
  721. std::string file_name = dir->d_name;
  722. std::size_t found = file_name.find_last_of(".");
  723. if (found == std::string::npos) {
  724. continue;
  725. }
  726. std::string overflow_time = file_name.substr(found + 1);
  727. if (stod(overflow_time) <= last_overflow_bin_) {
  728. MS_LOG(INFO) << "File already processed " << file_name;
  729. continue;
  730. }
  731. bin_list.push_back(stod(overflow_time));
  732. std::fstream infile;
  733. infile.open(file_path.c_str(), std::ios::binary | std::ios::in);
  734. if (!infile.is_open()) {
  735. MS_LOG(ERROR) << "Failed to open overflow bin file " << file_name;
  736. continue;
  737. }
  738. infile.seekg(313, std::ios::beg);
  739. std::vector<char> buffer;
  740. buffer.resize(BUF_SIZ);
  741. infile.read(buffer.data(), BUF_SIZ);
  742. uint64_t stream_id = BytestoInt64(std::vector<char>(buffer.begin() + 8, buffer.end()));
  743. uint64_t task_id = BytestoInt64(std::vector<char>(buffer.begin() + 16, buffer.end()));
  744. MS_LOG(INFO) << "Overflow stream_id " << stream_id << ", task_id " << task_id << ".";
  745. auto op = debugger_->stream_task_to_opname_.find(std::make_pair(stream_id, task_id));
  746. if (op != debugger_->stream_task_to_opname_.end()) {
  747. MS_LOG(ERROR) << "Overflow detected on node " << op->second << std::endl;
  748. op_names.push_back(op->second);
  749. } else {
  750. MS_LOG(INFO) << "No overflow is detected " << std::endl;
  751. }
  752. infile.close();
  753. }
  754. }
  755. } else {
  756. MS_LOG(INFO) << "OverFlow bin directory does not exist!";
  757. }
  758. closedir(d);
  759. if (op_names.size()) {
  760. MS_LOG(ERROR) << "These operation overflows are detected " << op_names;
  761. }
  762. for (auto &i : bin_list) {
  763. if (i > last_overflow_bin_) {
  764. last_overflow_bin_ = i;
  765. }
  766. }
  767. return op_names;
  768. }
  769. void Debugger::SetTrainingDone(bool training_done) { training_done_ = training_done; }
  770. bool Debugger::CheckPort(const char *port) {
  771. char *p = const_cast<char *>(port);
  772. int num = 0;
  773. if (*p == '0' && *(p + 1) != '\0') return false;
  774. while (*p != '\0') {
  775. if (*p < '0' || *p > '9') return false;
  776. num = num * 10 + (*p) - '0';
  777. if (num < 1 || num > 65535) return false;
  778. p++;
  779. }
  780. return true;
  781. }
  782. void Debugger::LoadParameters() {
  783. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  784. if (!(num_step_ == 0 || device_target_ == kAscendDevice ||
  785. (device_target_ == kGPUDevice && device::KernelRuntime::DumpDataEnabledIteration())))
  786. return;
  787. MS_EXCEPTION_IF_NULL(graph_ptr_);
  788. const auto &parameters = graph_ptr_->inputs();
  789. // for parameters, set its execution order to be 0;
  790. int exec_order = 0;
  791. for (auto &item : parameters) {
  792. if (!item->isa<Parameter>()) {
  793. continue;
  794. }
  795. std::string parameter_name = item->fullname_with_scope();
  796. auto addr = AnfAlgo::GetOutputAddr(item, PRAMATER_OUTPUT_INDEX);
  797. auto type = AnfAlgo::GetOutputInferDataType(item, PRAMATER_OUTPUT_INDEX);
  798. auto format = kOpFormat_DEFAULT;
  799. string tensor_name = parameter_name + ':' + "0";
  800. ShapeVector int_shapes;
  801. auto shape = AnfAlgo::GetOutputDeviceShape(item, PRAMATER_OUTPUT_INDEX);
  802. (void)std::transform(shape.begin(), shape.end(), std::back_inserter(int_shapes),
  803. [](size_t inner_item) { return SizeToInt(inner_item); });
  804. bool ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, 0, true);
  805. if (!ret) {
  806. MS_LOG(ERROR) << "LoadMemToHost:"
  807. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  808. }
  809. }
  810. }
  811. } // namespace mindspore