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