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

5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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.h"
  34. #include "utils/config_manager.h"
  35. #include "debug/env_config_parser.h"
  36. using debugger::Chunk;
  37. using debugger::EventReply;
  38. using debugger::GraphProto;
  39. using debugger::ModelProto;
  40. using debugger::TensorProto;
  41. using debugger::WatchCondition;
  42. using debugger::WatchCondition_Condition_inf;
  43. using debugger::WatchCondition_Condition_nan;
  44. using debugger::WatchCondition_Parameter;
  45. using debugger::WatchNode;
  46. using debugger::WatchpointHit;
  47. #define CHUNK_SIZE 1024 * 1024 * 3
  48. namespace mindspore {
  49. DebuggerPtr Debugger::debugger_ = nullptr;
  50. std::mutex Debugger::instance_lock_;
  51. Debugger::Debugger()
  52. : grpc_client_(nullptr),
  53. debug_services_(nullptr),
  54. device_id_(0),
  55. device_target_(""),
  56. num_step_(0),
  57. debugger_enabled_(false),
  58. run_level_(""),
  59. node_name_(""),
  60. cur_name_(""),
  61. training_done_(false),
  62. is_dataset_graph_(false),
  63. partial_memory_(false),
  64. last_overflow_bin_(0),
  65. initial_suspend_(true),
  66. not_dataset_graph_sum_(0),
  67. version_("") {
  68. CheckDebuggerEnabledParam();
  69. auto ms_context = MsContext::GetInstance();
  70. MS_EXCEPTION_IF_NULL(ms_context);
  71. std::string device_target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  72. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  73. if (device_target == kCPUDevice) {
  74. MS_LOG(WARNING) << "Not enabling debugger. Debugger does not support CPU.";
  75. } else if (CheckDebuggerEnabled()) {
  76. // configure partial memory reuse
  77. partial_memory_ = CheckDebuggerPartialMemoryEnabled();
  78. // switch memory reuse on or off
  79. EnvConfigParser::GetInstance().SetSysMemreuse(partial_memory_);
  80. // print some message about memory reuse to user
  81. if (partial_memory_) {
  82. MS_LOG(WARNING)
  83. << "Partial Memory Reuse is enabled. Note: 1. Please only set watchpoints before running the first "
  84. "step. 2. Tensor values are only available for nodes that are watched by any watchpoint.";
  85. } else {
  86. MS_LOG(WARNING)
  87. << "Memory Reuse is disabled. Set environment variable MS_DEBUGGER_PARTIAL_MEM=1 to reduce memory "
  88. "usage for large models.";
  89. }
  90. }
  91. }
  92. void Debugger::Init(const uint32_t device_id, const std::string device_target) {
  93. // access lock for public method
  94. std::lock_guard<std::mutex> a_lock(access_lock_);
  95. // save device_id
  96. MS_LOG(INFO) << "Debugger got device_id: " << device_id;
  97. device_id_ = device_id;
  98. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  99. device_target_ = device_target;
  100. version_ = "1.2.0";
  101. }
  102. bool IsTypeDebuggerSupported(TypeId type) {
  103. if (type < TypeId::kNumberTypeEnd && type > TypeId::kNumberTypeBegin && type != kNumberTypeComplex64) {
  104. return true;
  105. } else {
  106. MS_LOG(WARNING) << "Debugger does not support type id: " << type;
  107. return false;
  108. }
  109. }
  110. void Debugger::EnableDebugger() {
  111. // reset some of the class members
  112. num_step_ = 0;
  113. debugger_enabled_ = false;
  114. partial_memory_ = false;
  115. grpc_client_ = nullptr;
  116. debug_services_ = nullptr;
  117. // see if dump using debugger backend is enabled
  118. bool dump_enabled = CheckDebuggerDumpEnabled();
  119. MS_LOG(INFO) << "dump using debugger backend = " << dump_enabled;
  120. // check if debugger enabled
  121. debugger_enabled_ = CheckDebuggerEnabled();
  122. MS_LOG(INFO) << "debugger_enabled_ = " << debugger_enabled_;
  123. if (!debugger_enabled_ && !dump_enabled) {
  124. MS_LOG(INFO) << "Not enabling debugger. Set environment variable ENABLE_MS_DEBUGGER=1 to enable debugger.";
  125. return;
  126. }
  127. if (debugger_enabled_) {
  128. // configure grpc host
  129. const char *env_host_str = std::getenv("MS_DEBUGGER_HOST");
  130. std::string host;
  131. if (env_host_str != nullptr) {
  132. if (CheckIp(env_host_str)) {
  133. MS_LOG(INFO) << "Getenv MS_DEBUGGER_HOST: " << env_host_str;
  134. host = std::string(env_host_str);
  135. } else {
  136. debugger_enabled_ = false;
  137. MS_EXCEPTION(ValueError) << "Environment variable MS_DEBUGGER_HOST isn't a valid IP address. "
  138. "Please set environment variable MS_DEBUGGER_HOST=x.x.x.x to a valid IP";
  139. }
  140. } else {
  141. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_HOST doesn't exist. Using default debugger host: localhost";
  142. host = "localhost";
  143. }
  144. // configure grpc port
  145. const char *env_port_str = std::getenv("MS_DEBUGGER_PORT");
  146. std::string port;
  147. if (env_port_str != nullptr) {
  148. if (CheckPort(env_port_str)) {
  149. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PORT: " << env_port_str;
  150. port = std::string(env_port_str);
  151. } else {
  152. debugger_enabled_ = false;
  153. MS_EXCEPTION(ValueError) << "Environment variable MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to "
  154. "65535";
  155. }
  156. } else {
  157. port = "50051";
  158. if (!CheckPort(port.c_str())) {
  159. MS_EXCEPTION(ValueError) << "Default MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to 65535";
  160. }
  161. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_PORT doesn't exist. Using default debugger port: 50051";
  162. }
  163. // initialize grpc client
  164. grpc_client_ = std::make_unique<GrpcClient>(host, port);
  165. }
  166. debug_services_ = std::make_unique<DebugServices>();
  167. }
  168. void Debugger::SetOpOverflowBinPath(uint32_t graph_id) {
  169. #ifdef ENABLE_D
  170. // set operation overflow info
  171. overflow_bin_path_.insert(std::pair<uint32_t, std::string>(
  172. graph_id, DumpJsonParser::GetInstance().GetOpOverflowBinPath(graph_id, device_id_)));
  173. // new overflow dump files will have a timestamp greater than last_overflow_bin_
  174. auto overflow_bin_path = overflow_bin_path_.find(graph_id)->second;
  175. DIR *d;
  176. d = opendir(overflow_bin_path.c_str());
  177. if (d != nullptr) {
  178. struct dirent *dir;
  179. while ((dir = readdir(d)) != nullptr) {
  180. if (dir->d_type == DT_REG) {
  181. std::string file_path = overflow_bin_path;
  182. file_path.append(dir->d_name);
  183. std::size_t found = file_path.find_last_of(".");
  184. if (found == std::string::npos) {
  185. continue;
  186. }
  187. std::string overflow_time = file_path.substr(found + 1);
  188. if (stod(overflow_time) <= last_overflow_bin_) {
  189. MS_LOG(INFO) << "Old op overflow bin folder" << file_path;
  190. continue;
  191. }
  192. last_overflow_bin_ = stod(overflow_time);
  193. }
  194. }
  195. MS_LOG(INFO) << "last op overflow bin folder" << last_overflow_bin_;
  196. closedir(d);
  197. }
  198. #endif
  199. }
  200. void Debugger::CheckDatasetSinkMode() {
  201. if (CheckDebuggerDumpEnabled() && ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  202. MS_EXCEPTION(NotSupportError)
  203. << "e2e_dump not supported on GPU with dataset_sink_mode=True. Please set dataset_sink_mode=False";
  204. }
  205. if (CheckDebuggerEnabled() && ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  206. MS_EXCEPTION(NotSupportError)
  207. << "Debugger is not supported with dataset_sink_mode=True. Please set dataset_sink_mode=False";
  208. }
  209. }
  210. bool Debugger::CheckDebuggerDumpEnabled() const {
  211. // see if dump is enabled
  212. if (device_target_ == kGPUDevice) {
  213. return device::KernelRuntime::DumpDataEnabled();
  214. }
  215. return false;
  216. }
  217. bool Debugger::CheckDebuggerEnabled() const {
  218. // get env variables to configure debugger
  219. const char *env_enable_char = std::getenv("ENABLE_MS_DEBUGGER");
  220. if (env_enable_char != nullptr) {
  221. std::string env_enable_str = env_enable_char;
  222. (void)std::transform(env_enable_str.begin(), env_enable_str.end(), env_enable_str.begin(), ::tolower);
  223. if ((env_enable_str == "1" || env_enable_str == "true") && device_target_ != kCPUDevice) {
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. void Debugger::CheckDebuggerEnabledParam() const {
  230. // check the value of env variable ENABLE_MS_DEBUGGER
  231. const char *env_enable_char = std::getenv("ENABLE_MS_DEBUGGER");
  232. if (env_enable_char != nullptr) {
  233. std::string env_enable_str = env_enable_char;
  234. (void)std::transform(env_enable_str.begin(), env_enable_str.end(), env_enable_str.begin(), ::tolower);
  235. if (env_enable_str != "0" && env_enable_str != "1" && env_enable_str != "false" && env_enable_str != "true") {
  236. MS_LOG(WARNING) << "Env variable ENABLE_MS_DEBUGGER should be True/False/1/0 (case insensitive), but get: "
  237. << env_enable_str;
  238. }
  239. }
  240. }
  241. bool Debugger::CheckDebuggerPartialMemoryEnabled() const {
  242. const char *env_partial_mem_str = std::getenv("MS_DEBUGGER_PARTIAL_MEM");
  243. if (env_partial_mem_str != nullptr) {
  244. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PARTIAL_MEM: " << env_partial_mem_str;
  245. if (std::strcmp(env_partial_mem_str, "1") == 0) {
  246. return true;
  247. }
  248. }
  249. return false;
  250. }
  251. bool Debugger::DebuggerBackendEnabled() const { return CheckDebuggerDumpEnabled() || CheckDebuggerEnabled(); }
  252. void Debugger::Reset() {
  253. // access lock for public method
  254. std::lock_guard<std::mutex> a_lock(access_lock_);
  255. // reset components
  256. device_id_ = 0;
  257. device_target_ = "";
  258. num_step_ = 0;
  259. debugger_enabled_ = false;
  260. is_dataset_graph_ = false;
  261. partial_memory_ = false;
  262. graph_ptr_ = nullptr;
  263. grpc_client_ = nullptr;
  264. debug_services_ = nullptr;
  265. last_overflow_bin_ = 0;
  266. overflow_bin_path_.clear();
  267. stream_task_to_opname_.clear();
  268. graph_proto_list_.clear();
  269. graph_ptr_list_.clear();
  270. }
  271. void Debugger::PreExecute(const KernelGraphPtr &graph_ptr, uint32_t graph_sum) {
  272. // access lock for public method
  273. std::lock_guard<std::mutex> a_lock(access_lock_);
  274. CheckDatasetSinkMode();
  275. auto graph_id = graph_ptr->graph_id();
  276. // collect rungrap_ids to update step number in multigraph case
  277. if (!rungraph_id_list_.size()) {
  278. rungraph_id_list_.push_back(graph_id);
  279. } else {
  280. if (std::find(rungraph_id_list_.begin(), rungraph_id_list_.end(), graph_id) == rungraph_id_list_.end()) {
  281. rungraph_id_list_.push_back(graph_id);
  282. }
  283. }
  284. // check and save graph_ptr, suspend if graph is new
  285. MS_LOG(INFO) << "total number graph: " << graph_sum;
  286. // multiple graphs
  287. if (graph_sum > 1) {
  288. // there are more than one graphs are not dataset_graph
  289. if (not_dataset_graph_sum_ > 0) {
  290. // only try to enable debugger if they are not all dataset graphs
  291. if (!debugger_enabled_) {
  292. EnableDebugger();
  293. }
  294. if (debugger_enabled_) {
  295. if (graph_proto_list_.size()) {
  296. // only send compiled graphs once.
  297. auto dbg_graph_ptr = graph_ptr_;
  298. // use current graph ptr to load parameters
  299. graph_ptr_ = graph_ptr;
  300. LoadParametersAndConst();
  301. // revert graph ptr to original value
  302. graph_ptr_ = dbg_graph_ptr;
  303. SendMultiGraphsAndSuspend(graph_proto_list_);
  304. graph_proto_list_.clear();
  305. }
  306. }
  307. }
  308. } else if (graph_proto_list_.size() == 1) {
  309. // In single graph case, reset graph_ptr_ to be nullptr for the initial step
  310. if (num_step_ == 0) {
  311. graph_ptr_ = nullptr;
  312. }
  313. CheckGraphPtr(graph_ptr);
  314. }
  315. }
  316. void Debugger::PostExecute(const KernelGraphPtr &graph_ptr) {
  317. // access lock for public method
  318. std::lock_guard<std::mutex> a_lock(access_lock_);
  319. if (pipeline::ExecutorPy::GetDebugTerminate()) {
  320. return;
  321. }
  322. if (debugger_->DebuggerBackendEnabled()) {
  323. // analyze tensor data and send the watchpoints been hit
  324. if (debugger_enabled_ && !is_dataset_graph_) {
  325. if (device_target_ != kGPUDevice) {
  326. num_step_++;
  327. }
  328. SendWatchpoints(CheckWatchpoints());
  329. if (graph_ptr != nullptr && device_target_ == kGPUDevice) {
  330. auto graph_id = graph_ptr->graph_id();
  331. if (graph_id == rungraph_id_list_.front()) {
  332. CommandLoop();
  333. }
  334. } else {
  335. CommandLoop();
  336. }
  337. }
  338. // Only keep parameters in the current map
  339. debug_services_->ResetLoadedTensors();
  340. }
  341. }
  342. bool Debugger::ReadNodeDataRequired(const CNodePtr &kernel) const {
  343. if (debugger_enabled_ && !is_dataset_graph_) {
  344. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  345. // if node has a watchpoint on it, is next_to node, or continue_to node then read the kernel tensor data
  346. if (is_watchpoint || (run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_))) {
  347. return true;
  348. }
  349. }
  350. return false;
  351. }
  352. void Debugger::PostExecuteNode(const CNodePtr &kernel, bool last_kernel) {
  353. // access lock for public method
  354. std::lock_guard<std::mutex> a_lock(access_lock_);
  355. if (pipeline::ExecutorPy::GetDebugTerminate()) {
  356. return;
  357. }
  358. if (debugger_enabled_ && !is_dataset_graph_) {
  359. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  360. // if kernel is watchpoint,and get hit. suspend.
  361. bool hit_empty_flag = true;
  362. if (is_watchpoint) {
  363. auto hits = CheckWatchpoints(cur_name_, kernel);
  364. if (!hits.empty()) {
  365. SendWatchpoints(hits);
  366. CommandLoop();
  367. hit_empty_flag = false;
  368. }
  369. }
  370. if (hit_empty_flag && run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_) && !last_kernel) {
  371. // if kernel is not watchpoint and is next_to or continue_to node, suspend
  372. // No need to suspend if this is the last node in graph since PostExecute suspends at the end of graph
  373. CommandLoop();
  374. }
  375. return;
  376. }
  377. }
  378. void Debugger::PostDebugOp() {
  379. // access lock for public method
  380. std::lock_guard<std::mutex> a_lock(access_lock_);
  381. // suspend if debugger is enabled
  382. if (debugger_enabled_ && !is_dataset_graph_) {
  383. MS_LOG(INFO) << "Debugger suspend at debug_op";
  384. CommandLoop();
  385. }
  386. }
  387. void Debugger::SetStreamTaskToOpnameMap(const std::map<std::pair<uint32_t, uint32_t>, std::string> &mapping) {
  388. stream_task_to_opname_ = mapping;
  389. }
  390. void Debugger::LoadGraphs(const KernelGraphPtr &graph_ptr) {
  391. if (graph_ptr_ != graph_ptr) {
  392. MS_LOG(INFO) << "LoadGraphs Debugger got new graph: " << graph_ptr->graph_id();
  393. // save new graph_ptr
  394. graph_ptr_ = graph_ptr;
  395. CheckDatasetGraph();
  396. if (!is_dataset_graph_) {
  397. // get proto for new graph_ptr
  398. auto graph_proto = GetGraphProto(graph_ptr);
  399. // add new graph proto to graph_proto_list_
  400. graph_proto_list_.push_back(graph_proto);
  401. graph_ptr_list_.push_back(graph_ptr);
  402. #ifdef ENABLE_D
  403. SetOpOverflowBinPath(graph_ptr->graph_id());
  404. #endif
  405. not_dataset_graph_sum_++;
  406. }
  407. // reset is_dataset_graph to be false
  408. is_dataset_graph_ = false;
  409. }
  410. }
  411. // In single graph cases, check single graph ptr
  412. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  413. if (graph_ptr_ != graph_ptr) {
  414. MS_LOG(INFO) << "CheckGraphPtr Debugger got new graph: " << graph_ptr->graph_id();
  415. // save new graph_ptr
  416. graph_ptr_ = graph_ptr;
  417. if (!is_dataset_graph_) {
  418. // only try to enable debugger if it is not a dataset graph
  419. EnableDebugger();
  420. if (debugger_enabled_) {
  421. LoadParametersAndConst();
  422. // get graph proto and send to Mindinsight
  423. auto graph_proto = graph_proto_list_.front();
  424. SendGraphAndSuspend(graph_proto);
  425. }
  426. }
  427. }
  428. }
  429. void Debugger::CheckDatasetGraph() {
  430. // print parameter node names
  431. const auto &params = graph_ptr_->inputs();
  432. for (const auto &param : params) {
  433. MS_LOG(INFO) << "param: " << param->fullname_with_scope();
  434. }
  435. // check if there is GetNext or InitDataSetQueue node
  436. const auto &nodes = graph_ptr_->execution_order();
  437. for (const auto &node : nodes) {
  438. auto node_name = AnfAlgo::GetCNodeName(node);
  439. MS_LOG(INFO) << "node: " << node->fullname_with_scope();
  440. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  441. MS_LOG(INFO) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  442. << node_name;
  443. is_dataset_graph_ = true;
  444. return;
  445. }
  446. }
  447. is_dataset_graph_ = false;
  448. }
  449. GraphProto Debugger::GetGraphProto(const KernelGraphPtr &graph_ptr) const {
  450. // convert kernel graph to debugger modelproto
  451. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr);
  452. return model.graph();
  453. }
  454. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  455. if (SendMetadata(true)) {
  456. // send graph to Mindinsight server
  457. EventReply reply = grpc_client_->SendGraph(graph_proto);
  458. if (reply.status() != reply.OK) {
  459. MS_LOG(ERROR) << "Error: SendGraph failed";
  460. }
  461. // enter command loop, wait and process commands
  462. CommandLoop();
  463. }
  464. }
  465. bool Debugger::SendMetadata(bool version_check) {
  466. // prepare metadata
  467. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  468. Metadata metadata;
  469. metadata.set_device_name(device_name);
  470. metadata.set_cur_step(num_step_);
  471. metadata.set_backend(device_target_);
  472. metadata.set_cur_node(cur_name_);
  473. metadata.set_training_done(training_done_);
  474. metadata.set_ms_version(version_);
  475. MS_LOG(INFO) << "Is training done?" << training_done_;
  476. // set graph munber to not_dataset_graph_sum_
  477. metadata.set_graph_num(not_dataset_graph_sum_);
  478. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  479. bool ret = false;
  480. if (reply_metadata.status() == reply_metadata.OK) {
  481. if (version_check) {
  482. // get type of the command in meta data reply, it should be version matched
  483. DebuggerCommand cmd = GetCommand(reply_metadata);
  484. if (cmd != DebuggerCommand::kVersionMatchedCMD) {
  485. MS_LOG(ERROR) << "MindInsight version is too old, Mindspore version is " << version_;
  486. Exit();
  487. } else {
  488. if (GetMiVersionMatched(reply_metadata)) {
  489. MS_LOG(INFO) << "MindSpore version is " << version_ << " matches MindInsight version.";
  490. ret = true;
  491. } else {
  492. MS_LOG(ERROR) << "MindSpore version " << version_ << ", did not match MindInsight version.";
  493. CommandLoop();
  494. }
  495. }
  496. } else {
  497. // version check is done before so we can just return true here
  498. ret = true;
  499. }
  500. } else {
  501. MS_LOG(ERROR) << "Error: SendMetadata failed";
  502. }
  503. return ret;
  504. }
  505. void Debugger::SendMultiGraphsAndSuspend(const std::list<GraphProto> &graph_proto_list) {
  506. if (!SendMetadata(true)) {
  507. return;
  508. }
  509. // send multiple graphs to mindinght server
  510. // split graph into chunks if one graph is larger than chunk size
  511. std::list<Chunk> chunked_graph_proto_list;
  512. Chunk chunk;
  513. for (auto graph : graph_proto_list) {
  514. std::string str = graph.SerializeAsString();
  515. auto graph_size = graph.ByteSize();
  516. if (graph_size > CHUNK_SIZE) {
  517. auto sub_graph_str = grpc_client_->ChunkString(str, graph_size);
  518. for (unsigned int i = 0; i < sub_graph_str.size(); i++) {
  519. chunk.set_buffer(sub_graph_str[i]);
  520. chunked_graph_proto_list.push_back(chunk);
  521. if (i < sub_graph_str.size() - 1) {
  522. chunk.set_finished(false);
  523. } else {
  524. chunk.set_finished(true);
  525. chunked_graph_proto_list.push_back(chunk);
  526. }
  527. }
  528. } else {
  529. chunk.set_buffer(str);
  530. chunk.set_finished(true);
  531. chunked_graph_proto_list.push_back(chunk);
  532. }
  533. }
  534. EventReply reply = grpc_client_->SendMultiGraphs(chunked_graph_proto_list);
  535. if (reply.status() != reply.OK) {
  536. MS_LOG(ERROR) << "Error: SendGraph failed";
  537. }
  538. // enter command loop, wait and process commands
  539. CommandLoop();
  540. }
  541. void Debugger::CommandLoop() {
  542. // prepare metadata
  543. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  544. Metadata metadata;
  545. metadata.set_device_name(device_name);
  546. metadata.set_cur_step(num_step_);
  547. metadata.set_backend(device_target_);
  548. metadata.set_cur_node(cur_name_);
  549. metadata.set_training_done(training_done_);
  550. // loop exit flag
  551. bool run = false;
  552. int num_wait_fail = 0;
  553. const int max_num_wait_fail = 5;
  554. while (!run) {
  555. // wait for command
  556. EventReply reply = grpc_client_->WaitForCommand(metadata);
  557. if (reply.status() != reply.OK) {
  558. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  559. num_wait_fail++;
  560. if (num_wait_fail > max_num_wait_fail) {
  561. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session.";
  562. MS_LOG(ERROR) << "Failed to connect to MindInsight debugger server. Please check the config "
  563. "of debugger host and port.";
  564. Exit();
  565. run = true;
  566. } else {
  567. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  568. << num_wait_fail << "s";
  569. std::this_thread::sleep_for(std::chrono::milliseconds(1000 * num_wait_fail));
  570. }
  571. continue;
  572. }
  573. // get type of the command in reply
  574. DebuggerCommand cmd = GetCommand(reply);
  575. if (cmd == DebuggerCommand::kUnknownCMD) {
  576. MS_LOG(DEBUG) << "Debug: debugger received unknown command";
  577. continue;
  578. }
  579. MS_LOG(INFO) << "received command: ";
  580. switch (cmd) {
  581. case DebuggerCommand::kUnknownCMD:
  582. MS_LOG(INFO) << "UnknownCMD";
  583. break;
  584. case DebuggerCommand::kExitCMD:
  585. MS_LOG(INFO) << "ExitCMD";
  586. Exit();
  587. // Used for debugger termination
  588. run = true;
  589. break;
  590. case DebuggerCommand::kRunCMD:
  591. ProcessRunCMD(reply);
  592. if (GetRunLevel(reply) != "recheck") {
  593. // exit loop
  594. run = true;
  595. }
  596. break;
  597. case DebuggerCommand::kSetCMD:
  598. ProcessKSetCMD(reply);
  599. break;
  600. case DebuggerCommand::kViewCMD:
  601. ProcessKViewCMD(reply);
  602. break;
  603. case DebuggerCommand::kVersionMatchedCMD:
  604. MS_LOG(ERROR) << "Received unexpected Version Matched CMD from Mindinsight.";
  605. Exit();
  606. break;
  607. default:
  608. MS_LOG(ERROR) << "Received unknown CMD from Mindinsight";
  609. Exit();
  610. break;
  611. }
  612. }
  613. }
  614. void Debugger::ProcessRunCMD(const EventReply &reply) {
  615. MS_LOG(INFO) << "RunCMD";
  616. if (GetRunLevel(reply) == "recheck") {
  617. MS_LOG(INFO) << "rechecking all watchpoints";
  618. SendWatchpoints(CheckWatchpoints("", nullptr, true));
  619. } else {
  620. // no longer the initial suspension.
  621. initial_suspend_ = false;
  622. // print run cmd content
  623. // get run_level and node_name
  624. run_level_ = GetRunLevel(reply);
  625. node_name_ = GetNodeName(reply);
  626. MS_LOG(INFO) << "run_level: " << run_level_;
  627. MS_LOG(INFO) << "node_name_: " << node_name_;
  628. }
  629. }
  630. void Debugger::ProcessKSetCMD(const EventReply &reply) {
  631. MS_LOG(INFO) << "SetCMD";
  632. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  633. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  634. if (GetWatchpointDelete(reply)) {
  635. MS_LOG(INFO) << "Deleting watchpoint";
  636. RemoveWatchpoint(GetWatchpointID(reply));
  637. } else {
  638. MS_LOG(INFO) << "Setting watchpoint";
  639. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  640. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  641. for (const auto &node : recieved_nodes) {
  642. MS_LOG(INFO) << "node name: " << node.node_name();
  643. MS_LOG(INFO) << "node type: " << node.node_type();
  644. }
  645. ProtoVector<WatchCondition_Parameter> parameters = GetParameters(reply);
  646. for (const auto &parameter : parameters) {
  647. MS_LOG(INFO) << "parameter name: " << parameter.name();
  648. MS_LOG(INFO) << "parameter is disabled: " << parameter.disabled();
  649. MS_LOG(INFO) << "parameter value: " << parameter.value();
  650. }
  651. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply), GetParameters(reply));
  652. }
  653. }
  654. void Debugger::ProcessKViewCMD(const EventReply &reply) {
  655. MS_LOG(INFO) << "ViewCMD";
  656. // print view cmd content
  657. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  658. for (auto received_tensor : received_tensors) {
  659. MS_LOG(INFO) << "tensor node name: " << received_tensor.node_name();
  660. MS_LOG(INFO) << "tensor slot: " << received_tensor.slot();
  661. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << received_tensor.finished() << std::noboolalpha;
  662. MS_LOG(INFO) << "tensor iter: " << received_tensor.iter();
  663. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << received_tensor.truncate() << std::noboolalpha;
  664. }
  665. MS_LOG(INFO) << "Sending tensors";
  666. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  667. // print view cmd reply
  668. for (auto tensor : tensors) {
  669. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  670. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  671. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  672. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  673. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  674. MS_LOG(INFO) << "tensor dims: ";
  675. for (auto dim : tensor.dims()) {
  676. MS_LOG(INFO) << dim << ",";
  677. }
  678. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  679. }
  680. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  681. if (send_tensors_reply.status() != send_tensors_reply.OK) {
  682. MS_LOG(ERROR) << "Error: SendTensors failed";
  683. }
  684. }
  685. void AddTensorProtoInfo(TensorProto *tensor_item, const TensorProto &tensor) {
  686. tensor_item->set_node_name(tensor.node_name());
  687. tensor_item->set_slot(tensor.slot());
  688. tensor_item->set_iter(tensor.iter());
  689. tensor_item->set_truncate(tensor.truncate());
  690. tensor_item->clear_tensor_content();
  691. tensor_item->clear_data_type();
  692. tensor_item->clear_dims();
  693. }
  694. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id,
  695. const ProtoVector<WatchCondition_Parameter> &parameters) {
  696. std::vector<std::tuple<std::string, bool>> check_node_list;
  697. std::vector<DebugServices::parameter_t> parameter_list;
  698. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  699. [](const WatchNode &node) -> std::tuple<std::string, bool> {
  700. return make_tuple(node.node_name(), node.node_type() == "scope");
  701. });
  702. std::transform(
  703. parameters.begin(), parameters.end(), std::back_inserter(parameter_list),
  704. [](const WatchCondition_Parameter &parameter) -> DebugServices::parameter_t {
  705. return DebugServices::parameter_t{parameter.name(), parameter.disabled(), parameter.value(), parameter.hit()};
  706. });
  707. debug_services_->AddWatchpoint(id, condition.condition(), condition.value(), check_node_list, parameter_list);
  708. }
  709. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  710. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  711. std::vector<std::string> name;
  712. std::vector<std::string> ret_name;
  713. std::vector<char *> data_ptr;
  714. std::vector<ssize_t> data_size;
  715. std::vector<unsigned int> dtype;
  716. std::vector<std::vector<int64_t>> shape;
  717. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  718. // ret_name will contain tensor names that are found in TensorLoader
  719. // items in ret_name will be in the same order with tensors if found
  720. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  721. std::list<TensorProto> tensor_list;
  722. unsigned int result_index = 0;
  723. for (auto tensor : tensors) {
  724. ssize_t size_iter = 0;
  725. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  726. TensorProto tensor_item;
  727. tensor_item.set_finished(true);
  728. AddTensorProtoInfo(&tensor_item, tensor);
  729. tensor_list.push_back(tensor_item);
  730. continue;
  731. }
  732. ssize_t tensor_size = data_size[result_index];
  733. while (size_iter < tensor_size) {
  734. ssize_t chunk_size = CHUNK_SIZE;
  735. TensorProto tensor_item;
  736. tensor_item.set_finished(false);
  737. if (tensor_size - size_iter <= CHUNK_SIZE) {
  738. chunk_size = tensor_size - size_iter;
  739. tensor_item.set_finished(true);
  740. }
  741. AddTensorProtoInfo(&tensor_item, tensor);
  742. // return empty tensor if didn't find the requested tensor
  743. tensor_item.set_tensor_content(data_ptr[result_index] + size_iter, chunk_size);
  744. tensor_item.set_data_type((debugger::DataType)dtype[result_index]);
  745. for (auto &elem : shape[result_index]) {
  746. tensor_item.add_dims(elem);
  747. }
  748. // add tensor to result list and increment result_index to check next item in ret_name
  749. tensor_list.push_back(tensor_item);
  750. size_iter += CHUNK_SIZE;
  751. }
  752. result_index++;
  753. }
  754. return tensor_list;
  755. }
  756. void Debugger::Exit() {
  757. // clear resource before exit
  758. // debugger will notify main thread to exit because main thread can only exit at step boundary
  759. pipeline::ExecutorPy::DebugTerminate(true);
  760. }
  761. std::list<WatchpointHit> Debugger::CheckWatchpoints(const std::string &watchnode, const CNodePtr &kernel,
  762. bool recheck) {
  763. std::vector<std::string> name;
  764. std::vector<std::string> slot;
  765. std::vector<int> condition;
  766. std::vector<unsigned int> watchpoint_id;
  767. std::vector<std::string> overflow_ops;
  768. std::vector<std::vector<DebugServices::parameter_t>> parameters;
  769. std::vector<int32_t> error_codes;
  770. #ifdef ENABLE_D
  771. overflow_ops = CheckOpOverflow();
  772. #endif
  773. std::vector<std::shared_ptr<TensorData>> tensor_list;
  774. if (watchnode.empty()) {
  775. tensor_list = debug_services_->GetTensor();
  776. } else {
  777. tensor_list = debug_services_->GetNodeTensor(kernel);
  778. }
  779. std::vector<std::string> file_list;
  780. debug_services_->CheckWatchpoints(&name, &slot, &condition, &watchpoint_id, &parameters, &error_codes, overflow_ops,
  781. file_list, &tensor_list, initial_suspend_, watchnode.empty(), recheck);
  782. std::list<WatchpointHit> hits;
  783. for (unsigned int i = 0; i < name.size(); i++) {
  784. WatchpointHit hit;
  785. std::vector<DebugServices::parameter_t> &parameter = parameters[i];
  786. hit.set_id(watchpoint_id[i]);
  787. hit.set_error_code(error_codes[i]);
  788. // here TensorProto act as a tensor indicator, not sending tensor content
  789. TensorProto *tensor_item = hit.mutable_tensor();
  790. tensor_item->set_node_name(name[i]);
  791. tensor_item->set_slot(slot[i]);
  792. tensor_item->set_finished(true);
  793. WatchCondition *condition_item = hit.mutable_watch_condition();
  794. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  795. for (const auto &p : parameter) {
  796. auto x = condition_item->mutable_params()->Add();
  797. x->set_name(p.name);
  798. x->set_disabled(p.disabled);
  799. x->set_value(p.value);
  800. x->set_hit(p.hit);
  801. x->set_actual_value(p.actual_value);
  802. }
  803. hits.push_back(hit);
  804. }
  805. return hits;
  806. }
  807. void Debugger::SendWatchpoints(const std::list<WatchpointHit> &points) {
  808. // send info about watchpoint
  809. if (!points.empty()) {
  810. EventReply reply = grpc_client_->SendWatchpointHits(points);
  811. if (reply.status() != reply.OK) {
  812. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  813. }
  814. }
  815. }
  816. bool Debugger::DumpTensorToFile(const std::string &tensor_name, bool trans_flag, const std::string &filepath,
  817. const std::string &host_fmt, const std::vector<int64_t> &host_shape, TypeId host_type,
  818. TypeId device_type, const std::string &addr_format, size_t slot) const {
  819. return debug_services_.get()->DumpTensorToFile(tensor_name, trans_flag, filepath, host_fmt, host_shape, host_type,
  820. device_type, addr_format, slot);
  821. }
  822. bool Debugger::DebugServicesIsWatchPoint(const std::string &kernel_name, const CNodePtr &kernel) const {
  823. return debug_services_.get()->IsWatchPoint(kernel_name, kernel);
  824. }
  825. void Debugger::EmptyTensor() { debug_services_.get()->EmptyTensor(); }
  826. void Debugger::SetTensorLoaderIterNum(uint32_t iter_num) { debug_services_.get()->SetTensorLoaderIterNum(iter_num); }
  827. void Debugger::EmptyPrevTensor() { debug_services_.get()->EmptyPrevTensor(); }
  828. uint32_t Debugger::GetTensorLoaderIterNum() const { return debug_services_.get()->GetTensorLoaderIterNum(); }
  829. bool Debugger::LoadNewTensor(const std::shared_ptr<TensorData> &tensor, bool keep_prev) {
  830. return debug_services_.get()->LoadNewTensor(tensor, keep_prev);
  831. }
  832. bool Debugger::debugger_enabled() const { return debugger_enabled_; }
  833. DebuggerCommand GetCommand(const EventReply &reply) {
  834. DebuggerCommand cmd = DebuggerCommand::kUnknownCMD;
  835. switch (reply.cmd_case()) {
  836. case debugger::EventReply::CmdCase::kExit:
  837. cmd = DebuggerCommand::kExitCMD;
  838. break;
  839. case debugger::EventReply::CmdCase::kRunCmd:
  840. cmd = DebuggerCommand::kRunCMD;
  841. break;
  842. case debugger::EventReply::CmdCase::kSetCmd:
  843. cmd = DebuggerCommand::kSetCMD;
  844. break;
  845. case debugger::EventReply::CmdCase::kViewCmd:
  846. cmd = DebuggerCommand::kViewCMD;
  847. break;
  848. case debugger::EventReply::CmdCase::kVersionMatched:
  849. cmd = DebuggerCommand::kVersionMatchedCMD;
  850. break;
  851. default:
  852. MS_LOG(DEBUG) << "Debug: UnknownCMD";
  853. break;
  854. }
  855. return cmd;
  856. }
  857. ProtoVector<WatchCondition_Parameter> GetParameters(const EventReply &reply) {
  858. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  859. MS_LOG(ERROR) << "Error: Can not get Parameters from command. Returning default value: ProtoVector<Parameter>().";
  860. return ProtoVector<WatchCondition_Parameter>();
  861. }
  862. return reply.set_cmd().watch_condition().params();
  863. }
  864. ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply) {
  865. if (!reply.has_set_cmd()) {
  866. MS_LOG(ERROR) << "Error: Not SetCMD, can not get WatchNodes. Returning default value: ProtoVector<WatchNode>().";
  867. return ProtoVector<WatchNode>();
  868. }
  869. return reply.set_cmd().watch_nodes();
  870. }
  871. std::string GetRunLevel(const EventReply &reply) {
  872. if (!reply.has_run_cmd()) {
  873. MS_LOG(ERROR) << "Error: Not RunCMD, can not get RunLevel. Returning default value: "
  874. "";
  875. return "";
  876. }
  877. return reply.run_cmd().run_level();
  878. }
  879. std::string GetNodeName(const EventReply &reply) {
  880. if (!reply.has_run_cmd()) {
  881. MS_LOG(ERROR) << "Error: Not RunCMD, can not get NodeName. Returning default value: "
  882. "";
  883. return "";
  884. }
  885. return reply.run_cmd().node_name();
  886. }
  887. WatchCondition GetWatchcondition(const EventReply &reply) {
  888. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  889. MS_LOG(ERROR) << "Error: Can not get WatchCondition from command. Returning default value: WatchCondition().";
  890. return WatchCondition();
  891. }
  892. return reply.set_cmd().watch_condition();
  893. }
  894. int32_t GetWatchpointID(const EventReply &reply) {
  895. if (!reply.has_set_cmd()) {
  896. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint ID. Returning default value: 0.";
  897. return 0;
  898. }
  899. return reply.set_cmd().id();
  900. }
  901. bool GetWatchpointDelete(const EventReply &reply) {
  902. if (!reply.has_set_cmd()) {
  903. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint delete flag. Returning default value: false.";
  904. return false;
  905. }
  906. return reply.set_cmd().delete_();
  907. }
  908. ProtoVector<TensorProto> GetTensors(const EventReply &reply) {
  909. if (!reply.has_view_cmd()) {
  910. MS_LOG(ERROR) << "Error: Not ViewCMD, can not get Tensors. Returning default value: ProtoVector<TensorProto>().";
  911. return ProtoVector<TensorProto>();
  912. }
  913. return reply.view_cmd().tensors();
  914. }
  915. std::string GetTensorFullName(const TensorProto &tensor) {
  916. string node_name = tensor.node_name();
  917. if (tensor.truncate()) {
  918. // scopes in node name are separated by '/'
  919. // use the name without scope if truncate is true
  920. std::size_t found = node_name.find_last_of("/");
  921. node_name = node_name.substr(found + 1);
  922. }
  923. return node_name + ":" + tensor.slot() + (tensor.iter() == "" ? "" : ":" + tensor.iter());
  924. }
  925. bool GetMiVersionMatched(const EventReply &reply) { return reply.version_matched(); }
  926. bool Debugger::partial_memory() const { return partial_memory_; }
  927. void Debugger::SetCurNode(const std::string &cur_name) {
  928. // access lock for public method
  929. std::lock_guard<std::mutex> a_lock(access_lock_);
  930. cur_name_ = cur_name;
  931. }
  932. std::string Debugger::run_level() const { return run_level_; }
  933. void Debugger::SetStepNum(int32_t cur_num_step) {
  934. // access lock for public method
  935. std::lock_guard<std::mutex> a_lock(access_lock_);
  936. num_step_ = cur_num_step;
  937. }
  938. int32_t Debugger::step_num() const { return num_step_; }
  939. uint64_t BytestoInt64(const std::vector<char> &buffer) {
  940. uint64_t ret;
  941. ret = ((uint64_t)buffer[7] << 56) | ((uint64_t)buffer[6] << 48) | ((uint64_t)buffer[5] << 40) |
  942. ((uint64_t)buffer[4] << 32) | ((uint64_t)buffer[3] << 24) | ((uint64_t)buffer[2] << 16) |
  943. ((uint64_t)buffer[1] << 8) | ((uint64_t)buffer[0]);
  944. return ret;
  945. }
  946. #define BUF_SIZ 256
  947. std::vector<std::string> Debugger::CheckOpOverflow() {
  948. std::vector<double> bin_list;
  949. std::vector<std::string> op_names;
  950. for (const auto &[graph_id, overflow_bin_path] : overflow_bin_path_) {
  951. DIR *d;
  952. d = opendir(overflow_bin_path.c_str());
  953. MS_LOG(INFO) << "processing bin file path " << overflow_bin_path << ", graph id " << graph_id;
  954. if (d != nullptr) {
  955. struct dirent *dir = nullptr;
  956. while ((dir = readdir(d)) != nullptr) {
  957. if (dir->d_type == DT_REG) {
  958. std::string file_path = overflow_bin_path;
  959. file_path.append(dir->d_name);
  960. std::string file_name = dir->d_name;
  961. std::size_t found = file_name.find_last_of(".");
  962. if (found == std::string::npos) {
  963. continue;
  964. }
  965. std::string overflow_time = file_name.substr(found + 1);
  966. if (stod(overflow_time) <= last_overflow_bin_) {
  967. MS_LOG(INFO) << "File already processed " << file_name;
  968. continue;
  969. }
  970. bin_list.push_back(stod(overflow_time));
  971. std::fstream infile;
  972. infile.open(file_path.c_str(), std::ios::binary | std::ios::in);
  973. if (!infile.is_open()) {
  974. MS_LOG(ERROR) << "Failed to open overflow bin file " << file_name;
  975. continue;
  976. }
  977. infile.seekg(313, std::ios::beg);
  978. std::vector<char> buffer;
  979. buffer.resize(BUF_SIZ);
  980. infile.read(buffer.data(), BUF_SIZ);
  981. uint64_t stream_id = BytestoInt64(std::vector<char>(buffer.begin() + 8, buffer.end()));
  982. uint64_t task_id = BytestoInt64(std::vector<char>(buffer.begin() + 16, buffer.end()));
  983. MS_LOG(INFO) << "Overflow stream_id " << stream_id << ", task_id " << task_id << ".";
  984. auto op = debugger_->stream_task_to_opname_.find(std::make_pair(stream_id, task_id));
  985. if (op != debugger_->stream_task_to_opname_.end()) {
  986. MS_LOG(ERROR) << "Overflow detected on node " << op->second << std::endl;
  987. op_names.push_back(op->second);
  988. } else {
  989. MS_LOG(INFO) << "No overflow is detected " << std::endl;
  990. }
  991. infile.close();
  992. }
  993. }
  994. } else {
  995. MS_LOG(INFO) << "OverFlow bin directory does not exist!";
  996. }
  997. closedir(d);
  998. }
  999. if (!op_names.empty()) {
  1000. MS_LOG(ERROR) << "These operation overflows are detected " << op_names;
  1001. }
  1002. for (auto &i : bin_list) {
  1003. if (i > last_overflow_bin_) {
  1004. last_overflow_bin_ = i;
  1005. }
  1006. }
  1007. auto iter_op_names = overflow_ops_.find(num_step_);
  1008. if (iter_op_names == overflow_ops_.end()) {
  1009. overflow_ops_.insert(std::pair<uint32_t, std::vector<std::string>>(num_step_, op_names));
  1010. return op_names;
  1011. }
  1012. iter_op_names->second.insert(std::end(iter_op_names->second), std::begin(op_names), std::end(op_names));
  1013. return iter_op_names->second;
  1014. }
  1015. void Debugger::SetTrainingDone(bool training_done) { training_done_ = training_done; }
  1016. bool Debugger::CheckPort(const char *port) const {
  1017. int num = 0;
  1018. const int min_port_num = 1;
  1019. const int max_port_num = 65535;
  1020. if (*port == '0' && *(port + 1) != '\0') return false;
  1021. int i = 0;
  1022. while (*(port + i) != '\0') {
  1023. if (*(port + i) < '0' || *(port + i) > '9') return false;
  1024. num = num * 10 + (*(port + i)) - '0';
  1025. if (num > max_port_num) return false;
  1026. i++;
  1027. }
  1028. if (num < min_port_num) return false;
  1029. return true;
  1030. }
  1031. bool Debugger::CheckIp(const char *host) const {
  1032. std::regex reg_ip(
  1033. "(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"
  1034. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  1035. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  1036. "[.](25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])");
  1037. std::smatch smat;
  1038. std::string host_str = std::string(host);
  1039. return std::regex_match(host_str, smat, reg_ip);
  1040. }
  1041. uint32_t Debugger::GetFirstRunGraphId() const { return rungraph_id_list_.front(); }
  1042. void Debugger::LoadSingleAnfnode(const AnfNodePtr &anf_node, const size_t output_index) {
  1043. MS_EXCEPTION_IF_NULL(anf_node);
  1044. if (!anf_node->isa<Parameter>() && !anf_node->isa<ValueNode>()) {
  1045. return;
  1046. }
  1047. // for parameters and value nodes, set its execution order to be 0;
  1048. int exec_order = 0;
  1049. std::string node_name = anf_node->fullname_with_scope();
  1050. GetFileKernelName(NOT_NULL(&node_name));
  1051. // check if output adde exists, if not, return;
  1052. if (!AnfAlgo::OutputAddrExist(anf_node, output_index)) {
  1053. return;
  1054. }
  1055. auto addr = AnfAlgo::GetOutputAddr(anf_node, output_index);
  1056. MS_EXCEPTION_IF_NULL(addr);
  1057. auto type = AnfAlgo::GetOutputInferDataType(anf_node, output_index);
  1058. if (!IsTypeDebuggerSupported(type)) {
  1059. return;
  1060. }
  1061. auto format = kOpFormat_DEFAULT;
  1062. string tensor_name = node_name + ':' + "0";
  1063. ShapeVector int_shapes = trans::GetRuntimePaddingShape(anf_node, output_index);
  1064. bool keep_prev;
  1065. if (anf_node->isa<Parameter>()) {
  1066. keep_prev = true;
  1067. debug_services_->MoveTensorCurrentToPrev(tensor_name);
  1068. } else {
  1069. keep_prev = false;
  1070. }
  1071. bool ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, 0, keep_prev);
  1072. if (!ret) {
  1073. MS_LOG(ERROR) << "LoadMemToHost:"
  1074. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1075. }
  1076. }
  1077. void Debugger::LoadParametersAndConst() {
  1078. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  1079. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1080. // load parameters
  1081. MS_LOG(INFO) << "Start to load Parameters!";
  1082. const auto &parameters = graph_ptr_->inputs();
  1083. for (auto &item : parameters) {
  1084. LoadSingleAnfnode(item, PARAMETER_OUTPUT_INDEX);
  1085. }
  1086. // load value nodes
  1087. // get all constant avlues from the graph
  1088. MS_LOG(INFO) << "Start to load value nodes!";
  1089. const auto value_nodes = graph_ptr_->graph_value_nodes();
  1090. for (auto &item : value_nodes) {
  1091. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX);
  1092. }
  1093. }
  1094. void Debugger::LoadGraphOutputs() {
  1095. if (!(debugger_enabled() && device_target_ == kAscendDevice)) return;
  1096. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1097. const auto &apply_kernels = graph_ptr_->execution_order();
  1098. // for kernels, execution order starts from 1
  1099. int exec_order = 1;
  1100. for (const auto &node : apply_kernels) {
  1101. MS_EXCEPTION_IF_NULL(node);
  1102. std::string kernel_name = node->fullname_with_scope();
  1103. auto output_size = AnfAlgo::GetOutputTensorNum(node);
  1104. if (partial_memory_) {
  1105. if (!debug_services_->IsWatchPoint(kernel_name, node)) {
  1106. continue;
  1107. }
  1108. }
  1109. for (size_t j = 0; j < output_size; ++j) {
  1110. if (!AnfAlgo::OutputAddrExist(node, j)) {
  1111. MS_LOG(INFO) << "Cannot find output addr for slot " << j << " for " << node->fullname_with_scope();
  1112. continue;
  1113. }
  1114. auto addr = AnfAlgo::GetOutputAddr(node, j);
  1115. MS_EXCEPTION_IF_NULL(addr);
  1116. auto type = AnfAlgo::GetOutputInferDataType(node, j);
  1117. if (!IsTypeDebuggerSupported(type)) {
  1118. continue;
  1119. }
  1120. auto format = kOpFormat_DEFAULT;
  1121. string tensor_name = kernel_name + ':' + std::to_string(j);
  1122. ShapeVector int_shapes = trans::GetRuntimePaddingShape(node, j);
  1123. auto ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, j, false);
  1124. if (!ret) {
  1125. MS_LOG(ERROR) << "LoadMemToHost:"
  1126. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1127. }
  1128. }
  1129. exec_order = exec_order + 1;
  1130. }
  1131. }
  1132. void Debugger::UpdateStepNum(const session::KernelGraph *graph) {
  1133. // update step number if we are processing the first graph (to support multigraph)
  1134. if (device_target_ == kGPUDevice && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration()) &&
  1135. (graph->graph_id() == debugger_->GetFirstRunGraphId())) {
  1136. // access lock for public method
  1137. std::lock_guard<std::mutex> a_lock(access_lock_);
  1138. ++num_step_;
  1139. }
  1140. }
  1141. void Debugger::ClearCurrentData() {
  1142. if (device_target_ == kGPUDevice && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration()))
  1143. debug_services_->EmptyCurrentTensor();
  1144. }
  1145. bool Debugger::TensorExistsInCurrent(const std::string &tensor_name) {
  1146. return debug_services_->TensorExistsInCurrent(tensor_name);
  1147. }
  1148. } // namespace mindspore