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