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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. }
  248. // if kernel is not watchpoint and is next_to or continue_to node, suspend.
  249. if (run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_)) {
  250. CommandLoop();
  251. }
  252. return;
  253. }
  254. }
  255. void Debugger::PostDebugOp() {
  256. // access lock for public method
  257. std::lock_guard<std::mutex> a_lock(access_lock_);
  258. // suspend if debugger is enabled
  259. if (debugger_enabled_ && !is_dataset_graph_) {
  260. MS_LOG(INFO) << "Debugger suspend at debug_op";
  261. CommandLoop();
  262. }
  263. }
  264. std::map<std::pair<uint32_t, uint32_t>, std::string> &Debugger::GetStreamTaskToOpnameMap() {
  265. return stream_task_to_opname_;
  266. }
  267. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  268. if (graph_ptr_ != graph_ptr) {
  269. MS_LOG(INFO) << "Debugger got new graph: " << graph_ptr->graph_id();
  270. // save new graph_ptr
  271. graph_ptr_ = graph_ptr;
  272. // check if it is dataset graph
  273. CheckDatasetGraph();
  274. if (!is_dataset_graph_) {
  275. // only try to enable debugger if it is not a dataset graph
  276. EnableDebugger();
  277. if (debugger_enabled_) {
  278. // get graph proto and send to mindinsight
  279. SendGraphAndSuspend(GetGraphProto());
  280. }
  281. }
  282. }
  283. }
  284. void Debugger::CheckDatasetGraph() {
  285. // print parameter node names
  286. const auto &params = graph_ptr_->inputs();
  287. for (const auto &param : params) {
  288. MS_LOG(INFO) << "param: " << param->fullname_with_scope();
  289. }
  290. // check if there is GetNext or InitDataSetQueue node
  291. const auto &nodes = graph_ptr_->execution_order();
  292. for (const auto &node : nodes) {
  293. auto node_name = AnfAlgo::GetCNodeName(node);
  294. MS_LOG(INFO) << "node: " << node->fullname_with_scope();
  295. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  296. MS_LOG(INFO) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  297. << node_name;
  298. is_dataset_graph_ = true;
  299. return;
  300. }
  301. }
  302. is_dataset_graph_ = false;
  303. }
  304. GraphProto Debugger::GetGraphProto() const {
  305. // convert kernel graph to debugger modelproto
  306. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr_);
  307. return model.graph();
  308. }
  309. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  310. SendMetadata();
  311. // send graph to mindinght server
  312. EventReply reply = grpc_client_->SendGraph(graph_proto);
  313. if (reply.status() != reply.OK) {
  314. MS_LOG(ERROR) << "Error: SendGraph failed";
  315. }
  316. // enter command loop, wait and process commands
  317. CommandLoop();
  318. }
  319. void Debugger::SendMetadata() {
  320. // prepare metadata
  321. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  322. Metadata metadata;
  323. metadata.set_device_name(device_name);
  324. metadata.set_cur_step(num_step_);
  325. metadata.set_backend(device_target_);
  326. metadata.set_cur_node(cur_name_);
  327. metadata.set_training_done(training_done_);
  328. MS_LOG(INFO) << "Is training done?" << training_done_;
  329. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  330. if (reply_metadata.status() != reply_metadata.OK) {
  331. MS_LOG(ERROR) << "Error: SendMetadata failed";
  332. }
  333. }
  334. void Debugger::CommandLoop() {
  335. // prepare metadata
  336. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  337. Metadata metadata;
  338. metadata.set_device_name(device_name);
  339. metadata.set_cur_step(num_step_);
  340. metadata.set_backend(device_target_);
  341. metadata.set_cur_node(cur_name_);
  342. metadata.set_training_done(training_done_);
  343. // loop exit flag
  344. bool run = false;
  345. int num_wait_fail = 0;
  346. const int max_num_wait_fail = 5;
  347. while (!run) {
  348. // wait for command
  349. EventReply reply = grpc_client_->WaitForCommand(metadata);
  350. if (reply.status() != reply.OK) {
  351. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  352. num_wait_fail++;
  353. if (num_wait_fail > max_num_wait_fail) {
  354. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session";
  355. Exit();
  356. }
  357. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  358. << num_wait_fail << "s";
  359. std::this_thread::sleep_for(std::chrono::milliseconds(1000 * num_wait_fail));
  360. continue;
  361. }
  362. // get type of the command in reply
  363. DebuggerCommand cmd = GetCommand(reply);
  364. if (cmd == DebuggerCommand::kUnknownCMD) {
  365. MS_LOG(ERROR) << "Error: debugger recieved unknown command";
  366. continue;
  367. }
  368. MS_LOG(INFO) << "recieved command: ";
  369. switch (cmd) {
  370. case DebuggerCommand::kUnknownCMD:
  371. MS_LOG(INFO) << "UnknownCMD";
  372. break;
  373. case DebuggerCommand::kExitCMD:
  374. MS_LOG(INFO) << "ExitCMD";
  375. Exit();
  376. break;
  377. case DebuggerCommand::kRunCMD:
  378. MS_LOG(INFO) << "RunCMD";
  379. {
  380. // print run cmd content
  381. // get run_level and node_name
  382. run_level_ = GetRunLevel(reply);
  383. node_name_ = GetNodeName(reply);
  384. MS_LOG(INFO) << "run_level: " << run_level_;
  385. MS_LOG(INFO) << "node_name_: " << node_name_;
  386. }
  387. // exit loop
  388. run = true;
  389. break;
  390. case DebuggerCommand::kSetCMD:
  391. MS_LOG(INFO) << "SetCMD";
  392. {
  393. // print set cmd content
  394. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  395. for (auto node : recieved_nodes) {
  396. MS_LOG(INFO) << "node name: " << node.node_name();
  397. MS_LOG(INFO) << "node type: " << node.node_type();
  398. }
  399. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  400. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  401. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  402. }
  403. MS_LOG(INFO) << "Setting watchpoint";
  404. if (GetWatchpointDelete(reply)) {
  405. RemoveWatchpoint(GetWatchpointID(reply));
  406. } else {
  407. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply));
  408. }
  409. break;
  410. case DebuggerCommand::kViewCMD:
  411. MS_LOG(INFO) << "ViewCMD";
  412. {
  413. // print view cmd content
  414. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  415. for (auto tensor : received_tensors) {
  416. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  417. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  418. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  419. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  420. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  421. }
  422. }
  423. MS_LOG(INFO) << "Sending tensors";
  424. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  425. {
  426. // print view cmd reply
  427. for (auto tensor : tensors) {
  428. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  429. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  430. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  431. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  432. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  433. MS_LOG(INFO) << "tensor dims: ";
  434. for (auto dim : tensor.dims()) {
  435. MS_LOG(INFO) << dim << ",";
  436. }
  437. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  438. }
  439. }
  440. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  441. if (send_tensors_reply.status() != send_tensors_reply.OK) {
  442. MS_LOG(ERROR) << "Error: SendTensors failed";
  443. }
  444. break;
  445. }
  446. }
  447. }
  448. void AddTensorProtoInfo(TensorProto *tensor_item, TensorProto tensor) {
  449. tensor_item->set_node_name(tensor.node_name());
  450. tensor_item->set_slot(tensor.slot());
  451. tensor_item->set_iter(tensor.iter());
  452. tensor_item->set_truncate(tensor.truncate());
  453. tensor_item->clear_tensor_content();
  454. tensor_item->clear_data_type();
  455. tensor_item->clear_dims();
  456. }
  457. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id) {
  458. std::vector<std::tuple<std::string, bool>> check_node_list;
  459. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  460. [](WatchNode node) -> std::tuple<std::string, bool> {
  461. return make_tuple(node.node_name(), node.node_type() == "scope");
  462. });
  463. debug_services_->AddWatchpoint(id, condition.condition(), condition.value(), check_node_list);
  464. }
  465. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  466. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  467. std::vector<std::string> name;
  468. std::vector<std::string> ret_name;
  469. std::vector<char *> data_ptr;
  470. std::vector<unsigned int> data_size;
  471. std::vector<TypePtr> dtype;
  472. std::vector<std::vector<int>> shape;
  473. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  474. // ret_name will contain tensor names that are found in TensorLoader
  475. // items in ret_name will be in the same order with tensors if found
  476. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  477. std::list<TensorProto> tensor_list;
  478. unsigned int result_index = 0;
  479. for (auto tensor : tensors) {
  480. int size_iter = 0;
  481. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  482. TensorProto tensor_item;
  483. tensor_item.set_finished(true);
  484. AddTensorProtoInfo(&tensor_item, tensor);
  485. tensor_list.push_back(tensor_item);
  486. continue;
  487. }
  488. int tensor_size = data_size[result_index];
  489. while (size_iter < tensor_size) {
  490. int chunk_size = CHUNK_SIZE;
  491. TensorProto tensor_item;
  492. tensor_item.set_finished(false);
  493. if (tensor_size - size_iter <= CHUNK_SIZE) {
  494. chunk_size = tensor_size - size_iter;
  495. tensor_item.set_finished(true);
  496. }
  497. AddTensorProtoInfo(&tensor_item, tensor);
  498. // return empty tensor if didn't find the requested tensor
  499. tensor_item.set_tensor_content(data_ptr[result_index] + size_iter, chunk_size);
  500. tensor_item.set_data_type(GetDebuggerNumberDataType(dtype[result_index]));
  501. for (auto &elem : shape[result_index]) {
  502. tensor_item.add_dims(elem);
  503. }
  504. // add tensor to result list and increment result_index to check next item in ret_name
  505. tensor_list.push_back(tensor_item);
  506. size_iter += CHUNK_SIZE;
  507. }
  508. result_index++;
  509. }
  510. return tensor_list;
  511. }
  512. void Debugger::Exit() {
  513. // clear resource before exit
  514. pipeline::ClearResAtexit();
  515. std::exit(EXIT_FAILURE);
  516. }
  517. std::list<WatchpointHit> Debugger::CheckWatchpoints(const std::string &watchnode) {
  518. std::vector<std::string> name;
  519. std::vector<std::string> slot;
  520. std::vector<int> condition;
  521. std::vector<unsigned int> watchpoint_id;
  522. std::vector<std::string> overflow_ops;
  523. #ifdef ENABLE_D
  524. overflow_ops = CheckOpOverflow();
  525. #endif
  526. auto tensor_loader = debug_services_->tensor_loader();
  527. std::vector<std::shared_ptr<TensorData>> tensor_list;
  528. if (watchnode.empty()) {
  529. tensor_list = tensor_loader->GetTensor();
  530. } else {
  531. tensor_list = tensor_loader->GetNodeTensorMap(watchnode);
  532. }
  533. debug_services_->CheckWatchpoints(&name, &slot, &condition, &watchpoint_id, overflow_ops, tensor_list);
  534. std::list<WatchpointHit> hits;
  535. for (unsigned int i = 0; i < name.size(); i++) {
  536. WatchpointHit hit;
  537. hit.set_id(watchpoint_id[i]);
  538. // here TensorProto act as a tensor indicator, not sending tensor content
  539. TensorProto *tensor_item = hit.mutable_tensor();
  540. tensor_item->set_node_name(name[i]);
  541. tensor_item->set_slot(slot[i]);
  542. tensor_item->set_finished(true);
  543. WatchCondition *condition_item = hit.mutable_watch_condition();
  544. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  545. hits.push_back(hit);
  546. }
  547. return hits;
  548. }
  549. void Debugger::SendWatchpointsAndSuspend(const std::list<WatchpointHit> &points) {
  550. // send info about watchpoint
  551. if (!points.empty()) {
  552. EventReply reply = grpc_client_->SendWatchpointHits(points);
  553. if (reply.status() != reply.OK) {
  554. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  555. }
  556. }
  557. // enter command loop
  558. CommandLoop();
  559. }
  560. DebugServices *Debugger::debug_services() const { return debug_services_.get(); }
  561. bool Debugger::debugger_enabled() const { return debugger_enabled_; }
  562. DebuggerCommand GetCommand(const EventReply &reply) {
  563. DebuggerCommand cmd = DebuggerCommand::kUnknownCMD;
  564. switch (reply.cmd_case()) {
  565. case debugger::EventReply::CmdCase::kExit:
  566. cmd = DebuggerCommand::kExitCMD;
  567. break;
  568. case debugger::EventReply::CmdCase::kRunCmd:
  569. cmd = DebuggerCommand::kRunCMD;
  570. break;
  571. case debugger::EventReply::CmdCase::kSetCmd:
  572. cmd = DebuggerCommand::kSetCMD;
  573. break;
  574. case debugger::EventReply::CmdCase::kViewCmd:
  575. cmd = DebuggerCommand::kViewCMD;
  576. break;
  577. default:
  578. MS_LOG(ERROR) << "Error: UnknownCMD";
  579. break;
  580. }
  581. return cmd;
  582. }
  583. ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply) {
  584. if (!reply.has_set_cmd()) {
  585. MS_LOG(ERROR) << "Error: Not SetCMD, can not get WatchNodes. Returning default value: ProtoVector<WatchNode>().";
  586. return ProtoVector<WatchNode>();
  587. }
  588. return reply.set_cmd().watch_nodes();
  589. }
  590. std::string GetRunLevel(const EventReply &reply) {
  591. if (!reply.has_run_cmd()) {
  592. MS_LOG(ERROR) << "Error: Not RunCMD, can not get RunLevel. Returning default value: "
  593. "";
  594. return "";
  595. }
  596. return reply.run_cmd().run_level();
  597. }
  598. std::string GetNodeName(const EventReply &reply) {
  599. if (!reply.has_run_cmd()) {
  600. MS_LOG(ERROR) << "Error: Not RunCMD, can not get NodeName. Returning default value: "
  601. "";
  602. return "";
  603. }
  604. return reply.run_cmd().node_name();
  605. }
  606. WatchCondition GetWatchcondition(const EventReply &reply) {
  607. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  608. MS_LOG(ERROR) << "Error: Can not get WatchCondition from command. Returning default value: WatchCondition().";
  609. return WatchCondition();
  610. }
  611. return reply.set_cmd().watch_condition();
  612. }
  613. int32_t GetWatchpointID(const EventReply &reply) {
  614. if (!reply.has_set_cmd()) {
  615. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint ID. Returning default value: 0.";
  616. return 0;
  617. }
  618. return reply.set_cmd().id();
  619. }
  620. bool GetWatchpointDelete(const EventReply &reply) {
  621. if (!reply.has_set_cmd()) {
  622. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint delete flag. Returning default value: false.";
  623. return false;
  624. }
  625. return reply.set_cmd().delete_();
  626. }
  627. ProtoVector<TensorProto> GetTensors(const EventReply &reply) {
  628. if (!reply.has_view_cmd()) {
  629. MS_LOG(ERROR) << "Error: Not ViewCMD, can not get Tensors. Returning default value: ProtoVector<TensorProto>().";
  630. return ProtoVector<TensorProto>();
  631. }
  632. return reply.view_cmd().tensors();
  633. }
  634. std::string GetTensorFullName(const TensorProto &tensor) {
  635. string node_name = tensor.node_name();
  636. if (tensor.truncate()) {
  637. // scopes in node name are seperated by '/'
  638. // use the name without scope if truncate is true
  639. std::size_t found = node_name.find_last_of("/");
  640. node_name = node_name.substr(found + 1);
  641. }
  642. return node_name + ":" + tensor.slot() + (tensor.iter() == "" ? "" : ":" + tensor.iter());
  643. }
  644. bool Debugger::partial_memory() { return partial_memory_; }
  645. void Debugger::SetCurNode(std::string cur_name) {
  646. // access lock for public method
  647. std::lock_guard<std::mutex> a_lock(access_lock_);
  648. cur_name_ = cur_name;
  649. }
  650. std::string Debugger::run_level() const { return run_level_; }
  651. void Debugger::SetStepNum(int32_t cur_num_step) {
  652. // access lock for public method
  653. std::lock_guard<std::mutex> a_lock(access_lock_);
  654. num_step_ = cur_num_step;
  655. }
  656. int32_t Debugger::step_num() const { return num_step_; }
  657. uint64_t BytestoInt64(const std::vector<char> &buffer) {
  658. uint64_t ret;
  659. ret = ((uint64_t)buffer[7] << 56) | ((uint64_t)buffer[6] << 48) | ((uint64_t)buffer[5] << 40) |
  660. ((uint64_t)buffer[4] << 32) | (buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0];
  661. return ret;
  662. }
  663. #define BUF_SIZ 256
  664. std::vector<std::string> Debugger::CheckOpOverflow() {
  665. std::vector<double> bin_list;
  666. std::vector<std::string> op_names;
  667. DIR *d;
  668. struct dirent *dir = nullptr;
  669. d = opendir(overflow_bin_path_.c_str());
  670. if (d != nullptr) {
  671. while ((dir = readdir(d)) != NULL) {
  672. if (dir->d_type == DT_REG) {
  673. std::string file_path = overflow_bin_path_;
  674. file_path.append(dir->d_name);
  675. std::string file_name = dir->d_name;
  676. std::size_t found = file_name.find_last_of(".");
  677. if (found == std::string::npos) {
  678. continue;
  679. }
  680. std::string overflow_time = file_name.substr(found + 1);
  681. if (stod(overflow_time) <= last_overflow_bin_) {
  682. MS_LOG(INFO) << "File already processed " << file_name;
  683. continue;
  684. }
  685. bin_list.push_back(stod(overflow_time));
  686. std::fstream infile;
  687. infile.open(file_path.c_str(), std::ios::binary | std::ios::in);
  688. infile.seekg(313, std::ios::beg);
  689. std::vector<char> buffer;
  690. buffer.resize(BUF_SIZ);
  691. infile.read(buffer.data(), BUF_SIZ);
  692. uint64_t stream_id = BytestoInt64(std::vector<char>(buffer.begin() + 8, buffer.end()));
  693. uint64_t task_id = BytestoInt64(std::vector<char>(buffer.begin() + 16, buffer.end()));
  694. MS_LOG(INFO) << "Overflow stream_id " << stream_id << ", task_id " << task_id << ".";
  695. auto op = debugger_->stream_task_to_opname_.find(std::make_pair(stream_id, task_id));
  696. if (op != debugger_->stream_task_to_opname_.end()) {
  697. MS_LOG(ERROR) << "Overflow detected on node " << op->second << std::endl;
  698. op_names.push_back(op->second);
  699. } else {
  700. MS_LOG(INFO) << "No overflow is detected " << std::endl;
  701. }
  702. infile.close();
  703. }
  704. }
  705. } else {
  706. MS_LOG(INFO) << "OverFlow bin directory does not exist!";
  707. }
  708. closedir(d);
  709. if (op_names.size()) {
  710. MS_LOG(ERROR) << "These operation overflows are detected " << op_names;
  711. }
  712. for (auto &i : bin_list) {
  713. if (i > last_overflow_bin_) {
  714. last_overflow_bin_ = i;
  715. }
  716. }
  717. return op_names;
  718. }
  719. void Debugger::SetTrainingDone(bool training_done) { training_done_ = training_done; }
  720. } // namespace mindspore