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