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

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