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