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 58 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
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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. #include "utils/comm_manager.h"
  37. #include "runtime/hardware/device_context_manager.h"
  38. #include "debug/anf_ir_dump.h"
  39. #include "debug/anf_ir_utils.h"
  40. #ifdef ENABLE_DEBUGGER
  41. #include "debug/debugger/proto_exporter.h"
  42. #else
  43. #include "debug/debugger/proto_exporter_stub.h"
  44. #endif
  45. using debugger::Chunk;
  46. using debugger::EventReply;
  47. using debugger::GraphProto;
  48. using debugger::ModelProto;
  49. using debugger::Statistics;
  50. using debugger::TensorProto;
  51. using debugger::WatchCondition;
  52. using debugger::WatchCondition_Condition_inf;
  53. using debugger::WatchCondition_Condition_nan;
  54. using debugger::WatchCondition_Parameter;
  55. using debugger::WatchNode;
  56. using debugger::WatchpointHit;
  57. namespace mindspore {
  58. static constexpr auto g_chunk_size = 1024 * 1024 * 3;
  59. static constexpr int32_t heartbeat_period_second = 30;
  60. DebuggerPtr Debugger::debugger_ = nullptr;
  61. std::mutex Debugger::instance_lock_;
  62. Debugger::Debugger()
  63. : grpc_client_(nullptr),
  64. debug_services_(nullptr),
  65. heartbeat_thread_(nullptr),
  66. device_id_(0),
  67. device_target_(""),
  68. num_step_(0),
  69. debugger_enabled_(false),
  70. suspended_at_last_kernel_(false),
  71. run_level_(""),
  72. node_name_(""),
  73. cur_name_(""),
  74. training_done_(false),
  75. send_metadata_done_(false),
  76. received_new_graph_(false),
  77. is_dataset_graph_(false),
  78. partial_memory_(false),
  79. initial_suspend_(true),
  80. enable_heartbeat_(false),
  81. not_dataset_graph_sum_(0),
  82. version_("") {
  83. CheckDebuggerEnabledParam();
  84. auto ms_context = MsContext::GetInstance();
  85. MS_EXCEPTION_IF_NULL(ms_context);
  86. std::string device_target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  87. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  88. if (device_target == kCPUDevice) {
  89. MS_LOG(WARNING) << "Not enabling debugger. Debugger does not support CPU.";
  90. } else if (CheckDebuggerEnabled()) {
  91. // configure partial memory reuse
  92. partial_memory_ = CheckDebuggerPartialMemoryEnabled();
  93. // switch memory reuse on or off
  94. EnvConfigParser::GetInstance().SetSysMemreuse(partial_memory_);
  95. // print some message about memory reuse to user
  96. if (partial_memory_) {
  97. MS_LOG(WARNING)
  98. << "Partial Memory Reuse is enabled. Note: 1. Please only set watchpoints before running the first "
  99. "step. 2. Tensor values are only available for nodes that are watched by any watchpoint.";
  100. } else {
  101. MS_LOG(WARNING)
  102. << "Memory Reuse is disabled. Set environment variable MS_DEBUGGER_PARTIAL_MEM=1 to reduce memory "
  103. "usage for large models.";
  104. }
  105. }
  106. }
  107. void Debugger::Init(const uint32_t device_id, const std::string device_target) {
  108. // access lock for public method
  109. std::lock_guard<std::mutex> a_lock(access_lock_);
  110. // save device_id
  111. MS_LOG(INFO) << "Debugger got device_id: " << device_id;
  112. device_id_ = device_id;
  113. MS_LOG(INFO) << "Debugger got device_target: " << device_target;
  114. device_target_ = device_target;
  115. version_ = MSVERSION;
  116. }
  117. bool IsTypeDebuggerSupported(TypeId type) {
  118. if (type < TypeId::kNumberTypeEnd && type > TypeId::kNumberTypeBegin && type != kNumberTypeComplex64) {
  119. return true;
  120. }
  121. MS_LOG(INFO) << "Debugger does not support type: " << TypeIdLabel(type);
  122. return false;
  123. }
  124. void Debugger::EnableDebugger() {
  125. // reset some of the class members
  126. num_step_ = 0;
  127. debugger_enabled_ = false;
  128. enable_heartbeat_ = false;
  129. partial_memory_ = false;
  130. grpc_client_ = nullptr;
  131. debug_services_ = nullptr;
  132. heartbeat_thread_ = nullptr;
  133. // see if dump using debugger backend is enabled
  134. bool dump_enabled = CheckDebuggerDumpEnabled();
  135. MS_LOG(INFO) << "dump using debugger backend = " << dump_enabled;
  136. // check if debugger enabled
  137. debugger_enabled_ = CheckDebuggerEnabled();
  138. MS_LOG(INFO) << "debugger_enabled_ = " << debugger_enabled_;
  139. if (!debugger_enabled_ && !dump_enabled) {
  140. MS_LOG(INFO) << "Not enabling debugger. Set environment variable ENABLE_MS_DEBUGGER=1 to enable debugger.";
  141. return;
  142. }
  143. if (debugger_enabled_) {
  144. // configure grpc host
  145. std::string env_host_str = common::GetEnv("MS_DEBUGGER_HOST");
  146. std::string host;
  147. if (!env_host_str.empty()) {
  148. if (CheckIp(env_host_str)) {
  149. MS_LOG(INFO) << "Getenv MS_DEBUGGER_HOST: " << env_host_str;
  150. host = env_host_str;
  151. } else {
  152. debugger_enabled_ = false;
  153. MS_EXCEPTION(ValueError) << "Environment variable MS_DEBUGGER_HOST isn't a valid IP address. "
  154. "Please set environment variable MS_DEBUGGER_HOST=x.x.x.x to a valid IP";
  155. }
  156. } else {
  157. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_HOST doesn't exist. Using default debugger host: localhost";
  158. host = "localhost";
  159. }
  160. // configure grpc port
  161. std::string env_port_str = common::GetEnv("MS_DEBUGGER_PORT");
  162. std::string port;
  163. if (!env_port_str.empty()) {
  164. if (CheckPort(env_port_str)) {
  165. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PORT: " << env_port_str;
  166. port = env_port_str;
  167. } else {
  168. debugger_enabled_ = false;
  169. MS_EXCEPTION(ValueError) << "Environment variable MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to "
  170. "65535";
  171. }
  172. } else {
  173. port = "50051";
  174. if (!CheckPort(port)) {
  175. MS_EXCEPTION(ValueError) << "Default MS_DEBUGGER_PORT is not valid. Custom port ranging from 1 to 65535";
  176. }
  177. MS_LOG(INFO) << "Environment variable MS_DEBUGGER_PORT doesn't exist. Using default debugger port: 50051";
  178. }
  179. // initialize grpc client
  180. grpc_client_ = std::make_unique<GrpcClient>(host, port);
  181. // initialize sending heartbeat
  182. heartbeat_thread_ = std::make_unique<std::thread>([this]() { SendHeartbeat(heartbeat_period_second); });
  183. }
  184. debug_services_ = std::make_unique<DebugServices>();
  185. }
  186. void Debugger::CheckDatasetSinkMode(const KernelGraphPtr &graph_ptr) {
  187. bool sink_mode = ConfigManager::GetInstance().dataset_mode() || graph_ptr->IsDatasetGraph();
  188. if (CheckDebuggerDumpEnabled() && sink_mode) {
  189. MS_EXCEPTION(NotSupportError)
  190. << "e2e_dump is not supported on GPU with dataset_sink_mode=True. Please set dataset_sink_mode=False";
  191. }
  192. if (CheckDebuggerEnabled() && sink_mode) {
  193. MS_EXCEPTION(NotSupportError)
  194. << "Debugger is not supported with dataset_sink_mode=True. Please set dataset_sink_mode=False";
  195. }
  196. }
  197. bool Debugger::CheckDebuggerDumpEnabled() const {
  198. // see if dump is enabled
  199. if (device_target_ == kGPUDevice) {
  200. return device::KernelRuntime::DumpDataEnabled();
  201. }
  202. return false;
  203. }
  204. bool Debugger::CheckDebuggerEnabled() const {
  205. // get env variables to configure debugger
  206. std::string env_enable_str = common::GetEnv("ENABLE_MS_DEBUGGER");
  207. if (!env_enable_str.empty()) {
  208. (void)std::transform(env_enable_str.begin(), env_enable_str.end(), env_enable_str.begin(), ::tolower);
  209. if ((env_enable_str == "1" || env_enable_str == "true") && device_target_ != kCPUDevice) {
  210. return true;
  211. }
  212. }
  213. return false;
  214. }
  215. void Debugger::CheckDebuggerEnabledParam() const {
  216. // check the value of env variable ENABLE_MS_DEBUGGER
  217. std::string env_enable_str = common::GetEnv("ENABLE_MS_DEBUGGER");
  218. if (!env_enable_str.empty()) {
  219. (void)std::transform(env_enable_str.begin(), env_enable_str.end(), env_enable_str.begin(), ::tolower);
  220. if (env_enable_str != "0" && env_enable_str != "1" && env_enable_str != "false" && env_enable_str != "true") {
  221. MS_LOG(WARNING) << "Env variable ENABLE_MS_DEBUGGER should be True/False/1/0 (case insensitive), but get: "
  222. << env_enable_str;
  223. }
  224. }
  225. }
  226. bool Debugger::CheckDebuggerPartialMemoryEnabled() const {
  227. std::string env_partial_mem_str = common::GetEnv("MS_DEBUGGER_PARTIAL_MEM");
  228. if (!env_partial_mem_str.empty()) {
  229. MS_LOG(INFO) << "Getenv MS_DEBUGGER_PARTIAL_MEM: " << env_partial_mem_str;
  230. if (env_partial_mem_str == "1") {
  231. return true;
  232. }
  233. }
  234. return false;
  235. }
  236. bool Debugger::DebuggerBackendEnabled() const { return CheckDebuggerDumpEnabled() || CheckDebuggerEnabled(); }
  237. void Debugger::Reset() {
  238. // access lock for public method
  239. std::lock_guard<std::mutex> a_lock(access_lock_);
  240. // reset components
  241. if (heartbeat_thread_ && heartbeat_thread_->joinable()) {
  242. SetEnableHeartbeat(false);
  243. heartbeat_thread_->join();
  244. MS_LOG(INFO) << "Join Heartbeat thread.";
  245. }
  246. heartbeat_thread_ = nullptr;
  247. device_id_ = 0;
  248. device_target_ = "";
  249. num_step_ = 0;
  250. debugger_enabled_ = false;
  251. is_dataset_graph_ = false;
  252. partial_memory_ = false;
  253. graph_ptr_ = nullptr;
  254. grpc_client_ = nullptr;
  255. debug_services_ = nullptr;
  256. graph_proto_list_.clear();
  257. graph_ptr_list_.clear();
  258. graph_ptr_step_vec_.clear();
  259. MS_LOG(INFO) << "Release Debugger resource.";
  260. }
  261. void Debugger::PreExecuteGraphDebugger(const std::vector<KernelGraphPtr> &graphs) {
  262. // Only GPU is supported for MindRTBackend
  263. if (device_target_ != kGPUDevice) {
  264. return;
  265. }
  266. // Store graphs that are run in one step.
  267. graph_ptr_step_vec_ = graphs;
  268. prev_root_graph_id_ = cur_root_graph_id_;
  269. // set first run graph as the root graph
  270. cur_root_graph_id_ = graph_ptr_step_vec_[0]->graph_id();
  271. MS_LOG(DEBUG) << "Current root graph id: " << cur_root_graph_id_ << " prev_root_graph_id_: " << prev_root_graph_id_
  272. << " for step: " << num_step_ << ".";
  273. MS_LOG(DEBUG) << "Set root graph for all the subgraphs:";
  274. for (size_t graph_index = 0; graph_index < graphs.size(); ++graph_index) {
  275. const auto &graph = graphs[graph_index];
  276. // set root graph id for GPU mindrt runtime.
  277. MS_LOG(DEBUG) << "Set root graph for graph: " << graph->graph_id() << " to: " << cur_root_graph_id_ << ".";
  278. graph->set_root_graph_id(cur_root_graph_id_);
  279. if (debugger_) {
  280. debugger_->PreExecute(graph);
  281. }
  282. }
  283. }
  284. void Debugger::SetCurrentAndPrevRootGraph(uint32_t root_graph_id) {
  285. // for GPU root graphs are set in PreExecuteGraphDebugger.
  286. if (device_target_ != kAscendDevice) {
  287. return;
  288. }
  289. prev_root_graph_id_ = cur_root_graph_id_;
  290. cur_root_graph_id_ = root_graph_id;
  291. MS_LOG(DEBUG) << "Current root graph id: " << cur_root_graph_id_ << " prev_root_graph_id_: " << prev_root_graph_id_
  292. << " for step: " << num_step_ << ".";
  293. }
  294. void Debugger::StoreRunGraphIdList(uint32_t graph_id) {
  295. // collect rungrap_ids to update step number in multigraph case
  296. if (!rungraph_id_list_.size()) {
  297. rungraph_id_list_.push_back(graph_id);
  298. } else {
  299. if (std::find(rungraph_id_list_.begin(), rungraph_id_list_.end(), graph_id) == rungraph_id_list_.end()) {
  300. rungraph_id_list_.push_back(graph_id);
  301. }
  302. }
  303. }
  304. void Debugger::PreExecute(const KernelGraphPtr &graph_ptr) {
  305. MS_EXCEPTION_IF_NULL(graph_ptr);
  306. // access lock for public method
  307. std::lock_guard<std::mutex> a_lock(access_lock_);
  308. if (!MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_MINDRT)) {
  309. // Checking dataset_sink_mode for mindRT is done in debug_actor
  310. CheckDatasetSinkMode(graph_ptr);
  311. }
  312. auto graph_id = graph_ptr->graph_id();
  313. MS_LOG(DEBUG) << "PreExecute for graph: " << graph_id << " in step: " << num_step_ << ".";
  314. StoreRunGraphIdList(graph_id);
  315. SetCurrentAndPrevRootGraph(graph_ptr->root_graph_id());
  316. // multiple graphs
  317. if (graph_proto_list_.size() > 1) {
  318. // there are more than one graphs are not dataset_graph
  319. if (not_dataset_graph_sum_ > 0) {
  320. SendMultiGraphsAndClear(graph_ptr);
  321. }
  322. } else if (graph_proto_list_.size() == 1) {
  323. // single graph, and not the initial step
  324. if (device_target_ == kGPUDevice && !MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_MINDRT) &&
  325. num_step_ != 0) {
  326. if (debugger_enabled_ && !(run_level_ == "node" && suspended_at_last_kernel_)) {
  327. CommandLoop();
  328. }
  329. debug_services_->ResetLoadedTensors();
  330. }
  331. // In single graph case, reset graph_ptr_ to be nullptr when debugger receives a new graph
  332. if (received_new_graph_) {
  333. graph_ptr_ = nullptr;
  334. CheckGraphPtr(graph_ptr);
  335. }
  336. } else if (debugger_enabled_ && graph_id == rungraph_id_list_.front() && device_target_ == kGPUDevice &&
  337. !MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_MINDRT)) {
  338. // Multiple graph, and not the initial step,
  339. // stop only when receive the first sub run graph for each step for old runtime
  340. // if we have stopped for the last kernel before, no need to stop again
  341. if (pipeline::GraphExecutorPy::GetDebugTerminate()) {
  342. return;
  343. }
  344. if (!(run_level_ == "node" && suspended_at_last_kernel_)) {
  345. CommandLoop();
  346. }
  347. debug_services_->ResetLoadedTensors();
  348. }
  349. // resets for the new graph
  350. suspended_at_last_kernel_ = false;
  351. }
  352. void Debugger::SendMultiGraphsAndClear(const KernelGraphPtr &graph_ptr) {
  353. // only try to enable debugger if they are not all dataset graphs
  354. if (!debugger_enabled_) {
  355. EnableDebugger();
  356. }
  357. if (debugger_enabled_) {
  358. // only send compiled graphs once at the initial step.
  359. auto dbg_graph_ptr = graph_ptr_;
  360. // use current graph ptr to load parameters
  361. graph_ptr_ = graph_ptr;
  362. LoadParametersAndConst();
  363. // revert graph ptr to original value
  364. graph_ptr_ = dbg_graph_ptr;
  365. SendMultiGraphsAndSuspend(graph_proto_list_);
  366. graph_proto_list_.clear();
  367. received_new_graph_ = false;
  368. }
  369. }
  370. bool Debugger::DumpDataEnabledIteration() const {
  371. auto &dump_json_parser = DumpJsonParser::GetInstance();
  372. if (!dump_json_parser.e2e_dump_enabled()) {
  373. return false;
  374. }
  375. auto cur_iter = dump_json_parser.cur_dump_iter();
  376. if (dump_json_parser.IsDumpIter(cur_iter)) {
  377. return true;
  378. }
  379. return false;
  380. }
  381. uint32_t Debugger::GetRankID() {
  382. auto ms_context = MsContext::GetInstance();
  383. MS_EXCEPTION_IF_NULL(ms_context);
  384. std::string device_target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  385. uint32_t device_id = ms_context->get_param<uint32_t>(MS_CTX_DEVICE_ID);
  386. const auto &device_context =
  387. device::DeviceContextManager::GetInstance().GetOrCreateDeviceContext({device_target, device_id});
  388. uint32_t rank_id = device_context->GetRankID();
  389. return rank_id;
  390. }
  391. void Debugger::Dump(const KernelGraphPtr &kernel_graph) const {
  392. uint32_t rank_id = GetRankID();
  393. E2eDump::DumpRunIter(kernel_graph, rank_id);
  394. if (debugger_ && debugger_->DebuggerBackendEnabled()) {
  395. MS_EXCEPTION_IF_NULL(kernel_graph);
  396. (void)E2eDump::DumpParametersAndConstData(kernel_graph.get(), rank_id, debugger_.get());
  397. } else {
  398. DumpJsonParser::GetInstance().UpdateDumpIter();
  399. }
  400. }
  401. void Debugger::DumpSingleNode(const CNodePtr &node, uint32_t graph_id) {
  402. if (debugger_ && debugger_->DebuggerBackendEnabled()) {
  403. uint32_t rank_id = GetRankID();
  404. (void)E2eDump::DumpSingleNodeData(node, graph_id, rank_id, debugger_.get());
  405. }
  406. }
  407. void Debugger::DumpSetup(const KernelGraphPtr &kernel_graph) const {
  408. MS_LOG(INFO) << "Start!";
  409. MS_EXCEPTION_IF_NULL(kernel_graph);
  410. E2eDump::DumpSetup(kernel_graph.get());
  411. MS_LOG(INFO) << "Finish!";
  412. }
  413. void Debugger::DumpInGraphCompiler(const KernelGraphPtr &kernel_graph) {
  414. // This function will be called for new GPU runtime using MindRTBackend
  415. auto &json_parser = DumpJsonParser::GetInstance();
  416. if (json_parser.e2e_dump_enabled()) {
  417. uint32_t rank_id = GetRankID();
  418. kernel_graph->set_root_graph_id(kernel_graph->graph_id());
  419. std::string final_graph = "trace_code_graph_" + std::to_string(kernel_graph->graph_id());
  420. std::string root_dir = json_parser.path() + "/rank_" + std::to_string(rank_id);
  421. std::string target_dir = root_dir + "/graphs";
  422. std::string ir_file_path = target_dir + "/" + "ms_output_" + final_graph + ".ir";
  423. DumpIRProtoWithSrcInfo(kernel_graph, final_graph, target_dir, kDebugWholeStack);
  424. DumpIR("trace_code_graph", kernel_graph, true, kWholeStack, ir_file_path);
  425. DumpGraphExeOrder("ms_execution_order_graph_" + std::to_string(kernel_graph->graph_id()) + ".csv", root_dir,
  426. kernel_graph->execution_order());
  427. }
  428. }
  429. void Debugger::PostExecuteGraphDebugger() {
  430. // On CPU, update dump iteration, Parameters and consts are not dumped here
  431. if (device_target_ == kCPUDevice) {
  432. DumpJsonParser::GetInstance().UpdateDumpIter();
  433. return;
  434. }
  435. // Only GPU is supported for MindRTBackend
  436. if (device_target_ != kGPUDevice) {
  437. return;
  438. }
  439. // LoadParametersAndConst for all the graphs that have been run in the current step
  440. if (debugger_) {
  441. for (auto graph : graph_ptr_step_vec_) {
  442. debugger_->LoadParametersAndConst(graph);
  443. }
  444. }
  445. // debug used for dump
  446. if (debugger_ && debugger_->CheckDebuggerDumpEnabled()) {
  447. // Dump Parameters and consts
  448. for (auto graph : graph_ptr_step_vec_) {
  449. debugger_->Dump(graph);
  450. if (!debugger_->debugger_enabled()) {
  451. debugger_->ClearCurrentData();
  452. }
  453. }
  454. }
  455. if (debugger_) {
  456. debugger_->PostExecute();
  457. }
  458. E2eDump::UpdateIterGPUDump();
  459. }
  460. void Debugger::PostExecute() {
  461. // access lock for public method
  462. std::lock_guard<std::mutex> a_lock(access_lock_);
  463. if (pipeline::GraphExecutorPy::GetDebugTerminate()) {
  464. return;
  465. }
  466. if (debugger_ && debugger_->DebuggerBackendEnabled()) {
  467. // analyze tensor data and send the watchpoints been hit
  468. if (debugger_enabled_ && !is_dataset_graph_) {
  469. SendWatchpoints(CheckWatchpoints());
  470. // no need to suspend at each graph for GPU old runtime, suspension happens in preExecute
  471. if (device_target_ == kAscendDevice) {
  472. CommandLoop();
  473. } else if (device_target_ == kGPUDevice && MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_MINDRT)) {
  474. if (!(run_level_ == "node" && suspended_at_last_kernel_)) {
  475. CommandLoop();
  476. }
  477. }
  478. if (device_target_ != kGPUDevice) {
  479. num_step_++;
  480. }
  481. }
  482. // Only keep parameters in th current map
  483. // GPU ResetLoadedTensors for old runtime happens in preExecute
  484. if ((device_target_ == kGPUDevice && MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_MINDRT)) ||
  485. device_target_ == kAscendDevice) {
  486. debug_services_->ResetLoadedTensors();
  487. }
  488. }
  489. }
  490. bool Debugger::ReadNodeDataRequired(const CNodePtr &kernel) const {
  491. if (debugger_enabled_ && !is_dataset_graph_) {
  492. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  493. // if node has a watchpoint on it, is next_to node, or continue_to node then read the kernel tensor data
  494. if (is_watchpoint || (run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_))) {
  495. return true;
  496. }
  497. }
  498. return false;
  499. }
  500. void Debugger::PostExecuteNode(const CNodePtr &kernel, bool last_kernel) {
  501. // access lock for public method
  502. std::lock_guard<std::mutex> a_lock(access_lock_);
  503. if (pipeline::GraphExecutorPy::GetDebugTerminate()) {
  504. return;
  505. }
  506. if (debugger_enabled_ && !is_dataset_graph_) {
  507. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  508. // if kernel is watchpoint,and get hit. suspend.
  509. bool hit_empty_flag = true;
  510. if (is_watchpoint) {
  511. auto hits = CheckWatchpoints(cur_name_, kernel);
  512. if (!hits.empty()) {
  513. SendWatchpoints(hits);
  514. CommandLoop();
  515. hit_empty_flag = false;
  516. }
  517. }
  518. if (hit_empty_flag && run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_)) {
  519. // if kernel is not watchpoint and is next_to or continue_to node, suspend
  520. // sets a bool to be checked in preExecute to avoid double stopping at last kernel in the last graph
  521. if (last_kernel) {
  522. suspended_at_last_kernel_ = true;
  523. }
  524. CommandLoop();
  525. }
  526. return;
  527. }
  528. }
  529. void Debugger::LoadGraphs(const KernelGraphPtr &graph_ptr) {
  530. MS_EXCEPTION_IF_NULL(graph_ptr);
  531. if (graph_ptr_ != graph_ptr) {
  532. MS_LOG(INFO) << "LoadGraphs Debugger got new graph: " << graph_ptr->graph_id();
  533. received_new_graph_ = true;
  534. // save new graph_ptr
  535. graph_ptr_ = graph_ptr;
  536. CheckDatasetGraph();
  537. if (!is_dataset_graph_) {
  538. // get proto for new graph_ptr
  539. auto graph_proto = GetGraphProto(graph_ptr);
  540. // add new graph proto to graph_proto_list_
  541. graph_proto_list_.push_back(graph_proto);
  542. graph_ptr_list_.push_back(graph_ptr);
  543. not_dataset_graph_sum_++;
  544. }
  545. // reset is_dataset_graph to be false
  546. is_dataset_graph_ = false;
  547. }
  548. }
  549. // In single graph cases, check single graph ptr
  550. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  551. MS_EXCEPTION_IF_NULL(graph_ptr);
  552. if (graph_ptr_ != graph_ptr) {
  553. MS_LOG(INFO) << "CheckGraphPtr Debugger got new graph: " << graph_ptr->graph_id();
  554. // save new graph_ptr
  555. graph_ptr_ = graph_ptr;
  556. if (!is_dataset_graph_) {
  557. // only try to enable debugger if it is not a dataset graph
  558. if (!debugger_enabled_) {
  559. EnableDebugger();
  560. }
  561. if (debugger_enabled_) {
  562. LoadParametersAndConst();
  563. // get graph proto and send to Mindinsight
  564. auto graph_proto = graph_proto_list_.front();
  565. SendGraphAndSuspend(graph_proto);
  566. graph_proto_list_.clear();
  567. received_new_graph_ = false;
  568. }
  569. }
  570. }
  571. }
  572. void Debugger::CheckDatasetGraph() {
  573. // print parameter node names
  574. MS_EXCEPTION_IF_NULL(graph_ptr_);
  575. const auto &params = graph_ptr_->inputs();
  576. for (const auto &param : params) {
  577. MS_LOG(INFO) << "param: " << GetKernelNodeName(param);
  578. }
  579. // check if there is GetNext or InitDataSetQueue node
  580. const auto &nodes = graph_ptr_->execution_order();
  581. for (const auto &node : nodes) {
  582. auto node_name = AnfAlgo::GetCNodeName(node);
  583. MS_LOG(INFO) << "node: " << GetKernelNodeName(node);
  584. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  585. MS_LOG(INFO) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  586. << node_name;
  587. is_dataset_graph_ = true;
  588. return;
  589. }
  590. }
  591. is_dataset_graph_ = false;
  592. }
  593. GraphProto Debugger::GetGraphProto(const KernelGraphPtr &graph_ptr) const {
  594. // convert kernel graph to debugger modelproto
  595. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr);
  596. return model.graph();
  597. }
  598. void Debugger::SendHeartbeat(int32_t period) {
  599. int num_heartbeat_fail = 0;
  600. const int max_num_heartbeat_fail = 5;
  601. const int retry_milliseconds = 500;
  602. Heartbeat heartbeat;
  603. heartbeat.set_message("Debugger is alive");
  604. heartbeat.set_period(heartbeat_period_second);
  605. SetEnableHeartbeat(CheckDebuggerEnabled());
  606. while (enable_heartbeat_) {
  607. MS_EXCEPTION_IF_NULL(grpc_client_);
  608. EventReply reply = grpc_client_->SendHeartbeat(heartbeat);
  609. if (reply.status() != reply.OK) {
  610. MS_LOG(ERROR) << "Error: SendHeartbeat failed";
  611. num_heartbeat_fail++;
  612. if (num_heartbeat_fail >= max_num_heartbeat_fail) {
  613. MS_LOG(ERROR) << "Maximum number of failure for SendHeartbeat reached : exiting training session.";
  614. SetEnableHeartbeat(false);
  615. break;
  616. } else {
  617. MS_LOG(ERROR) << "Number of consecutive SendHeartbeat fail:" << num_heartbeat_fail;
  618. std::this_thread::sleep_for(std::chrono::milliseconds(retry_milliseconds));
  619. }
  620. } else {
  621. int recheck_period_ms = 200;
  622. for (int i = 0; i < (period * 1000 / recheck_period_ms); i++) {
  623. if (enable_heartbeat_) {
  624. std::this_thread::sleep_for(std::chrono::milliseconds(recheck_period_ms));
  625. } else {
  626. break;
  627. }
  628. }
  629. }
  630. }
  631. }
  632. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  633. if (!CheckSendMetadata()) {
  634. return;
  635. }
  636. // send graph to Mindinsight server
  637. MS_EXCEPTION_IF_NULL(grpc_client_);
  638. EventReply reply = grpc_client_->SendGraph(graph_proto);
  639. if (reply.status() != reply.OK) {
  640. MS_LOG(ERROR) << "Error: SendGraph failed";
  641. }
  642. // enter command loop, wait and process commands
  643. CommandLoop();
  644. }
  645. bool Debugger::SendMetadata(bool version_check) {
  646. // prepare metadata
  647. MS_EXCEPTION_IF_NULL(graph_ptr_);
  648. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  649. Metadata metadata;
  650. metadata.set_device_name(device_name);
  651. metadata.set_cur_step(num_step_);
  652. metadata.set_backend(device_target_);
  653. metadata.set_cur_node(cur_name_);
  654. metadata.set_training_done(training_done_);
  655. metadata.set_ms_version(version_);
  656. MS_LOG(INFO) << "Is training done?" << training_done_;
  657. // set graph number to not_dataset_graph_sum_
  658. metadata.set_graph_num(not_dataset_graph_sum_);
  659. MS_EXCEPTION_IF_NULL(grpc_client_);
  660. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  661. bool ret = false;
  662. if (reply_metadata.status() == reply_metadata.OK) {
  663. if (version_check) {
  664. // get type of the command in meta data reply, it should be version matched
  665. DebuggerCommand cmd = GetCommand(reply_metadata);
  666. if (cmd != DebuggerCommand::kVersionMatchedCMD) {
  667. MS_LOG(ERROR) << "MindInsight version is too old, Mindspore version is " << version_;
  668. Exit();
  669. } else {
  670. if (GetMiVersionMatched(reply_metadata)) {
  671. MS_LOG(INFO) << "MindSpore version is " << version_ << " matches MindInsight version.";
  672. ret = true;
  673. } else {
  674. MS_LOG(ERROR) << "MindSpore version " << version_ << ", did not match MindInsight version.";
  675. CommandLoop();
  676. }
  677. }
  678. } else {
  679. // version check is done before so we can just return true here
  680. ret = true;
  681. }
  682. } else {
  683. MS_LOG(ERROR) << "Error: SendMetadata failed";
  684. }
  685. return ret;
  686. }
  687. void Debugger::SendMultiGraphsAndSuspend(const std::list<GraphProto> &graph_proto_list) {
  688. if (!CheckSendMetadata()) {
  689. return;
  690. }
  691. MS_EXCEPTION_IF_NULL(grpc_client_);
  692. // send multiple graphs to mindinght server
  693. // split graph into chunks if one graph is larger than chunk size
  694. std::list<Chunk> chunked_graph_proto_list;
  695. Chunk chunk;
  696. for (auto graph : graph_proto_list) {
  697. std::string str = graph.SerializeAsString();
  698. auto graph_size = graph.ByteSize();
  699. if (graph_size > g_chunk_size) {
  700. auto sub_graph_str = grpc_client_->ChunkString(str, graph_size);
  701. for (unsigned int i = 0; i < sub_graph_str.size(); i++) {
  702. chunk.set_buffer(sub_graph_str[i]);
  703. if (i < sub_graph_str.size() - 1) {
  704. chunk.set_finished(false);
  705. } else {
  706. chunk.set_finished(true);
  707. }
  708. chunked_graph_proto_list.push_back(chunk);
  709. }
  710. } else {
  711. chunk.set_buffer(str);
  712. chunk.set_finished(true);
  713. chunked_graph_proto_list.push_back(chunk);
  714. }
  715. }
  716. EventReply reply = grpc_client_->SendMultiGraphs(chunked_graph_proto_list);
  717. if (reply.status() != reply.OK) {
  718. MS_LOG(ERROR) << "Error: SendGraph failed";
  719. }
  720. // enter command loop, wait and process commands
  721. CommandLoop();
  722. }
  723. bool Debugger::CheckSendMetadata() {
  724. if (!send_metadata_done_) {
  725. if (!SendMetadata(true)) {
  726. return false;
  727. }
  728. send_metadata_done_ = true;
  729. }
  730. return true;
  731. }
  732. void Debugger::CommandLoop() {
  733. // prepare metadata
  734. MS_EXCEPTION_IF_NULL(graph_ptr_);
  735. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(cur_root_graph_id_);
  736. Metadata metadata;
  737. metadata.set_device_name(device_name);
  738. metadata.set_cur_step(num_step_);
  739. metadata.set_backend(device_target_);
  740. metadata.set_cur_node(cur_name_);
  741. metadata.set_training_done(training_done_);
  742. // loop exit flag
  743. bool run = false;
  744. int num_wait_fail = 0;
  745. const int max_num_wait_fail = 5;
  746. while (!run) {
  747. // wait for command
  748. MS_EXCEPTION_IF_NULL(grpc_client_);
  749. EventReply reply = grpc_client_->WaitForCommand(metadata);
  750. if (reply.status() != reply.OK) {
  751. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  752. num_wait_fail++;
  753. if (num_wait_fail > max_num_wait_fail) {
  754. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session.";
  755. MS_LOG(ERROR) << "Failed to connect to MindInsight debugger server. Please check the config "
  756. "of debugger host and port.";
  757. Exit();
  758. run = true;
  759. } else {
  760. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  761. << num_wait_fail << "s";
  762. std::this_thread::sleep_for(std::chrono::seconds(num_wait_fail));
  763. }
  764. continue;
  765. }
  766. // get type of the command in reply
  767. DebuggerCommand cmd = GetCommand(reply);
  768. if (cmd == DebuggerCommand::kUnknownCMD) {
  769. MS_LOG(DEBUG) << "Debug: debugger received unknown command";
  770. continue;
  771. }
  772. MS_LOG(INFO) << "received command: ";
  773. switch (cmd) {
  774. case DebuggerCommand::kUnknownCMD:
  775. MS_LOG(INFO) << "UnknownCMD";
  776. break;
  777. case DebuggerCommand::kExitCMD:
  778. MS_LOG(INFO) << "ExitCMD";
  779. Exit(true);
  780. // Used for debugger termination
  781. run = true;
  782. break;
  783. case DebuggerCommand::kRunCMD:
  784. ProcessRunCMD(reply);
  785. if (GetRunLevel(reply) != "recheck") {
  786. // exit loop
  787. run = true;
  788. }
  789. break;
  790. case DebuggerCommand::kSetCMD:
  791. ProcessKSetCMD(reply);
  792. break;
  793. case DebuggerCommand::kViewCMD:
  794. ProcessKViewCMD(reply);
  795. break;
  796. case DebuggerCommand::kVersionMatchedCMD:
  797. MS_LOG(ERROR) << "Received unexpected Version Matched CMD from Mindinsight.";
  798. Exit();
  799. break;
  800. default:
  801. MS_LOG(ERROR) << "Received unknown CMD from Mindinsight";
  802. Exit();
  803. break;
  804. }
  805. }
  806. }
  807. void Debugger::ProcessRunCMD(const EventReply &reply) {
  808. MS_LOG(INFO) << "RunCMD";
  809. if (GetRunLevel(reply) == "recheck") {
  810. MS_LOG(INFO) << "rechecking all watchpoints";
  811. SendWatchpoints(CheckWatchpoints("", nullptr, true));
  812. } else {
  813. // no longer the initial suspension.
  814. initial_suspend_ = false;
  815. // print run cmd content
  816. // get run_level and node_name
  817. run_level_ = GetRunLevel(reply);
  818. node_name_ = GetNodeName(reply);
  819. MS_LOG(INFO) << "run_level: " << run_level_;
  820. MS_LOG(INFO) << "node_name_: " << node_name_;
  821. }
  822. }
  823. void Debugger::ProcessKSetCMD(const EventReply &reply) {
  824. MS_LOG(INFO) << "SetCMD";
  825. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  826. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  827. if (GetWatchpointDelete(reply)) {
  828. MS_LOG(INFO) << "Deleting watchpoint";
  829. RemoveWatchpoint(GetWatchpointID(reply));
  830. } else {
  831. MS_LOG(INFO) << "Setting watchpoint";
  832. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  833. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  834. for (const auto &node : recieved_nodes) {
  835. MS_LOG(INFO) << "node name: " << node.node_name();
  836. MS_LOG(INFO) << "node type: " << node.node_type();
  837. }
  838. ProtoVector<WatchCondition_Parameter> parameters = GetParameters(reply);
  839. for (const auto &parameter : parameters) {
  840. MS_LOG(INFO) << "parameter name: " << parameter.name();
  841. MS_LOG(INFO) << "parameter is disabled: " << parameter.disabled();
  842. MS_LOG(INFO) << "parameter value: " << parameter.value();
  843. }
  844. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply), GetParameters(reply));
  845. }
  846. }
  847. void Debugger::ProcessKViewCMD(const EventReply &reply) {
  848. MS_LOG(INFO) << "ViewCMD";
  849. // print view cmd content
  850. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  851. for (auto received_tensor : received_tensors) {
  852. MS_LOG(INFO) << "tensor node name: " << received_tensor.node_name();
  853. MS_LOG(INFO) << "tensor slot: " << received_tensor.slot();
  854. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << received_tensor.finished() << std::noboolalpha;
  855. MS_LOG(INFO) << "tensor iter: " << received_tensor.iter();
  856. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << received_tensor.truncate() << std::noboolalpha;
  857. }
  858. switch (reply.view_cmd().level()) {
  859. case debugger::ViewCMD_Level::ViewCMD_Level_base:
  860. MS_LOG(INFO) << "Tensor base request.";
  861. ViewBaseLevel(reply);
  862. break;
  863. case debugger::ViewCMD_Level::ViewCMD_Level_statistics:
  864. MS_LOG(INFO) << "Tensor statistics request.";
  865. ViewStatLevel(reply);
  866. break;
  867. case debugger::ViewCMD_Level::ViewCMD_Level_value:
  868. MS_LOG(INFO) << "Tensor value request.";
  869. ViewValueLevel(reply);
  870. break;
  871. default:
  872. MS_LOG(DEBUG) << "Debug: Unknown tensor info level";
  873. break;
  874. }
  875. }
  876. void Debugger::ViewValueLevel(const EventReply &reply) {
  877. MS_LOG(INFO) << "Sending tensors";
  878. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  879. // print view cmd reply
  880. for (auto tensor : tensors) {
  881. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  882. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  883. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  884. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  885. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  886. MS_LOG(INFO) << "tensor dims: ";
  887. for (auto dim : tensor.dims()) {
  888. MS_LOG(INFO) << dim << ",";
  889. }
  890. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  891. }
  892. MS_EXCEPTION_IF_NULL(grpc_client_);
  893. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  894. if (send_tensors_reply.status() != debugger::EventReply::OK) {
  895. MS_LOG(ERROR) << "Error: SendTensors failed";
  896. }
  897. }
  898. void Debugger::ViewStatLevel(const EventReply &reply) {
  899. std::list<TensorSummary> tensor_stats_list = LoadTensorsStat(GetTensors(reply));
  900. EventReply send_tensors_stat_reply = grpc_client_->SendTensorStats(tensor_stats_list);
  901. if (send_tensors_stat_reply.status() != debugger::EventReply::OK) {
  902. MS_LOG(ERROR) << "Error: SendTensorsStats failed.";
  903. }
  904. }
  905. void Debugger::ViewBaseLevel(const EventReply &reply) {
  906. std::list<TensorBase> tensor_base_list = LoadTensorsBase(GetTensors(reply));
  907. EventReply send_tensor_base_reply = grpc_client_->SendTensorBase(tensor_base_list);
  908. if (send_tensor_base_reply.status() != debugger::EventReply::OK) {
  909. MS_LOG(ERROR) << "Error: SendTensorsBase failed.";
  910. }
  911. }
  912. void AddTensorProtoInfo(TensorProto *tensor_item, const TensorProto &tensor) {
  913. tensor_item->set_node_name(tensor.node_name());
  914. tensor_item->set_slot(tensor.slot());
  915. tensor_item->set_iter(tensor.iter());
  916. tensor_item->set_truncate(tensor.truncate());
  917. tensor_item->clear_tensor_content();
  918. tensor_item->clear_data_type();
  919. tensor_item->clear_dims();
  920. }
  921. void AddTensorStatInfo(const DebugServices::TensorStat &tensor_stat,
  922. std::list<TensorSummary> *const tensor_summary_list) {
  923. if (tensor_summary_list == nullptr) {
  924. MS_LOG(DEBUG) << "tensor_summary_list is nullptr.";
  925. return;
  926. }
  927. TensorSummary tensor_summary_item;
  928. TensorBase *tensor_base = tensor_summary_item.mutable_tensor_base();
  929. tensor_base->set_data_type(tensor_stat.dtype);
  930. tensor_base->set_data_size((int64_t)tensor_stat.data_size);
  931. for (auto elem : tensor_stat.shape) {
  932. tensor_base->add_shape(elem);
  933. }
  934. Statistics *tensor_statistics = tensor_summary_item.mutable_statistics();
  935. tensor_statistics->set_is_bool(tensor_stat.is_bool);
  936. tensor_statistics->set_max_value(static_cast<float>(tensor_stat.max_value));
  937. tensor_statistics->set_min_value(static_cast<float>(tensor_stat.min_value));
  938. tensor_statistics->set_avg_value(static_cast<float>(tensor_stat.avg_value));
  939. tensor_statistics->set_count(tensor_stat.count);
  940. tensor_statistics->set_neg_zero_count(tensor_stat.neg_zero_count);
  941. tensor_statistics->set_pos_zero_count(tensor_stat.pos_zero_count);
  942. tensor_statistics->set_nan_count(tensor_stat.nan_count);
  943. tensor_statistics->set_neg_inf_count(tensor_stat.neg_inf_count);
  944. tensor_statistics->set_pos_inf_count(tensor_stat.pos_inf_count);
  945. tensor_statistics->set_zero_count(tensor_stat.zero_count);
  946. tensor_summary_list->push_back(tensor_summary_item);
  947. }
  948. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id,
  949. const ProtoVector<WatchCondition_Parameter> &parameters) {
  950. std::vector<std::tuple<std::string, bool>> check_node_list;
  951. std::vector<DebugServices::parameter_t> parameter_list;
  952. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  953. [](const WatchNode &node) -> std::tuple<std::string, bool> {
  954. return make_tuple(node.node_name(), node.node_type() == "scope");
  955. });
  956. std::transform(
  957. parameters.begin(), parameters.end(), std::back_inserter(parameter_list),
  958. [](const WatchCondition_Parameter &parameter) -> DebugServices::parameter_t {
  959. return DebugServices::parameter_t{parameter.name(), parameter.disabled(), parameter.value(), parameter.hit()};
  960. });
  961. debug_services_->AddWatchpoint(id, condition.condition(), condition.value(), check_node_list, parameter_list);
  962. }
  963. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  964. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  965. std::vector<std::string> name;
  966. std::vector<std::string> ret_name;
  967. std::vector<const char *> data_ptr;
  968. std::vector<ssize_t> data_size;
  969. std::vector<unsigned int> dtype;
  970. std::vector<std::vector<int64_t>> shape;
  971. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  972. // ret_name will contain tensor names that are found in TensorLoader
  973. // items in ret_name will be in the same order with tensors if found
  974. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  975. std::list<TensorProto> tensor_list;
  976. size_t result_index = 0;
  977. for (auto tensor : tensors) {
  978. ssize_t size_iter = 0;
  979. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  980. TensorProto tensor_item;
  981. tensor_item.set_finished(true);
  982. AddTensorProtoInfo(&tensor_item, tensor);
  983. tensor_list.push_back(tensor_item);
  984. continue;
  985. }
  986. ssize_t tensor_size = data_size[result_index];
  987. while (size_iter < tensor_size) {
  988. ssize_t chunk_size = g_chunk_size;
  989. TensorProto tensor_item;
  990. tensor_item.set_finished(false);
  991. if (tensor_size - size_iter <= g_chunk_size) {
  992. chunk_size = tensor_size - size_iter;
  993. tensor_item.set_finished(true);
  994. }
  995. AddTensorProtoInfo(&tensor_item, tensor);
  996. // return empty tensor if didn't find the requested tensor
  997. tensor_item.set_tensor_content(data_ptr[result_index] + size_iter, chunk_size);
  998. tensor_item.set_data_type((debugger::DataType)dtype[result_index]);
  999. for (auto &elem : shape[result_index]) {
  1000. tensor_item.add_dims(elem);
  1001. }
  1002. // add tensor to result list and increment result_index to check next item in ret_name
  1003. tensor_list.push_back(tensor_item);
  1004. if (size_iter > INT_MAX - g_chunk_size) {
  1005. MS_EXCEPTION(ValueError) << size_iter << " + " << g_chunk_size << " would lead to integer overflow!";
  1006. }
  1007. size_iter += g_chunk_size;
  1008. }
  1009. result_index++;
  1010. }
  1011. return tensor_list;
  1012. }
  1013. std::list<TensorBase> Debugger::LoadTensorsBase(const ProtoVector<TensorProto> &tensors) const {
  1014. std::list<TensorBase> tensor_base_list;
  1015. std::vector<std::string> name;
  1016. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  1017. std::vector<std::tuple<std::string, std::shared_ptr<TensorData>>> result_list;
  1018. debug_services_->SearchNodesTensors(name, &result_list);
  1019. for (auto result : result_list) {
  1020. auto tensor = std::get<1>(result);
  1021. if (!tensor || cur_root_graph_id_ != tensor->GetRootGraphId()) {
  1022. // tensor was not found or tensor's graph was not executed in the current step, creating empty tensor base.
  1023. TensorBase tensor_base_item;
  1024. tensor_base_item.set_data_size(0);
  1025. tensor_base_item.set_data_type(0);
  1026. tensor_base_item.add_shape(0);
  1027. tensor_base_list.push_back(tensor_base_item);
  1028. continue;
  1029. }
  1030. // tensor was found creating tensor base object.
  1031. TensorBase tensor_base_item;
  1032. tensor_base_item.set_data_size((int64_t)tensor->GetByteSize());
  1033. tensor_base_item.set_data_type((int32_t)tensor->GetType());
  1034. for (auto elem : tensor->GetShape()) {
  1035. tensor_base_item.add_shape(elem);
  1036. }
  1037. tensor_base_list.push_back(tensor_base_item);
  1038. }
  1039. return tensor_base_list;
  1040. }
  1041. std::list<TensorSummary> Debugger::LoadTensorsStat(const ProtoVector<TensorProto> &tensors) const {
  1042. std::list<TensorSummary> tensor_summary_list;
  1043. std::vector<std::string> name;
  1044. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  1045. std::vector<std::tuple<std::string, std::shared_ptr<TensorData>>> result_list;
  1046. debug_services_->SearchNodesTensors(name, &result_list);
  1047. for (auto result : result_list) {
  1048. auto tensor = std::get<1>(result);
  1049. if (!tensor || cur_root_graph_id_ != tensor->GetRootGraphId()) {
  1050. // tensor was not found or tensor's graph was not executed in the current step, creating empty tensor summary.
  1051. DebugServices::TensorStat tensor_stat;
  1052. AddTensorStatInfo(tensor_stat, &tensor_summary_list);
  1053. continue;
  1054. }
  1055. // tensor was found creating tensor summary object.
  1056. DebugServices::TensorStat tensor_stat = DebugServices::GetTensorStatistics(tensor);
  1057. AddTensorStatInfo(tensor_stat, &tensor_summary_list);
  1058. }
  1059. return tensor_summary_list;
  1060. }
  1061. std::shared_ptr<TensorData> Debugger::GetTensor(const std::string &tensor_name) const {
  1062. return debug_services_->GetTensor(tensor_name);
  1063. }
  1064. void Debugger::Exit(bool exit_success) {
  1065. // debugger will notify main thread to exit because main thread can only exit at step boundary.
  1066. MS_LOG(INFO) << "Exit Debugger";
  1067. SetEnableHeartbeat(false);
  1068. pipeline::GraphExecutorPy::DebugTerminate(true, exit_success);
  1069. }
  1070. std::list<WatchpointHit> Debugger::CheckWatchpoints(const std::string &watchnode, const CNodePtr &kernel,
  1071. bool recheck) {
  1072. std::vector<std::string> name;
  1073. std::vector<std::string> slot;
  1074. std::vector<int> condition;
  1075. std::vector<unsigned int> watchpoint_id;
  1076. std::vector<std::string> overflow_ops;
  1077. std::vector<std::vector<DebugServices::parameter_t>> parameters;
  1078. std::vector<int32_t> error_codes;
  1079. std::vector<std::shared_ptr<TensorData>> tensor_list;
  1080. if (watchnode.empty()) {
  1081. tensor_list = debug_services_->GetTensor();
  1082. } else {
  1083. tensor_list = debug_services_->GetNodeTensor(kernel);
  1084. }
  1085. std::vector<std::string> file_list;
  1086. MS_LOG(INFO) << "checkwatchpoints call for step " << num_step_;
  1087. debug_services_->CheckWatchpoints(&name, &slot, &condition, &watchpoint_id, &parameters, &error_codes, overflow_ops,
  1088. file_list, &tensor_list, initial_suspend_, watchnode.empty(), recheck);
  1089. std::list<WatchpointHit> hits;
  1090. for (unsigned int i = 0; i < name.size(); i++) {
  1091. WatchpointHit hit;
  1092. std::vector<DebugServices::parameter_t> &parameter = parameters[i];
  1093. hit.set_id(watchpoint_id[i]);
  1094. hit.set_error_code(error_codes[i]);
  1095. // here TensorProto act as a tensor indicator, not sending tensor content
  1096. TensorProto *tensor_item = hit.mutable_tensor();
  1097. tensor_item->set_node_name(name[i]);
  1098. tensor_item->set_slot(slot[i]);
  1099. tensor_item->set_finished(true);
  1100. WatchCondition *condition_item = hit.mutable_watch_condition();
  1101. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  1102. for (const auto &p : parameter) {
  1103. auto x = condition_item->mutable_params()->Add();
  1104. x->set_name(p.name);
  1105. x->set_disabled(p.disabled);
  1106. x->set_value(p.value);
  1107. x->set_hit(p.hit);
  1108. x->set_actual_value(p.actual_value);
  1109. }
  1110. hits.push_back(hit);
  1111. }
  1112. return hits;
  1113. }
  1114. void Debugger::SendWatchpoints(const std::list<WatchpointHit> &points) {
  1115. // send info about watchpoint
  1116. if (!points.empty()) {
  1117. MS_EXCEPTION_IF_NULL(grpc_client_);
  1118. EventReply reply = grpc_client_->SendWatchpointHits(points);
  1119. if (reply.status() != reply.OK) {
  1120. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  1121. }
  1122. }
  1123. }
  1124. bool Debugger::DumpTensorToFile(const std::string &tensor_name, bool trans_flag, const std::string &filepath,
  1125. const std::string &host_fmt, const std::vector<int64_t> &host_shape, TypeId host_type,
  1126. TypeId device_type, const std::string &addr_format, size_t slot) const {
  1127. return debug_services_.get()->DumpTensorToFile(tensor_name, trans_flag, filepath, host_fmt, host_shape, host_type,
  1128. device_type, addr_format, slot);
  1129. }
  1130. bool Debugger::LoadNewTensor(const std::shared_ptr<TensorData> &tensor, bool keep_prev) {
  1131. return debug_services_.get()->LoadNewTensor(tensor, keep_prev);
  1132. }
  1133. bool Debugger::debugger_enabled() const { return debugger_enabled_; }
  1134. DebuggerCommand GetCommand(const EventReply &reply) {
  1135. DebuggerCommand cmd = DebuggerCommand::kUnknownCMD;
  1136. switch (reply.cmd_case()) {
  1137. case debugger::EventReply::CmdCase::kExit:
  1138. cmd = DebuggerCommand::kExitCMD;
  1139. break;
  1140. case debugger::EventReply::CmdCase::kRunCmd:
  1141. cmd = DebuggerCommand::kRunCMD;
  1142. break;
  1143. case debugger::EventReply::CmdCase::kSetCmd:
  1144. cmd = DebuggerCommand::kSetCMD;
  1145. break;
  1146. case debugger::EventReply::CmdCase::kViewCmd:
  1147. cmd = DebuggerCommand::kViewCMD;
  1148. break;
  1149. case debugger::EventReply::CmdCase::kVersionMatched:
  1150. cmd = DebuggerCommand::kVersionMatchedCMD;
  1151. break;
  1152. default:
  1153. MS_LOG(DEBUG) << "Debug: UnknownCMD";
  1154. break;
  1155. }
  1156. return cmd;
  1157. }
  1158. ProtoVector<WatchCondition_Parameter> GetParameters(const EventReply &reply) {
  1159. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  1160. MS_LOG(ERROR) << "Error: Can not get Parameters from command. Returning default value: ProtoVector<Parameter>().";
  1161. return ProtoVector<WatchCondition_Parameter>();
  1162. }
  1163. return reply.set_cmd().watch_condition().params();
  1164. }
  1165. ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply) {
  1166. if (!reply.has_set_cmd()) {
  1167. MS_LOG(ERROR) << "Error: Not SetCMD, can not get WatchNodes. Returning default value: ProtoVector<WatchNode>().";
  1168. return ProtoVector<WatchNode>();
  1169. }
  1170. return reply.set_cmd().watch_nodes();
  1171. }
  1172. std::string GetRunLevel(const EventReply &reply) {
  1173. if (!reply.has_run_cmd()) {
  1174. MS_LOG(ERROR) << "Error: Not RunCMD, can not get RunLevel. Returning default value: "
  1175. "";
  1176. return "";
  1177. }
  1178. return reply.run_cmd().run_level();
  1179. }
  1180. std::string GetNodeName(const EventReply &reply) {
  1181. if (!reply.has_run_cmd()) {
  1182. MS_LOG(ERROR) << "Error: Not RunCMD, can not get NodeName. Returning default value: "
  1183. "";
  1184. return "";
  1185. }
  1186. return reply.run_cmd().node_name();
  1187. }
  1188. WatchCondition GetWatchcondition(const EventReply &reply) {
  1189. if (!reply.has_set_cmd() || !reply.set_cmd().has_watch_condition()) {
  1190. MS_LOG(ERROR) << "Error: Can not get WatchCondition from command. Returning default value: WatchCondition().";
  1191. return WatchCondition();
  1192. }
  1193. return reply.set_cmd().watch_condition();
  1194. }
  1195. int32_t GetWatchpointID(const EventReply &reply) {
  1196. if (!reply.has_set_cmd()) {
  1197. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint ID. Returning default value: 0.";
  1198. return 0;
  1199. }
  1200. return reply.set_cmd().id();
  1201. }
  1202. bool GetWatchpointDelete(const EventReply &reply) {
  1203. if (!reply.has_set_cmd()) {
  1204. MS_LOG(ERROR) << "Error: Not SetCMD, can not get Watchpoint delete flag. Returning default value: false.";
  1205. return false;
  1206. }
  1207. return reply.set_cmd().delete_();
  1208. }
  1209. ProtoVector<TensorProto> GetTensors(const EventReply &reply) {
  1210. if (!reply.has_view_cmd()) {
  1211. MS_LOG(ERROR) << "Error: Not ViewCMD, can not get Tensors. Returning default value: ProtoVector<TensorProto>().";
  1212. return ProtoVector<TensorProto>();
  1213. }
  1214. return reply.view_cmd().tensors();
  1215. }
  1216. std::string GetTensorFullName(const TensorProto &tensor) {
  1217. string node_name = tensor.node_name();
  1218. if (tensor.truncate()) {
  1219. // scopes in node name are separated by '/'
  1220. // use the name without scope if truncate is true
  1221. std::size_t found = node_name.find_last_of("/");
  1222. node_name = node_name.substr(found + 1);
  1223. }
  1224. return node_name + ":" + tensor.slot() + (tensor.iter() == "" ? "" : ":" + tensor.iter());
  1225. }
  1226. bool GetMiVersionMatched(const EventReply &reply) { return reply.version_matched(); }
  1227. bool Debugger::partial_memory() const { return partial_memory_; }
  1228. void Debugger::SetEnableHeartbeat(bool enabled) { enable_heartbeat_ = enabled; }
  1229. void Debugger::SetCurNode(const std::string &cur_name) {
  1230. // access lock for public method
  1231. std::lock_guard<std::mutex> a_lock(access_lock_);
  1232. cur_name_ = cur_name;
  1233. }
  1234. std::string Debugger::run_level() const { return run_level_; }
  1235. void Debugger::SetTrainingDone(bool training_done) { training_done_ = training_done; }
  1236. bool Debugger::CheckPort(const std::string &port) const {
  1237. int num = 0;
  1238. const int min_port_num = 1;
  1239. const int max_port_num = 65535;
  1240. const int decimal = 10;
  1241. if (port[0] == '0' && port[1] != '\0') return false;
  1242. int i = 0;
  1243. while (port[i] != '\0') {
  1244. if (port[i] < '0' || port[i] > '9') return false;
  1245. num = num * decimal + (port[i] - '0');
  1246. if (num > max_port_num) return false;
  1247. i++;
  1248. }
  1249. if (num < min_port_num) return false;
  1250. return true;
  1251. }
  1252. bool Debugger::CheckIp(const std::string &host) const {
  1253. std::regex reg_ip(
  1254. "(25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"
  1255. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  1256. "[.](25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])"
  1257. "[.](25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])");
  1258. std::smatch smat;
  1259. std::string host_str = host;
  1260. return std::regex_match(host_str, smat, reg_ip);
  1261. }
  1262. uint32_t Debugger::GetFirstRunGraphId() const { return rungraph_id_list_.front(); }
  1263. void Debugger::LoadSingleAnfnode(const AnfNodePtr &anf_node, const size_t output_index, uint32_t root_graph_id) {
  1264. MS_EXCEPTION_IF_NULL(anf_node);
  1265. if (!anf_node->isa<Parameter>() && !anf_node->isa<ValueNode>()) {
  1266. return;
  1267. }
  1268. // When MindRT is used, only ValueNodes and ParameterWeights can be loaded from device to host
  1269. if (MsContext::GetInstance()->get_param<bool>(MS_CTX_ENABLE_MINDRT) && (device_target_ == kGPUDevice)) {
  1270. if (!anf_node->isa<ValueNode>() &&
  1271. !(anf_node->isa<Parameter>() && AnfAlgo::IsParameterWeight(anf_node->cast<ParameterPtr>()))) {
  1272. return;
  1273. }
  1274. }
  1275. // for parameters and value nodes, set its execution order to be 0;
  1276. int exec_order = 0;
  1277. std::string node_name = GetKernelNodeName(anf_node);
  1278. GetFileKernelName(NOT_NULL(&node_name));
  1279. // check if output adde exists, if not, return;
  1280. if (!AnfAlgo::OutputAddrExist(anf_node, output_index)) {
  1281. return;
  1282. }
  1283. auto addr = AnfAlgo::GetOutputAddr(anf_node, output_index);
  1284. MS_EXCEPTION_IF_NULL(addr);
  1285. auto type = AnfAlgo::GetOutputInferDataType(anf_node, output_index);
  1286. if (!IsTypeDebuggerSupported(type)) {
  1287. return;
  1288. }
  1289. auto format = kOpFormat_DEFAULT;
  1290. string tensor_name = node_name + ':' + "0";
  1291. ShapeVector int_shapes = trans::GetRuntimePaddingShape(anf_node, output_index);
  1292. bool keep_prev;
  1293. if (anf_node->isa<Parameter>()) {
  1294. keep_prev = true;
  1295. debug_services_->MoveTensorCurrentToPrev(tensor_name);
  1296. } else {
  1297. keep_prev = false;
  1298. }
  1299. bool ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, 0, keep_prev, root_graph_id);
  1300. if (!ret) {
  1301. MS_LOG(ERROR) << "LoadMemToHost:"
  1302. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1303. }
  1304. }
  1305. void Debugger::LoadParametersAndConst() {
  1306. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  1307. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1308. // load parameters
  1309. MS_LOG(INFO) << "Start to load Parameters for graph " << graph_ptr_->graph_id() << ".";
  1310. auto root_graph_id = graph_ptr_->root_graph_id();
  1311. const auto &parameters = graph_ptr_->inputs();
  1312. for (auto &item : parameters) {
  1313. LoadSingleAnfnode(item, PARAMETER_OUTPUT_INDEX, root_graph_id);
  1314. }
  1315. // load value nodes
  1316. // get all constant values from the graph
  1317. MS_LOG(INFO) << "Start to load value nodes for graph " << graph_ptr_->graph_id() << ".";
  1318. const auto value_nodes = graph_ptr_->graph_value_nodes();
  1319. for (auto &item : value_nodes) {
  1320. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX, root_graph_id);
  1321. }
  1322. }
  1323. void Debugger::LoadParametersAndConst(const KernelGraphPtr &graph) {
  1324. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  1325. MS_EXCEPTION_IF_NULL(graph);
  1326. // load parameters
  1327. MS_LOG(INFO) << "Start to load Parameters for graph " << graph->graph_id() << ".";
  1328. auto root_graph_id = graph->root_graph_id();
  1329. const auto &parameters = graph->inputs();
  1330. for (auto &item : parameters) {
  1331. LoadSingleAnfnode(item, PARAMETER_OUTPUT_INDEX, root_graph_id);
  1332. }
  1333. // load value nodes
  1334. // get all constant values from the graph
  1335. MS_LOG(INFO) << "Start to load value nodes for graph " << graph->graph_id() << ".";
  1336. const auto value_nodes = graph->graph_value_nodes();
  1337. for (auto &item : value_nodes) {
  1338. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX, root_graph_id);
  1339. }
  1340. }
  1341. void Debugger::LoadGraphOutputs() {
  1342. if (!(debugger_enabled() && device_target_ == kAscendDevice)) return;
  1343. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1344. const auto &apply_kernels = graph_ptr_->execution_order();
  1345. auto root_graph_id = graph_ptr_->root_graph_id();
  1346. // for kernels, execution order starts from 1
  1347. int exec_order = 1;
  1348. for (const auto &node : apply_kernels) {
  1349. MS_EXCEPTION_IF_NULL(node);
  1350. std::string kernel_name = GetKernelNodeName(node);
  1351. auto output_size = AnfAlgo::GetOutputTensorNum(node);
  1352. if (partial_memory_) {
  1353. if (!debug_services_->IsWatchPoint(kernel_name, node)) {
  1354. continue;
  1355. }
  1356. }
  1357. for (size_t j = 0; j < output_size; ++j) {
  1358. if (!AnfAlgo::OutputAddrExist(node, j)) {
  1359. MS_LOG(INFO) << "Cannot find output addr for slot " << j << " for " << kernel_name;
  1360. continue;
  1361. }
  1362. auto addr = AnfAlgo::GetOutputAddr(node, j);
  1363. MS_EXCEPTION_IF_NULL(addr);
  1364. auto type = AnfAlgo::GetOutputInferDataType(node, j);
  1365. if (!IsTypeDebuggerSupported(type)) {
  1366. continue;
  1367. }
  1368. auto format = kOpFormat_DEFAULT;
  1369. string tensor_name = kernel_name + ':' + std::to_string(j);
  1370. ShapeVector int_shapes = trans::GetRuntimePaddingShape(node, j);
  1371. auto ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, j, false, root_graph_id);
  1372. if (!ret) {
  1373. MS_LOG(ERROR) << "LoadMemToHost:"
  1374. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1375. }
  1376. }
  1377. exec_order = exec_order + 1;
  1378. }
  1379. }
  1380. void Debugger::UpdateStepNum(const session::KernelGraph *graph) {
  1381. MS_EXCEPTION_IF_NULL(graph);
  1382. MS_EXCEPTION_IF_NULL(debugger_);
  1383. // update step number if we are processing the first graph (to support multigraph)
  1384. if (device_target_ == kGPUDevice && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration()) &&
  1385. (graph->graph_id() == debugger_->GetFirstRunGraphId())) {
  1386. // access lock for public method
  1387. std::lock_guard<std::mutex> a_lock(access_lock_);
  1388. ++num_step_;
  1389. }
  1390. }
  1391. void Debugger::UpdateStepNumGPU() {
  1392. // UpdateStepNum with DebugActor::DebugOnStepEnd
  1393. if (device_target_ == kGPUDevice && (debugger_enabled_ || DumpDataEnabledIteration())) {
  1394. // access lock for public method
  1395. std::lock_guard<std::mutex> a_lock(access_lock_);
  1396. ++num_step_;
  1397. MS_LOG(DEBUG) << "Update step for GPU, current step: " << num_step_;
  1398. }
  1399. }
  1400. void Debugger::ClearCurrentData() {
  1401. if ((device_target_ == kGPUDevice) && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration())) {
  1402. if (debug_services_) {
  1403. debug_services_->EmptyCurrentTensor();
  1404. } else {
  1405. MS_LOG(ERROR) << "debug_services_ is nullptr";
  1406. }
  1407. }
  1408. }
  1409. bool Debugger::TensorExistsInCurrent(const std::string &tensor_name) {
  1410. return debug_services_->TensorExistsInCurrent(tensor_name);
  1411. }
  1412. #ifdef ENABLE_D
  1413. std::shared_ptr<DumpDataBuilder> Debugger::LoadDumpDataBuilder(const std::string &node_name) {
  1414. auto iter = dump_data_construct_map_.find(node_name);
  1415. if (iter == dump_data_construct_map_.end()) {
  1416. dump_data_construct_map_[node_name] = std::make_shared<DumpDataBuilder>();
  1417. }
  1418. return dump_data_construct_map_[node_name];
  1419. }
  1420. void Debugger::ClearDumpDataBuilder(const std::string &node_name) { dump_data_construct_map_.erase(node_name); }
  1421. #endif
  1422. } // namespace mindspore