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

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