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

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