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