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 67 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
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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::AsyncFilePool file_list;
  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. file_list, &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. bool ret = device_addr->LoadMemToHost(tensor_name, 0, format, int_shapes, type, 0, true, root_graph_id);
  1461. if (!ret) {
  1462. MS_LOG(ERROR) << "LoadMemToHost:"
  1463. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1464. }
  1465. }
  1466. /*
  1467. * Feature group: Dump, Online debugger.
  1468. * Target device group: Ascend, GPU.
  1469. * Runtime category: Old runtime, MindRT.
  1470. * Description: Load all the parameters and value nodes for the last loaded graph.
  1471. */
  1472. void Debugger::LoadParametersAndConst() {
  1473. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  1474. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1475. // load parameters
  1476. MS_LOG(INFO) << "Start to load Parameters for graph " << graph_ptr_->graph_id() << ".";
  1477. auto root_graph_id = graph_ptr_->root_graph_id();
  1478. const auto &parameters = graph_ptr_->inputs();
  1479. for (auto &item : parameters) {
  1480. LoadSingleAnfnode(item, PARAMETER_OUTPUT_INDEX, root_graph_id);
  1481. }
  1482. // load value nodes
  1483. // get all constant values from the graph
  1484. MS_LOG(INFO) << "Start to load value nodes for graph " << graph_ptr_->graph_id() << ".";
  1485. const auto value_nodes = graph_ptr_->graph_value_nodes();
  1486. for (auto &item : value_nodes) {
  1487. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX, root_graph_id);
  1488. }
  1489. }
  1490. /*
  1491. * Feature group: Dump, Online debugger.
  1492. * Target device group: Ascend, GPU.
  1493. * Runtime category: Old runtime, MindRT.
  1494. * Description: Load all the parameters and value nodes for the given graph.
  1495. */
  1496. void Debugger::LoadParametersAndConst(const KernelGraphPtr &graph) {
  1497. if (!(debugger_enabled_ || CheckDebuggerDumpEnabled())) return;
  1498. MS_EXCEPTION_IF_NULL(graph);
  1499. // load parameters
  1500. MS_LOG(INFO) << "Start to load Parameters for graph " << graph->graph_id() << ".";
  1501. auto root_graph_id = graph->root_graph_id();
  1502. const auto &parameters = graph->inputs();
  1503. for (auto &item : parameters) {
  1504. LoadSingleAnfnode(item, PARAMETER_OUTPUT_INDEX, root_graph_id);
  1505. }
  1506. // load value nodes
  1507. // get all constant values from the graph
  1508. MS_LOG(INFO) << "Start to load value nodes for graph " << graph->graph_id() << ".";
  1509. const auto value_nodes = graph->graph_value_nodes();
  1510. for (auto &item : value_nodes) {
  1511. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX, root_graph_id);
  1512. }
  1513. }
  1514. /*
  1515. * Feature group: Dump.
  1516. * Target device group: GPU.
  1517. * Runtime category: MindRT.
  1518. * Description: This function is for loading parameters' data from device to host into tensor_list_map_ for GPU dump.
  1519. * Ascend does not use tensor_map_list_ for dump so it is not needed for ascend dump.
  1520. */
  1521. void Debugger::LoadParametersAllGraphs() {
  1522. if (!(device_target_ == kGPUDevice && CheckDebuggerDumpEnabled())) {
  1523. return;
  1524. }
  1525. for (auto &node : parameters_mindRT_) {
  1526. LoadSingleParameterMindRT(node);
  1527. }
  1528. }
  1529. /*
  1530. * Feature group: Dump.
  1531. * Target device group: GPU.
  1532. * Runtime category: MindRT.
  1533. * Description: This function is for loading constant data from device to host into tensor_list_map_ for GPU dump.
  1534. * Ascend does not use tensor_map_list_ for dump so it is not needed for ascend dump.
  1535. */
  1536. void Debugger::LoadConstsForGraph(const KernelGraphPtr &graph) {
  1537. if (!(device_target_ == kGPUDevice && CheckDebuggerDumpEnabled())) {
  1538. return;
  1539. }
  1540. // load value nodes
  1541. // get all constant values from the graph
  1542. MS_LOG(INFO) << "Start to load value nodes for graph " << graph->graph_id() << ".";
  1543. auto root_graph_id = graph->root_graph_id();
  1544. const auto value_nodes = graph->graph_value_nodes();
  1545. for (auto &item : value_nodes) {
  1546. LoadSingleAnfnode(item, VALUE_NODE_OUTPUT_INDEX, root_graph_id);
  1547. }
  1548. }
  1549. /*
  1550. * Feature group: Online debugger.
  1551. * Target device group: Ascend.
  1552. * Runtime category: Old runtime, MindRT.
  1553. * Description: Load all the kernels for the last loaded graph.
  1554. */
  1555. void Debugger::LoadGraphOutputs() {
  1556. if (!(debugger_enabled() && device_target_ == kAscendDevice)) return;
  1557. MS_EXCEPTION_IF_NULL(graph_ptr_);
  1558. const auto &apply_kernels = graph_ptr_->execution_order();
  1559. auto root_graph_id = graph_ptr_->root_graph_id();
  1560. // for kernels, execution order starts from 1
  1561. int exec_order = 1;
  1562. for (const auto &node : apply_kernels) {
  1563. MS_EXCEPTION_IF_NULL(node);
  1564. std::string kernel_name = GetKernelNodeName(node);
  1565. auto output_size = common::AnfAlgo::GetOutputTensorNum(node);
  1566. if (partial_memory_) {
  1567. if (!debug_services_->IsWatchPoint(kernel_name, node)) {
  1568. continue;
  1569. }
  1570. }
  1571. for (size_t j = 0; j < output_size; ++j) {
  1572. if (!AnfAlgo::OutputAddrExist(node, j)) {
  1573. MS_LOG(INFO) << "Cannot find output addr for slot " << j << " for " << kernel_name;
  1574. continue;
  1575. }
  1576. auto addr = AnfAlgo::GetOutputAddr(node, j);
  1577. MS_EXCEPTION_IF_NULL(addr);
  1578. auto type = common::AnfAlgo::GetOutputInferDataType(node, j);
  1579. if (!IsTypeDebuggerSupported(type)) {
  1580. continue;
  1581. }
  1582. auto format = kOpFormat_DEFAULT;
  1583. string tensor_name = kernel_name + ':' + std::to_string(j);
  1584. ShapeVector int_shapes = trans::GetRuntimePaddingShape(node, j);
  1585. auto ret = addr->LoadMemToHost(tensor_name, exec_order, format, int_shapes, type, j, false, root_graph_id);
  1586. if (!ret) {
  1587. MS_LOG(ERROR) << "LoadMemToHost:"
  1588. << ", tensor_name:" << tensor_name << ", host_format:" << format << ".!";
  1589. }
  1590. }
  1591. exec_order = exec_order + 1;
  1592. }
  1593. }
  1594. /*
  1595. * Feature group: Online debugger.
  1596. * Target device group: GPU.
  1597. * Runtime category: Old runtime.
  1598. * Description: Update step number if we are processing the first graph (to support multigraph).
  1599. */
  1600. void Debugger::UpdateStepNum(const session::KernelGraph *graph) {
  1601. MS_EXCEPTION_IF_NULL(graph);
  1602. MS_EXCEPTION_IF_NULL(debugger_);
  1603. if (device_target_ == kGPUDevice && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration()) &&
  1604. (graph->graph_id() == debugger_->GetFirstRunGraphId())) {
  1605. // access lock for public method
  1606. std::lock_guard<std::mutex> a_lock(access_lock_);
  1607. ++num_step_;
  1608. }
  1609. }
  1610. /*
  1611. * Feature group: Online debugger.
  1612. * Target device group: GPU.
  1613. * Runtime category: MindRT.
  1614. * Description: Update step number when DebugActor::DebugOnStepEnd is called at the end of each step.
  1615. */
  1616. void Debugger::UpdateStepNumGPU() {
  1617. auto &dump_json_parser = DumpJsonParser::GetInstance();
  1618. if (device_target_ == kGPUDevice && (debugger_enabled_ || dump_json_parser.DumpEnabledForIter())) {
  1619. // access lock for public method
  1620. std::lock_guard<std::mutex> a_lock(access_lock_);
  1621. ++num_step_;
  1622. MS_LOG(DEBUG) << "Update step for GPU, current step: " << num_step_;
  1623. }
  1624. }
  1625. void Debugger::ClearCurrentData() {
  1626. if ((device_target_ == kGPUDevice) && (debugger_enabled_ || device::KernelRuntime::DumpDataEnabledIteration())) {
  1627. if (debug_services_) {
  1628. debug_services_->EmptyCurrentTensor();
  1629. } else {
  1630. MS_LOG(ERROR) << "debug_services_ is nullptr";
  1631. }
  1632. }
  1633. }
  1634. bool Debugger::TensorExistsInCurrent(const std::string &tensor_name) {
  1635. if (debug_services_ != nullptr) {
  1636. return debug_services_->TensorExistsInCurrent(tensor_name);
  1637. }
  1638. return false;
  1639. }
  1640. #ifdef ENABLE_D
  1641. /*
  1642. * Feature group: Dump.
  1643. * Target device group: Ascend.
  1644. * Runtime category: Old runtime, MindRT.
  1645. * Description: Load DumpDataBuilder object from dump_data_construct_map_ for tracking data chunks of node_name. It's
  1646. * for Ascend a + m dump. If not found, create a new one for it and add to dump_data_construct_map_.
  1647. */
  1648. std::shared_ptr<DumpDataBuilder> Debugger::LoadDumpDataBuilder(const std::string &node_name) {
  1649. auto iter = dump_data_construct_map_.find(node_name);
  1650. if (iter == dump_data_construct_map_.end()) {
  1651. dump_data_construct_map_[node_name] = std::make_shared<DumpDataBuilder>();
  1652. }
  1653. return dump_data_construct_map_[node_name];
  1654. }
  1655. void Debugger::ClearDumpDataBuilder(const std::string &node_name) { (void)dump_data_construct_map_.erase(node_name); }
  1656. #endif
  1657. } // namespace mindspore