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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 <fstream>
  17. #include <tuple>
  18. #include <vector>
  19. #include <algorithm>
  20. #include "debug/debugger/debugger.h"
  21. #include "pipeline/jit/pipeline.h"
  22. #include "backend/session/anf_runtime_algorithm.h"
  23. using debugger::EventReply;
  24. using debugger::GraphProto;
  25. using debugger::ModelProto;
  26. using debugger::TensorProto;
  27. using debugger::WatchCondition;
  28. using debugger::WatchCondition_Condition_inf;
  29. using debugger::WatchCondition_Condition_nan;
  30. using debugger::WatchNode;
  31. using debugger::WatchpointHit;
  32. namespace mindspore {
  33. DebuggerPtr Debugger::debugger_ = nullptr;
  34. std::mutex Debugger::instance_lock_;
  35. Debugger::Debugger()
  36. : grpc_client_(nullptr),
  37. debug_services_(nullptr),
  38. device_id_(0),
  39. num_step_(0),
  40. debugger_enabled_(false),
  41. is_dataset_graph_(false),
  42. partial_memory_(false) {}
  43. void Debugger::Init(const uint32_t device_id) {
  44. // access lock for public method
  45. std::lock_guard<std::mutex> a_lock(access_lock_);
  46. // save device_id
  47. MS_LOG(INFO) << "Debugger got device_id: " << device_id;
  48. device_id_ = device_id;
  49. }
  50. void Debugger::EnableDebugger() {
  51. // reset some of the class members
  52. num_step_ = 0;
  53. debugger_enabled_ = false;
  54. partial_memory_ = false;
  55. grpc_client_ = nullptr;
  56. debug_services_ = nullptr;
  57. // get env variables to configure debugger
  58. const char *env_enable_str = std::getenv("ENABLE_MS_DEBUGGER");
  59. if (env_enable_str != nullptr) {
  60. MS_LOG(INFO) << "Getenv ENABLE_MS_DEBUGGER: " << env_enable_str;
  61. if (std::strcmp(env_enable_str, "1") == 0) {
  62. debugger_enabled_ = true;
  63. }
  64. }
  65. if (!debugger_enabled_) {
  66. MS_LOG(WARNING) << "Not enabling debugger. Set environment variable ENABLE_MS_DEBUGGER=1 to enable debugger.";
  67. return;
  68. }
  69. // configure grpc host
  70. const char *env_host_str = std::getenv("MS_DEBUGGER_HOST");
  71. std::string host;
  72. if (env_host_str != nullptr) {
  73. MS_LOG(INFO) << "Getenv MS_DEBUGGER_HOST: " << env_host_str;
  74. host = std::string(env_host_str);
  75. } else {
  76. MS_LOG(WARNING) << "Environment variable MS_DEBUGGER_HOST doesn't exist. Using default debugger host: localhost";
  77. host = "localhost";
  78. }
  79. // configure grpc port
  80. const char *env_port_str = std::getenv("MS_DEBUGGER_PORT");
  81. std::string port;
  82. if (env_port_str != nullptr) {
  83. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PORT: " << env_port_str;
  84. port = std::string(env_port_str);
  85. } else {
  86. MS_LOG(WARNING) << "Environment variable MS_DEBUGGER_PORT doesn't exist. Using default debugger port: 50051";
  87. port = "50051";
  88. }
  89. // configure partial memory reuse
  90. const char *env_partial_mem_str = std::getenv("MS_DEBUGGER_PARTIAL_MEM");
  91. if (env_partial_mem_str != nullptr) {
  92. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PARTIAL_MEM: " << env_partial_mem_str;
  93. if (std::strcmp(env_partial_mem_str, "1") == 0) {
  94. partial_memory_ = true;
  95. }
  96. }
  97. // switch memory reuse on or off
  98. auto context_ptr = MsContext::GetInstance();
  99. MS_EXCEPTION_IF_NULL(context_ptr);
  100. context_ptr->set_enable_mem_reuse(partial_memory_);
  101. // print some message about memory reuse to user
  102. if (partial_memory_) {
  103. MS_LOG(WARNING) << "Partial Memory Reuse is enabled. Note: 1. Please only set watchpoints before running the first "
  104. "step. 2. Tensor values are only available for nodes that are watched by any watchpoint.";
  105. } else {
  106. MS_LOG(WARNING) << "Memory Reuse is disabled. Set environment variable MS_DEBUGGER_PARTIAL_MEM=1 to reduce memory "
  107. "usage for large models.";
  108. }
  109. // initialize grpc client
  110. grpc_client_ = std::make_unique<GrpcClient>(host, port);
  111. debug_services_ = std::make_unique<DebugServices>();
  112. }
  113. void Debugger::Reset() {
  114. // access lock for public method
  115. std::lock_guard<std::mutex> a_lock(access_lock_);
  116. // reset components
  117. device_id_ = 0;
  118. num_step_ = 0;
  119. debugger_enabled_ = false;
  120. is_dataset_graph_ = false;
  121. partial_memory_ = false;
  122. graph_ptr_ = nullptr;
  123. grpc_client_ = nullptr;
  124. debug_services_ = nullptr;
  125. }
  126. void Debugger::PreExecute(const KernelGraphPtr &graph_ptr) {
  127. // access lock for public method
  128. std::lock_guard<std::mutex> a_lock(access_lock_);
  129. // check and save graph_ptr, suspend if graph is new
  130. CheckGraphPtr(graph_ptr);
  131. }
  132. void Debugger::PostExecute() {
  133. // access lock for public method
  134. std::lock_guard<std::mutex> a_lock(access_lock_);
  135. // analyze tensor data and send the watchpoints been hit
  136. if (debugger_enabled_ && !is_dataset_graph_) {
  137. num_step_++;
  138. MS_LOG(INFO) << "Debugger suspend at end of step; number of steps executed: " << num_step_;
  139. SendWatchpointsAndSuspend(CheckWatchpoints());
  140. }
  141. }
  142. void Debugger::PostDebugOp() {
  143. // access lock for public method
  144. std::lock_guard<std::mutex> a_lock(access_lock_);
  145. // suspend if debugger is enabled
  146. if (debugger_enabled_ && !is_dataset_graph_) {
  147. MS_LOG(INFO) << "Debugger suspend at debug_op";
  148. CommandLoop();
  149. }
  150. }
  151. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  152. if (graph_ptr_ != graph_ptr) {
  153. MS_LOG(INFO) << "Debugger got new graph: " << graph_ptr->graph_id();
  154. // save new graph_ptr
  155. graph_ptr_ = graph_ptr;
  156. // check if it is dataset graph
  157. CheckDatasetGraph();
  158. if (!is_dataset_graph_) {
  159. // only try to enable debugger if it is not a dataset graph
  160. EnableDebugger();
  161. if (debugger_enabled_) {
  162. // get graph proto and send to mindinsight
  163. SendGraphAndSuspend(GetGraphProto());
  164. }
  165. }
  166. }
  167. }
  168. void Debugger::CheckDatasetGraph() {
  169. // print parameter node names
  170. const auto &params = graph_ptr_->inputs();
  171. for (const auto &param : params) {
  172. MS_LOG(INFO) << "param: " << param->fullname_with_scope();
  173. }
  174. // check if there is GetNext or InitDataSetQueue node
  175. const auto &nodes = graph_ptr_->execution_order();
  176. for (const auto &node : nodes) {
  177. auto node_name = AnfAlgo::GetCNodeName(node);
  178. MS_LOG(INFO) << "node: " << node->fullname_with_scope();
  179. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  180. MS_LOG(WARNING) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  181. << node_name;
  182. is_dataset_graph_ = true;
  183. return;
  184. }
  185. }
  186. is_dataset_graph_ = false;
  187. }
  188. GraphProto Debugger::GetGraphProto() const {
  189. // convert kernel graph to debugger modelproto
  190. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr_);
  191. return model.graph();
  192. }
  193. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  194. // prepare metadata
  195. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  196. Metadata metadata;
  197. metadata.set_device_name(device_name);
  198. metadata.set_cur_step(num_step_);
  199. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  200. if (reply_metadata.status() != reply_metadata.OK) {
  201. MS_LOG(ERROR) << "Error: SendMetadata failed";
  202. }
  203. // send graph to mindinght server
  204. EventReply reply = grpc_client_->SendGraph(graph_proto);
  205. if (reply.status() != reply.OK) {
  206. MS_LOG(ERROR) << "Error: SendGraph failed";
  207. }
  208. // enter command loop, wait and process commands
  209. CommandLoop();
  210. }
  211. void Debugger::CommandLoop() {
  212. // prepare metadata
  213. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  214. Metadata metadata;
  215. metadata.set_device_name(device_name);
  216. metadata.set_cur_step(num_step_);
  217. // loop exit flag
  218. bool run = false;
  219. int num_wait_fail = 0;
  220. const int max_num_wait_fail = 5;
  221. while (!run) {
  222. // wait for command
  223. EventReply reply = grpc_client_->WaitForCommand(metadata);
  224. if (reply.status() != reply.OK) {
  225. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  226. num_wait_fail++;
  227. if (num_wait_fail > max_num_wait_fail) {
  228. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session";
  229. Exit();
  230. }
  231. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  232. << num_wait_fail << "s";
  233. std::this_thread::sleep_for(std::chrono::milliseconds(1000 * num_wait_fail));
  234. continue;
  235. }
  236. // get type of the command in reply
  237. DebuggerCommand cmd = GetCommand(reply);
  238. if (cmd == DebuggerCommand::kUnknownCMD) {
  239. MS_LOG(ERROR) << "Error: debugger recieved unknown command";
  240. continue;
  241. }
  242. MS_LOG(INFO) << "recieved command: ";
  243. switch (cmd) {
  244. case DebuggerCommand::kUnknownCMD:
  245. MS_LOG(INFO) << "UnknownCMD";
  246. break;
  247. case DebuggerCommand::kExitCMD:
  248. MS_LOG(INFO) << "ExitCMD";
  249. Exit();
  250. break;
  251. case DebuggerCommand::kRunCMD:
  252. MS_LOG(INFO) << "RunCMD";
  253. // exit loop
  254. run = true;
  255. break;
  256. case DebuggerCommand::kSetCMD:
  257. MS_LOG(INFO) << "SetCMD";
  258. {
  259. // print set cmd content
  260. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  261. for (auto node : recieved_nodes) {
  262. MS_LOG(INFO) << "node name: " << node.node_name();
  263. MS_LOG(INFO) << "node type: " << node.node_type();
  264. }
  265. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  266. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  267. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  268. }
  269. MS_LOG(INFO) << "Setting watchpoint";
  270. if (GetWatchpointDelete(reply)) {
  271. RemoveWatchpoint(GetWatchpointID(reply));
  272. } else {
  273. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply));
  274. }
  275. break;
  276. case DebuggerCommand::kViewCMD:
  277. MS_LOG(INFO) << "ViewCMD";
  278. {
  279. // print view cmd content
  280. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  281. for (auto tensor : received_tensors) {
  282. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  283. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  284. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  285. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  286. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  287. }
  288. }
  289. MS_LOG(INFO) << "Sending tensors";
  290. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  291. {
  292. // print view cmd reply
  293. for (auto tensor : tensors) {
  294. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  295. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  296. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  297. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  298. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  299. MS_LOG(INFO) << "tensor dims: ";
  300. for (auto dim : tensor.dims()) {
  301. MS_LOG(INFO) << dim << ",";
  302. }
  303. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  304. }
  305. }
  306. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  307. if (send_tensors_reply.status() != send_tensors_reply.OK) {
  308. MS_LOG(ERROR) << "Error: SendTensors failed";
  309. }
  310. break;
  311. }
  312. }
  313. }
  314. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id) {
  315. std::vector<std::tuple<std::string, bool>> check_node_list;
  316. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  317. [](WatchNode node) -> std::tuple<std::string, bool> {
  318. return make_tuple(node.node_name(), node.node_type() == "scope");
  319. });
  320. debug_services_->AddWatchpoint(id, condition.condition(), check_node_list);
  321. }
  322. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  323. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  324. std::vector<std::string> name;
  325. std::vector<std::string> ret_name;
  326. std::vector<char *> data_ptr;
  327. std::vector<unsigned int> data_size;
  328. std::vector<TypePtr> dtype;
  329. std::vector<std::vector<int>> shape;
  330. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  331. // ret_name will contain tensor names that are found in TensorLoader
  332. // items in ret_name will be in the same order with tensors if found
  333. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  334. std::list<TensorProto> tensor_list;
  335. unsigned int result_index = 0;
  336. for (auto tensor : tensors) {
  337. TensorProto tensor_item;
  338. tensor_item.set_node_name(tensor.node_name());
  339. tensor_item.set_slot(tensor.slot());
  340. tensor_item.set_iter(tensor.iter());
  341. tensor_item.set_truncate(tensor.truncate());
  342. tensor_item.clear_tensor_content();
  343. tensor_item.clear_data_type();
  344. tensor_item.clear_dims();
  345. // always set finished to true before big tensor splitting is supported
  346. tensor_item.set_finished(true);
  347. // return empty tensor if didn't find the requested tensor
  348. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  349. tensor_list.push_back(tensor_item);
  350. continue;
  351. }
  352. tensor_item.set_tensor_content(data_ptr[result_index], data_size[result_index]);
  353. tensor_item.set_data_type(GetDebuggerNumberDataType(dtype[result_index]));
  354. for (auto &elem : shape[result_index]) {
  355. tensor_item.add_dims(elem);
  356. }
  357. // add tensor to result list and increment result_index to check next item in ret_name
  358. tensor_list.push_back(tensor_item);
  359. result_index++;
  360. }
  361. return tensor_list;
  362. }
  363. void Debugger::Exit() {
  364. // clear resource before exit
  365. pipeline::ClearResAtexit();
  366. std::exit(EXIT_FAILURE);
  367. }
  368. std::list<WatchpointHit> Debugger::CheckWatchpoints() const {
  369. std::vector<std::string> name;
  370. std::vector<std::string> slot;
  371. std::vector<char *> data_ptr;
  372. std::vector<unsigned int> data_size;
  373. std::vector<int> condition;
  374. std::vector<unsigned int> watchpoint_id;
  375. debug_services_->CheckWatchpoints(&name, &slot, &data_ptr, &data_size, &condition, &watchpoint_id);
  376. std::list<WatchpointHit> hits;
  377. for (unsigned int i = 0; i < name.size(); i++) {
  378. WatchpointHit hit;
  379. hit.set_id(watchpoint_id[i]);
  380. // here TensorProto act as a tensor indicator, not sending tensor content
  381. TensorProto *tensor_item = hit.mutable_tensor();
  382. tensor_item->set_node_name(name[i]);
  383. tensor_item->set_slot(slot[i]);
  384. tensor_item->set_finished(true);
  385. WatchCondition *condition_item = hit.mutable_watch_condition();
  386. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  387. hits.push_back(hit);
  388. }
  389. return hits;
  390. }
  391. void Debugger::SendWatchpointsAndSuspend(const std::list<WatchpointHit> &points) {
  392. // send info about watchpoint
  393. if (!points.empty()) {
  394. EventReply reply = grpc_client_->SendWatchpointHits(points);
  395. if (reply.status() != reply.OK) {
  396. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  397. }
  398. }
  399. // enter command loop
  400. CommandLoop();
  401. }
  402. DebugServices *Debugger::debug_services() const { return debug_services_.get(); }
  403. bool Debugger::debugger_enabled() const { return debugger_enabled_; }
  404. DebuggerCommand GetCommand(const EventReply &reply) {
  405. DebuggerCommand cmd = DebuggerCommand::kUnknownCMD;
  406. switch (reply.cmd_case()) {
  407. case debugger::EventReply::CmdCase::kExit:
  408. cmd = DebuggerCommand::kExitCMD;
  409. break;
  410. case debugger::EventReply::CmdCase::kRunCmd:
  411. cmd = DebuggerCommand::kRunCMD;
  412. break;
  413. case debugger::EventReply::CmdCase::kSetCmd:
  414. cmd = DebuggerCommand::kSetCMD;
  415. break;
  416. case debugger::EventReply::CmdCase::kViewCmd:
  417. cmd = DebuggerCommand::kViewCMD;
  418. break;
  419. default:
  420. MS_LOG(ERROR) << "Error: UnknownCMD";
  421. break;
  422. }
  423. return cmd;
  424. }
  425. ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply) {
  426. if (!reply.has_set_cmd()) {
  427. MS_LOG(ERROR) << "Error: Not SetCMD, can not get WatchNodes. Returning default value: ProtoVector<WatchNode>().";
  428. return ProtoVector<WatchNode>();
  429. }
  430. return reply.set_cmd().watch_nodes();
  431. }
  432. WatchCondition GetWatchcondition(const EventReply &reply) {
  433. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  434. MS_LOG(ERROR) << "Error: Can not get WatchCondition from command. Returning default value: WatchCondition().";
  435. return WatchCondition();
  436. }
  437. return reply.set_cmd().watch_condition();
  438. }
  439. int32_t GetWatchpointID(const EventReply &reply) {
  440. if (!reply.has_set_cmd()) {
  441. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint ID. Returning default value: 0.";
  442. return 0;
  443. }
  444. return reply.set_cmd().id();
  445. }
  446. bool GetWatchpointDelete(const EventReply &reply) {
  447. if (!reply.has_set_cmd()) {
  448. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint delete flag. Returning default value: false.";
  449. return false;
  450. }
  451. return reply.set_cmd().delete_();
  452. }
  453. ProtoVector<TensorProto> GetTensors(const EventReply &reply) {
  454. if (!reply.has_view_cmd()) {
  455. MS_LOG(ERROR) << "Error: Not ViewCMD, can not get Tensors. Returning default value: ProtoVector<TensorProto>().";
  456. return ProtoVector<TensorProto>();
  457. }
  458. return reply.view_cmd().tensors();
  459. }
  460. std::string GetTensorFullName(const TensorProto &tensor) {
  461. string node_name = tensor.node_name();
  462. if (tensor.truncate()) {
  463. // scopes in node name are seperated by '/'
  464. // use the name without scope if truncate is true
  465. std::size_t found = node_name.find_last_of("/");
  466. node_name = node_name.substr(found + 1);
  467. }
  468. return node_name + ":" + tensor.slot() + (tensor.iter() == "" ? "" : ":" + tensor.iter());
  469. }
  470. bool Debugger::partial_memory() { return partial_memory_; }
  471. } // namespace mindspore