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

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