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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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.4.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. 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. MS_LOG(INFO) << "Release Debugger resource.";
  256. }
  257. void Debugger::PreExecuteGraphDebugger(const std::vector<KernelGraphPtr> &graphs) {
  258. // Only GPU is supported for MindRTBackend
  259. if (device_target_ != kGPUDevice) {
  260. return;
  261. }
  262. for (size_t graph_index = 0; graph_index < graphs.size(); ++graph_index) {
  263. const auto &graph = graphs[graph_index];
  264. if (debugger_) {
  265. debugger_->PreExecute(graph);
  266. }
  267. DumpSetup(graph);
  268. }
  269. }
  270. void Debugger::PreExecute(const KernelGraphPtr &graph_ptr) {
  271. // access lock for public method
  272. std::lock_guard<std::mutex> a_lock(access_lock_);
  273. CheckDatasetSinkMode();
  274. auto graph_id = graph_ptr->graph_id();
  275. // collect rungrap_ids to update step number in multigraph case
  276. if (!rungraph_id_list_.size()) {
  277. rungraph_id_list_.push_back(graph_id);
  278. } else {
  279. if (std::find(rungraph_id_list_.begin(), rungraph_id_list_.end(), graph_id) == rungraph_id_list_.end()) {
  280. rungraph_id_list_.push_back(graph_id);
  281. }
  282. }
  283. // multiple graphs
  284. if (graph_proto_list_.size() > 1) {
  285. // there are more than one graphs are not dataset_graph
  286. if (not_dataset_graph_sum_ > 0) {
  287. // only try to enable debugger if they are not all dataset graphs
  288. if (!debugger_enabled_) {
  289. EnableDebugger();
  290. }
  291. if (debugger_enabled_) {
  292. // only send compiled graphs once at the initial step.
  293. auto dbg_graph_ptr = graph_ptr_;
  294. // use current graph ptr to load parameters
  295. graph_ptr_ = graph_ptr;
  296. LoadParametersAndConst();
  297. // revert graph ptr to original value
  298. graph_ptr_ = dbg_graph_ptr;
  299. SendMultiGraphsAndSuspend(graph_proto_list_);
  300. graph_proto_list_.clear();
  301. }
  302. }
  303. } else if (graph_proto_list_.size() == 1) {
  304. // single graph, and not the initial step
  305. if (device_target_ == kGPUDevice && num_step_ != 0) {
  306. if (debugger_enabled_ && !(run_level_ == "node" && suspended_at_last_kernel_)) {
  307. CommandLoop();
  308. }
  309. debug_services_->ResetLoadedTensors();
  310. }
  311. // In single graph case, reset graph_ptr_ to be nullptr for the initial step
  312. if (num_step_ == 0) {
  313. graph_ptr_ = nullptr;
  314. CheckGraphPtr(graph_ptr);
  315. }
  316. } else if (debugger_enabled_ && graph_id == rungraph_id_list_.front() && device_target_ == kGPUDevice) {
  317. // Multiple graph, and not the initial step,
  318. // stop only when receive the first sub run graph for each step
  319. // if we have stopped for the last kernel before, no need to stop again
  320. if (pipeline::GraphExecutorPy::GetDebugTerminate()) {
  321. return;
  322. }
  323. if (!(run_level_ == "node" && suspended_at_last_kernel_)) {
  324. CommandLoop();
  325. }
  326. debug_services_->ResetLoadedTensors();
  327. }
  328. // resets for the new graph
  329. suspended_at_last_kernel_ = false;
  330. }
  331. bool Debugger::DumpDataEnabledIteration() const {
  332. auto &dump_json_parser = DumpJsonParser::GetInstance();
  333. if (!dump_json_parser.e2e_dump_enabled()) {
  334. return false;
  335. }
  336. auto cur_iter = dump_json_parser.cur_dump_iter();
  337. if (dump_json_parser.IsDumpIter(cur_iter)) {
  338. return true;
  339. }
  340. return false;
  341. }
  342. uint32_t Debugger::GetRankID() {
  343. auto ms_context = MsContext::GetInstance();
  344. MS_EXCEPTION_IF_NULL(ms_context);
  345. std::string device_target = ms_context->get_param<std::string>(MS_CTX_DEVICE_TARGET);
  346. uint32_t device_id = ms_context->get_param<uint32_t>(MS_CTX_DEVICE_ID);
  347. const auto &device_context =
  348. device::DeviceContextManager::GetInstance().GetOrCreateDeviceContext({device_target, device_id});
  349. uint32_t rank_id = device_context->GetRankID();
  350. return rank_id;
  351. }
  352. void Debugger::Dump(const KernelGraphPtr &kernel_graph) const {
  353. uint32_t rank_id = GetRankID();
  354. if (debugger_->DebuggerBackendEnabled()) {
  355. MS_EXCEPTION_IF_NULL(kernel_graph);
  356. (void)E2eDump::DumpParametersAndConstData(kernel_graph.get(), rank_id, debugger_.get());
  357. } else {
  358. DumpJsonParser::GetInstance().UpdateDumpIter();
  359. }
  360. }
  361. void Debugger::DumpSingleNode(const CNodePtr &node, uint32_t graph_id) {
  362. if (debugger_->DebuggerBackendEnabled()) {
  363. uint32_t rank_id = GetRankID();
  364. (void)E2eDump::DumpSingleNodeData(node, graph_id, rank_id, debugger_.get());
  365. }
  366. }
  367. void Debugger::DumpSetup(const KernelGraphPtr &kernel_graph) const {
  368. MS_LOG(INFO) << "Start!";
  369. uint32_t rank_id = GetRankID();
  370. MS_EXCEPTION_IF_NULL(kernel_graph);
  371. E2eDump::DumpSetup(kernel_graph.get(), rank_id);
  372. MS_LOG(INFO) << "Finish!";
  373. }
  374. void Debugger::DumpInGraphCompiler(const KernelGraphPtr &kernel_graph) {
  375. // This function will be called for new GPU runtime using MindRTBackend
  376. auto &json_parser = DumpJsonParser::GetInstance();
  377. if (json_parser.e2e_dump_enabled()) {
  378. uint32_t rank_id = GetRankID();
  379. kernel_graph->set_root_graph_id(kernel_graph->graph_id());
  380. std::string final_graph = "trace_code_graph_" + std::to_string(kernel_graph->graph_id());
  381. std::string root_dir = json_parser.path() + "/rank_" + std::to_string(rank_id);
  382. std::string target_dir = root_dir + "/graphs";
  383. std::string ir_file_path = target_dir + "/" + "ms_output_" + final_graph + ".ir";
  384. DumpIRProtoWithSrcInfo(kernel_graph, final_graph, target_dir, kDebugWholeStack);
  385. DumpIR("trace_code_graph", kernel_graph, true, kWholeStack, ir_file_path);
  386. DumpGraphExeOrder("ms_execution_order_graph_" + std::to_string(kernel_graph->graph_id()) + ".csv", root_dir,
  387. kernel_graph->execution_order());
  388. }
  389. }
  390. void Debugger::PostExecuteGraphDebugger() {
  391. // On CPU, update dump iteration, Parameters and consts are not dumped here
  392. if (device_target_ == kCPUDevice) {
  393. DumpJsonParser::GetInstance().UpdateDumpIter();
  394. return;
  395. }
  396. // Only GPU is supported for MindRTBackend
  397. if (device_target_ != kGPUDevice) {
  398. return;
  399. }
  400. // LoadParametersAndConst for all the graphs
  401. for (auto graph : graph_ptr_list_) {
  402. debugger_->LoadParametersAndConst(graph);
  403. }
  404. // debug used for dump
  405. if (debugger_ && debugger_->CheckDebuggerDumpEnabled()) {
  406. // Dump Parameters and consts
  407. for (auto graph : graph_ptr_list_) {
  408. debugger_->Dump(graph);
  409. if (!debugger_->debugger_enabled()) {
  410. debugger_->ClearCurrentData();
  411. }
  412. }
  413. }
  414. if (debugger_) {
  415. debugger_->PostExecute();
  416. }
  417. }
  418. void Debugger::PostExecute() {
  419. // access lock for public method
  420. std::lock_guard<std::mutex> a_lock(access_lock_);
  421. if (pipeline::GraphExecutorPy::GetDebugTerminate()) {
  422. return;
  423. }
  424. if (debugger_->DebuggerBackendEnabled()) {
  425. // analyze tensor data and send the watchpoints been hit
  426. if (debugger_enabled_ && !is_dataset_graph_) {
  427. if (device_target_ != kGPUDevice) {
  428. num_step_++;
  429. }
  430. SendWatchpoints(CheckWatchpoints());
  431. // no need to suspend at each graph for GPU, suspension happens in preExecute
  432. if (device_target_ != kGPUDevice) {
  433. CommandLoop();
  434. }
  435. }
  436. // Only keep parameters in the current map
  437. // GPU ResetLoadedTensors happens in preExecute
  438. if (device_target_ != kGPUDevice) {
  439. debug_services_->ResetLoadedTensors();
  440. }
  441. }
  442. }
  443. bool Debugger::ReadNodeDataRequired(const CNodePtr &kernel) const {
  444. if (debugger_enabled_ && !is_dataset_graph_) {
  445. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  446. // if node has a watchpoint on it, is next_to node, or continue_to node then read the kernel tensor data
  447. if (is_watchpoint || (run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_))) {
  448. return true;
  449. }
  450. }
  451. return false;
  452. }
  453. void Debugger::PostExecuteNode(const CNodePtr &kernel, bool last_kernel) {
  454. // access lock for public method
  455. std::lock_guard<std::mutex> a_lock(access_lock_);
  456. if (pipeline::GraphExecutorPy::GetDebugTerminate()) {
  457. return;
  458. }
  459. if (debugger_enabled_ && !is_dataset_graph_) {
  460. auto is_watchpoint = debug_services_->IsWatchPoint(cur_name_, kernel);
  461. // if kernel is watchpoint,and get hit. suspend.
  462. bool hit_empty_flag = true;
  463. if (is_watchpoint) {
  464. auto hits = CheckWatchpoints(cur_name_, kernel);
  465. if (!hits.empty()) {
  466. SendWatchpoints(hits);
  467. CommandLoop();
  468. hit_empty_flag = false;
  469. }
  470. }
  471. if (hit_empty_flag && run_level_ == "node" && (node_name_ == "" || node_name_ == cur_name_)) {
  472. // if kernel is not watchpoint and is next_to or continue_to node, suspend
  473. // sets a bool to be checked in preExecute to avoid double stopping at last kernel in the last graph
  474. if (last_kernel) {
  475. suspended_at_last_kernel_ = true;
  476. }
  477. CommandLoop();
  478. }
  479. return;
  480. }
  481. }
  482. void Debugger::PostDebugOp() {
  483. // access lock for public method
  484. std::lock_guard<std::mutex> a_lock(access_lock_);
  485. // suspend if debugger is enabled
  486. if (debugger_enabled_ && !is_dataset_graph_) {
  487. MS_LOG(INFO) << "Debugger suspend at debug_op";
  488. CommandLoop();
  489. }
  490. }
  491. void Debugger::LoadGraphs(const KernelGraphPtr &graph_ptr) {
  492. if (graph_ptr_ != graph_ptr) {
  493. MS_LOG(INFO) << "LoadGraphs Debugger got new graph: " << graph_ptr->graph_id();
  494. // save new graph_ptr
  495. graph_ptr_ = graph_ptr;
  496. CheckDatasetGraph();
  497. if (!is_dataset_graph_) {
  498. // get proto for new graph_ptr
  499. auto graph_proto = GetGraphProto(graph_ptr);
  500. // add new graph proto to graph_proto_list_
  501. graph_proto_list_.push_back(graph_proto);
  502. graph_ptr_list_.push_back(graph_ptr);
  503. not_dataset_graph_sum_++;
  504. }
  505. // reset is_dataset_graph to be false
  506. is_dataset_graph_ = false;
  507. }
  508. }
  509. // In single graph cases, check single graph ptr
  510. void Debugger::CheckGraphPtr(const KernelGraphPtr &graph_ptr) {
  511. if (graph_ptr_ != graph_ptr) {
  512. MS_LOG(INFO) << "CheckGraphPtr Debugger got new graph: " << graph_ptr->graph_id();
  513. // save new graph_ptr
  514. graph_ptr_ = graph_ptr;
  515. if (!is_dataset_graph_) {
  516. // only try to enable debugger if it is not a dataset graph
  517. EnableDebugger();
  518. if (debugger_enabled_) {
  519. LoadParametersAndConst();
  520. // get graph proto and send to Mindinsight
  521. auto graph_proto = graph_proto_list_.front();
  522. SendGraphAndSuspend(graph_proto);
  523. }
  524. }
  525. }
  526. }
  527. void Debugger::CheckDatasetGraph() {
  528. // print parameter node names
  529. const auto &params = graph_ptr_->inputs();
  530. for (const auto &param : params) {
  531. MS_LOG(INFO) << "param: " << GetKernelNodeName(param);
  532. }
  533. // check if there is GetNext or InitDataSetQueue node
  534. const auto &nodes = graph_ptr_->execution_order();
  535. for (const auto &node : nodes) {
  536. auto node_name = AnfAlgo::GetCNodeName(node);
  537. MS_LOG(INFO) << "node: " << GetKernelNodeName(node);
  538. if (node_name == "GetNext" || node_name == "InitDataSetQueue") {
  539. MS_LOG(INFO) << "Not enabling debugger for graph " << graph_ptr_->graph_id() << ": found dataset graph node "
  540. << node_name;
  541. is_dataset_graph_ = true;
  542. return;
  543. }
  544. }
  545. is_dataset_graph_ = false;
  546. }
  547. GraphProto Debugger::GetGraphProto(const KernelGraphPtr &graph_ptr) const {
  548. // convert kernel graph to debugger modelproto
  549. ModelProto model = GetDebuggerFuncGraphProto(graph_ptr);
  550. return model.graph();
  551. }
  552. void Debugger::SendHeartbeat(int32_t period) {
  553. int num_heartbeat_fail = 0;
  554. const int max_num_heartbeat_fail = 5;
  555. const int retry_milliseconds = 500;
  556. Heartbeat heartbeat;
  557. heartbeat.set_message("Debugger is alive");
  558. heartbeat.set_period(heartbeat_period_second);
  559. SetEnableHeartbeat(CheckDebuggerEnabled());
  560. while (enable_heartbeat_) {
  561. EventReply reply = grpc_client_->SendHeartbeat(heartbeat);
  562. if (reply.status() != reply.OK) {
  563. MS_LOG(ERROR) << "Error: SendHeartbeat failed";
  564. num_heartbeat_fail++;
  565. if (num_heartbeat_fail >= max_num_heartbeat_fail) {
  566. MS_LOG(ERROR) << "Maximum number of failure for SendHeartbeat reached : exiting training session.";
  567. SetEnableHeartbeat(false);
  568. break;
  569. } else {
  570. MS_LOG(ERROR) << "Number of consecutive SendHeartbeat fail:" << num_heartbeat_fail;
  571. std::this_thread::sleep_for(std::chrono::milliseconds(retry_milliseconds));
  572. }
  573. } else {
  574. std::this_thread::sleep_for(std::chrono::milliseconds(period * 1000));
  575. }
  576. }
  577. }
  578. void Debugger::SendGraphAndSuspend(const GraphProto &graph_proto) {
  579. if (SendMetadata(true)) {
  580. // send graph to Mindinsight server
  581. EventReply reply = grpc_client_->SendGraph(graph_proto);
  582. if (reply.status() != reply.OK) {
  583. MS_LOG(ERROR) << "Error: SendGraph failed";
  584. }
  585. // enter command loop, wait and process commands
  586. CommandLoop();
  587. }
  588. }
  589. bool Debugger::SendMetadata(bool version_check) {
  590. // prepare metadata
  591. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  592. Metadata metadata;
  593. metadata.set_device_name(device_name);
  594. metadata.set_cur_step(num_step_);
  595. metadata.set_backend(device_target_);
  596. metadata.set_cur_node(cur_name_);
  597. metadata.set_training_done(training_done_);
  598. metadata.set_ms_version(version_);
  599. MS_LOG(INFO) << "Is training done?" << training_done_;
  600. // set graph munber to not_dataset_graph_sum_
  601. metadata.set_graph_num(not_dataset_graph_sum_);
  602. EventReply reply_metadata = grpc_client_->SendMetadata(metadata);
  603. bool ret = false;
  604. if (reply_metadata.status() == reply_metadata.OK) {
  605. if (version_check) {
  606. // get type of the command in meta data reply, it should be version matched
  607. DebuggerCommand cmd = GetCommand(reply_metadata);
  608. if (cmd != DebuggerCommand::kVersionMatchedCMD) {
  609. MS_LOG(ERROR) << "MindInsight version is too old, Mindspore version is " << version_;
  610. Exit();
  611. } else {
  612. if (GetMiVersionMatched(reply_metadata)) {
  613. MS_LOG(INFO) << "MindSpore version is " << version_ << " matches MindInsight version.";
  614. ret = true;
  615. } else {
  616. MS_LOG(ERROR) << "MindSpore version " << version_ << ", did not match MindInsight version.";
  617. CommandLoop();
  618. }
  619. }
  620. } else {
  621. // version check is done before so we can just return true here
  622. ret = true;
  623. }
  624. } else {
  625. MS_LOG(ERROR) << "Error: SendMetadata failed";
  626. }
  627. return ret;
  628. }
  629. void Debugger::SendMultiGraphsAndSuspend(const std::list<GraphProto> &graph_proto_list) {
  630. if (!SendMetadata(true)) {
  631. return;
  632. }
  633. // send multiple graphs to mindinght server
  634. // split graph into chunks if one graph is larger than chunk size
  635. std::list<Chunk> chunked_graph_proto_list;
  636. Chunk chunk;
  637. for (auto graph : graph_proto_list) {
  638. std::string str = graph.SerializeAsString();
  639. auto graph_size = graph.ByteSize();
  640. if (graph_size > g_chunk_size) {
  641. auto sub_graph_str = grpc_client_->ChunkString(str, graph_size);
  642. for (unsigned int i = 0; i < sub_graph_str.size(); i++) {
  643. chunk.set_buffer(sub_graph_str[i]);
  644. if (i < sub_graph_str.size() - 1) {
  645. chunk.set_finished(false);
  646. } else {
  647. chunk.set_finished(true);
  648. }
  649. chunked_graph_proto_list.push_back(chunk);
  650. }
  651. } else {
  652. chunk.set_buffer(str);
  653. chunk.set_finished(true);
  654. chunked_graph_proto_list.push_back(chunk);
  655. }
  656. }
  657. EventReply reply = grpc_client_->SendMultiGraphs(chunked_graph_proto_list);
  658. if (reply.status() != reply.OK) {
  659. MS_LOG(ERROR) << "Error: SendGraph failed";
  660. }
  661. // enter command loop, wait and process commands
  662. CommandLoop();
  663. }
  664. void Debugger::CommandLoop() {
  665. // prepare metadata
  666. std::string device_name = std::to_string(device_id_) + ":" + std::to_string(graph_ptr_->graph_id());
  667. Metadata metadata;
  668. metadata.set_device_name(device_name);
  669. metadata.set_cur_step(num_step_);
  670. metadata.set_backend(device_target_);
  671. metadata.set_cur_node(cur_name_);
  672. metadata.set_training_done(training_done_);
  673. // loop exit flag
  674. bool run = false;
  675. int num_wait_fail = 0;
  676. const int max_num_wait_fail = 5;
  677. while (!run) {
  678. // wait for command
  679. EventReply reply = grpc_client_->WaitForCommand(metadata);
  680. if (reply.status() != reply.OK) {
  681. MS_LOG(ERROR) << "Error: WaitForCommand failed";
  682. num_wait_fail++;
  683. if (num_wait_fail > max_num_wait_fail) {
  684. MS_LOG(ERROR) << "Maximum number of WaitForCommand retry reached: exiting training session.";
  685. MS_LOG(ERROR) << "Failed to connect to MindInsight debugger server. Please check the config "
  686. "of debugger host and port.";
  687. Exit();
  688. run = true;
  689. } else {
  690. MS_LOG(ERROR) << "Number of consecutive WaitForCommand fail:" << num_wait_fail << "; Retry after "
  691. << num_wait_fail << "s";
  692. std::this_thread::sleep_for(std::chrono::seconds(num_wait_fail));
  693. }
  694. continue;
  695. }
  696. // get type of the command in reply
  697. DebuggerCommand cmd = GetCommand(reply);
  698. if (cmd == DebuggerCommand::kUnknownCMD) {
  699. MS_LOG(DEBUG) << "Debug: debugger received unknown command";
  700. continue;
  701. }
  702. MS_LOG(INFO) << "received command: ";
  703. switch (cmd) {
  704. case DebuggerCommand::kUnknownCMD:
  705. MS_LOG(INFO) << "UnknownCMD";
  706. break;
  707. case DebuggerCommand::kExitCMD:
  708. MS_LOG(INFO) << "ExitCMD";
  709. Exit();
  710. // Used for debugger termination
  711. run = true;
  712. break;
  713. case DebuggerCommand::kRunCMD:
  714. ProcessRunCMD(reply);
  715. if (GetRunLevel(reply) != "recheck") {
  716. // exit loop
  717. run = true;
  718. }
  719. break;
  720. case DebuggerCommand::kSetCMD:
  721. ProcessKSetCMD(reply);
  722. break;
  723. case DebuggerCommand::kViewCMD:
  724. ProcessKViewCMD(reply);
  725. break;
  726. case DebuggerCommand::kVersionMatchedCMD:
  727. MS_LOG(ERROR) << "Received unexpected Version Matched CMD from Mindinsight.";
  728. Exit();
  729. break;
  730. default:
  731. MS_LOG(ERROR) << "Received unknown CMD from Mindinsight";
  732. Exit();
  733. break;
  734. }
  735. }
  736. }
  737. void Debugger::ProcessRunCMD(const EventReply &reply) {
  738. MS_LOG(INFO) << "RunCMD";
  739. if (GetRunLevel(reply) == "recheck") {
  740. MS_LOG(INFO) << "rechecking all watchpoints";
  741. SendWatchpoints(CheckWatchpoints("", nullptr, true));
  742. } else {
  743. // no longer the initial suspension.
  744. initial_suspend_ = false;
  745. // print run cmd content
  746. // get run_level and node_name
  747. run_level_ = GetRunLevel(reply);
  748. node_name_ = GetNodeName(reply);
  749. MS_LOG(INFO) << "run_level: " << run_level_;
  750. MS_LOG(INFO) << "node_name_: " << node_name_;
  751. }
  752. }
  753. void Debugger::ProcessKSetCMD(const EventReply &reply) {
  754. MS_LOG(INFO) << "SetCMD";
  755. MS_LOG(INFO) << "id: " << GetWatchpointID(reply);
  756. MS_LOG(INFO) << "delete: " << GetWatchpointDelete(reply);
  757. if (GetWatchpointDelete(reply)) {
  758. MS_LOG(INFO) << "Deleting watchpoint";
  759. RemoveWatchpoint(GetWatchpointID(reply));
  760. } else {
  761. MS_LOG(INFO) << "Setting watchpoint";
  762. MS_LOG(INFO) << "condition: " << GetWatchcondition(reply).condition();
  763. ProtoVector<WatchNode> recieved_nodes = GetWatchnodes(reply);
  764. for (const auto &node : recieved_nodes) {
  765. MS_LOG(INFO) << "node name: " << node.node_name();
  766. MS_LOG(INFO) << "node type: " << node.node_type();
  767. }
  768. ProtoVector<WatchCondition_Parameter> parameters = GetParameters(reply);
  769. for (const auto &parameter : parameters) {
  770. MS_LOG(INFO) << "parameter name: " << parameter.name();
  771. MS_LOG(INFO) << "parameter is disabled: " << parameter.disabled();
  772. MS_LOG(INFO) << "parameter value: " << parameter.value();
  773. }
  774. SetWatchpoint(GetWatchnodes(reply), GetWatchcondition(reply), GetWatchpointID(reply), GetParameters(reply));
  775. }
  776. }
  777. void Debugger::ProcessKViewCMD(const EventReply &reply) {
  778. MS_LOG(INFO) << "ViewCMD";
  779. // print view cmd content
  780. ProtoVector<TensorProto> received_tensors = GetTensors(reply);
  781. for (auto received_tensor : received_tensors) {
  782. MS_LOG(INFO) << "tensor node name: " << received_tensor.node_name();
  783. MS_LOG(INFO) << "tensor slot: " << received_tensor.slot();
  784. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << received_tensor.finished() << std::noboolalpha;
  785. MS_LOG(INFO) << "tensor iter: " << received_tensor.iter();
  786. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << received_tensor.truncate() << std::noboolalpha;
  787. }
  788. switch (reply.view_cmd().level()) {
  789. case debugger::ViewCMD_Level::ViewCMD_Level_base:
  790. MS_LOG(INFO) << "Tensor base request.";
  791. ViewBaseLevel(reply);
  792. break;
  793. case debugger::ViewCMD_Level::ViewCMD_Level_statistics:
  794. MS_LOG(INFO) << "Tensor statistics request.";
  795. ViewStatLevel(reply);
  796. break;
  797. case debugger::ViewCMD_Level::ViewCMD_Level_value:
  798. MS_LOG(INFO) << "Tensor value request.";
  799. ViewValueLevel(reply);
  800. break;
  801. default:
  802. MS_LOG(DEBUG) << "Debug: Unknown tensor info level";
  803. break;
  804. }
  805. }
  806. void Debugger::ViewValueLevel(const EventReply &reply) {
  807. MS_LOG(INFO) << "Sending tensors";
  808. std::list<TensorProto> tensors = LoadTensors(GetTensors(reply));
  809. // print view cmd reply
  810. for (auto tensor : tensors) {
  811. MS_LOG(INFO) << "tensor node name: " << tensor.node_name();
  812. MS_LOG(INFO) << "tensor slot: " << tensor.slot();
  813. MS_LOG(INFO) << "tensor finished: " << std::boolalpha << tensor.finished() << std::noboolalpha;
  814. MS_LOG(INFO) << "tensor iter: " << tensor.iter();
  815. MS_LOG(INFO) << "tensor truncate: " << std::boolalpha << tensor.truncate() << std::noboolalpha;
  816. MS_LOG(INFO) << "tensor dims: ";
  817. for (auto dim : tensor.dims()) {
  818. MS_LOG(INFO) << dim << ",";
  819. }
  820. MS_LOG(INFO) << "tensor dtype: " << tensor.data_type();
  821. }
  822. EventReply send_tensors_reply = grpc_client_->SendTensors(tensors);
  823. if (send_tensors_reply.status() != debugger::EventReply::OK) {
  824. MS_LOG(ERROR) << "Error: SendTensors failed";
  825. }
  826. }
  827. void Debugger::ViewStatLevel(const EventReply &reply) {
  828. std::list<TensorSummary> tensor_stats_list = LoadTensorsStat(GetTensors(reply));
  829. EventReply send_tensors_stat_reply = grpc_client_->SendTensorStats(tensor_stats_list);
  830. if (send_tensors_stat_reply.status() != debugger::EventReply::OK) {
  831. MS_LOG(ERROR) << "Error: SendTensorsStats failed.";
  832. }
  833. }
  834. void Debugger::ViewBaseLevel(const EventReply &reply) {
  835. std::list<TensorBase> tensor_base_list = LoadTensorsBase(GetTensors(reply));
  836. EventReply send_tensor_base_reply = grpc_client_->SendTensorBase(tensor_base_list);
  837. if (send_tensor_base_reply.status() != debugger::EventReply::OK) {
  838. MS_LOG(ERROR) << "Error: SendTensorsBase failed.";
  839. }
  840. }
  841. void AddTensorProtoInfo(TensorProto *tensor_item, const TensorProto &tensor) {
  842. tensor_item->set_node_name(tensor.node_name());
  843. tensor_item->set_slot(tensor.slot());
  844. tensor_item->set_iter(tensor.iter());
  845. tensor_item->set_truncate(tensor.truncate());
  846. tensor_item->clear_tensor_content();
  847. tensor_item->clear_data_type();
  848. tensor_item->clear_dims();
  849. }
  850. void AddTensorStatInfo(const DebugServices::TensorStat &tensor_stat, std::list<TensorSummary> *tensor_summary_list) {
  851. if (tensor_summary_list == nullptr) {
  852. MS_LOG(DEBUG) << "tensor_summary_list is nullptr.";
  853. return;
  854. }
  855. TensorSummary tensor_summary_item;
  856. TensorBase *tensor_base = tensor_summary_item.mutable_tensor_base();
  857. tensor_base->set_data_type(tensor_stat.dtype);
  858. tensor_base->set_data_size(tensor_stat.data_size);
  859. for (auto elem : tensor_stat.shape) {
  860. tensor_base->add_shape(elem);
  861. }
  862. Statistics *tensor_statistics = tensor_summary_item.mutable_statistics();
  863. tensor_statistics->set_is_bool(tensor_stat.is_bool);
  864. tensor_statistics->set_max_value(tensor_stat.max_value);
  865. tensor_statistics->set_min_value(tensor_stat.min_value);
  866. tensor_statistics->set_avg_value(tensor_stat.avg_value);
  867. tensor_statistics->set_count(tensor_stat.count);
  868. tensor_statistics->set_neg_zero_count(tensor_stat.neg_zero_count);
  869. tensor_statistics->set_pos_zero_count(tensor_stat.pos_zero_count);
  870. tensor_statistics->set_nan_count(tensor_stat.nan_count);
  871. tensor_statistics->set_neg_inf_count(tensor_stat.neg_inf_count);
  872. tensor_statistics->set_pos_inf_count(tensor_stat.pos_inf_count);
  873. tensor_statistics->set_zero_count(tensor_stat.zero_count);
  874. tensor_summary_list->push_back(tensor_summary_item);
  875. }
  876. void Debugger::SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id,
  877. const ProtoVector<WatchCondition_Parameter> &parameters) {
  878. std::vector<std::tuple<std::string, bool>> check_node_list;
  879. std::vector<DebugServices::parameter_t> parameter_list;
  880. std::transform(nodes.begin(), nodes.end(), std::back_inserter(check_node_list),
  881. [](const WatchNode &node) -> std::tuple<std::string, bool> {
  882. return make_tuple(node.node_name(), node.node_type() == "scope");
  883. });
  884. std::transform(
  885. parameters.begin(), parameters.end(), std::back_inserter(parameter_list),
  886. [](const WatchCondition_Parameter &parameter) -> DebugServices::parameter_t {
  887. return DebugServices::parameter_t{parameter.name(), parameter.disabled(), parameter.value(), parameter.hit()};
  888. });
  889. debug_services_->AddWatchpoint(id, condition.condition(), condition.value(), check_node_list, parameter_list);
  890. }
  891. void Debugger::RemoveWatchpoint(const int32_t id) { debug_services_->RemoveWatchpoint(id); }
  892. std::list<TensorProto> Debugger::LoadTensors(const ProtoVector<TensorProto> &tensors) const {
  893. std::vector<std::string> name;
  894. std::vector<std::string> ret_name;
  895. std::vector<char *> data_ptr;
  896. std::vector<ssize_t> data_size;
  897. std::vector<unsigned int> dtype;
  898. std::vector<std::vector<int64_t>> shape;
  899. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  900. // ret_name will contain tensor names that are found in TensorLoader
  901. // items in ret_name will be in the same order with tensors if found
  902. debug_services_->ReadNodesTensors(name, &ret_name, &data_ptr, &data_size, &dtype, &shape);
  903. std::list<TensorProto> tensor_list;
  904. size_t result_index = 0;
  905. for (auto tensor : tensors) {
  906. ssize_t size_iter = 0;
  907. if (result_index >= ret_name.size() || ret_name[result_index] != GetTensorFullName(tensor)) {
  908. TensorProto tensor_item;
  909. tensor_item.set_finished(true);
  910. AddTensorProtoInfo(&tensor_item, tensor);
  911. tensor_list.push_back(tensor_item);
  912. continue;
  913. }
  914. ssize_t tensor_size = data_size[result_index];
  915. while (size_iter < tensor_size) {
  916. ssize_t chunk_size = g_chunk_size;
  917. TensorProto tensor_item;
  918. tensor_item.set_finished(false);
  919. if (tensor_size - size_iter <= g_chunk_size) {
  920. chunk_size = tensor_size - size_iter;
  921. tensor_item.set_finished(true);
  922. }
  923. AddTensorProtoInfo(&tensor_item, tensor);
  924. // return empty tensor if didn't find the requested tensor
  925. tensor_item.set_tensor_content(data_ptr[result_index] + size_iter, chunk_size);
  926. tensor_item.set_data_type((debugger::DataType)dtype[result_index]);
  927. for (auto &elem : shape[result_index]) {
  928. tensor_item.add_dims(elem);
  929. }
  930. // add tensor to result list and increment result_index to check next item in ret_name
  931. tensor_list.push_back(tensor_item);
  932. if (size_iter > INT_MAX - g_chunk_size) {
  933. MS_EXCEPTION(ValueError) << size_iter << " + " << g_chunk_size << " would lead to integer overflow!";
  934. }
  935. size_iter += g_chunk_size;
  936. }
  937. result_index++;
  938. }
  939. return tensor_list;
  940. }
  941. std::list<TensorBase> Debugger::LoadTensorsBase(const ProtoVector<TensorProto> &tensors) const {
  942. std::list<TensorBase> tensor_base_list;
  943. std::vector<std::string> name;
  944. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  945. std::vector<std::tuple<std::string, std::shared_ptr<TensorData>>> result_list;
  946. debug_services_->SearchNodesTensors(name, &result_list);
  947. for (auto result : result_list) {
  948. auto tensor = std::get<1>(result);
  949. if (!tensor) {
  950. // tensor was not found, creating empty tensor base.
  951. TensorBase tensor_base_item;
  952. tensor_base_item.set_data_size(0);
  953. tensor_base_item.set_data_type(0);
  954. tensor_base_item.add_shape(0);
  955. tensor_base_list.push_back(tensor_base_item);
  956. continue;
  957. }
  958. // tensor was found creating tensor base object.
  959. TensorBase tensor_base_item;
  960. tensor_base_item.set_data_size(tensor->GetByteSize());
  961. tensor_base_item.set_data_type(tensor->GetType());
  962. for (auto elem : tensor->GetShape()) {
  963. tensor_base_item.add_shape(elem);
  964. }
  965. tensor_base_list.push_back(tensor_base_item);
  966. }
  967. return tensor_base_list;
  968. }
  969. std::list<TensorSummary> Debugger::LoadTensorsStat(const ProtoVector<TensorProto> &tensors) const {
  970. std::list<TensorSummary> tensor_summary_list;
  971. std::vector<std::string> name;
  972. std::transform(tensors.begin(), tensors.end(), std::back_inserter(name), GetTensorFullName);
  973. std::vector<std::tuple<std::string, std::shared_ptr<TensorData>>> result_list;
  974. debug_services_->SearchNodesTensors(name, &result_list);
  975. for (auto result : result_list) {
  976. auto tensor = std::get<1>(result);
  977. if (!tensor) {
  978. // tensor was not found, creating empty tensor summary.
  979. DebugServices::TensorStat tensor_stat;
  980. AddTensorStatInfo(tensor_stat, &tensor_summary_list);
  981. continue;
  982. }
  983. // tensor was found creating tensor summary object.
  984. DebugServices::TensorStat tensor_stat = debug_services_->GetTensorStatistics(tensor);
  985. AddTensorStatInfo(tensor_stat, &tensor_summary_list);
  986. }
  987. return tensor_summary_list;
  988. }
  989. void Debugger::Exit() {
  990. // debugger will notify main thread to exit because main thread can only exit at step boundary.
  991. MS_LOG(INFO) << "Exit Debugger";
  992. SetEnableHeartbeat(false);
  993. pipeline::GraphExecutorPy::DebugTerminate(true);
  994. }
  995. std::list<WatchpointHit> Debugger::CheckWatchpoints(const std::string &watchnode, const CNodePtr &kernel,
  996. bool recheck) {
  997. std::vector<std::string> name;
  998. std::vector<std::string> slot;
  999. std::vector<int> condition;
  1000. std::vector<unsigned int> watchpoint_id;
  1001. std::vector<std::string> overflow_ops;
  1002. std::vector<std::vector<DebugServices::parameter_t>> parameters;
  1003. std::vector<int32_t> error_codes;
  1004. std::vector<std::shared_ptr<TensorData>> tensor_list;
  1005. if (watchnode.empty()) {
  1006. tensor_list = debug_services_->GetTensor();
  1007. } else {
  1008. tensor_list = debug_services_->GetNodeTensor(kernel);
  1009. }
  1010. std::vector<std::string> file_list;
  1011. MS_LOG(INFO) << "checkwatchpoints call for step " << num_step_;
  1012. debug_services_->CheckWatchpoints(&name, &slot, &condition, &watchpoint_id, &parameters, &error_codes, overflow_ops,
  1013. file_list, &tensor_list, initial_suspend_, watchnode.empty(), recheck);
  1014. std::list<WatchpointHit> hits;
  1015. for (unsigned int i = 0; i < name.size(); i++) {
  1016. WatchpointHit hit;
  1017. std::vector<DebugServices::parameter_t> &parameter = parameters[i];
  1018. hit.set_id(watchpoint_id[i]);
  1019. hit.set_error_code(error_codes[i]);
  1020. // here TensorProto act as a tensor indicator, not sending tensor content
  1021. TensorProto *tensor_item = hit.mutable_tensor();
  1022. tensor_item->set_node_name(name[i]);
  1023. tensor_item->set_slot(slot[i]);
  1024. tensor_item->set_finished(true);
  1025. WatchCondition *condition_item = hit.mutable_watch_condition();
  1026. condition_item->set_condition(debugger::WatchCondition_Condition(condition[i]));
  1027. for (const auto &p : parameter) {
  1028. auto x = condition_item->mutable_params()->Add();
  1029. x->set_name(p.name);
  1030. x->set_disabled(p.disabled);
  1031. x->set_value(p.value);
  1032. x->set_hit(p.hit);
  1033. x->set_actual_value(p.actual_value);
  1034. }
  1035. hits.push_back(hit);
  1036. }
  1037. return hits;
  1038. }
  1039. void Debugger::SendWatchpoints(const std::list<WatchpointHit> &points) {
  1040. // send info about watchpoint
  1041. if (!points.empty()) {
  1042. EventReply reply = grpc_client_->SendWatchpointHits(points);
  1043. if (reply.status() != reply.OK) {
  1044. MS_LOG(ERROR) << "Error: SendWatchpointHits failed";
  1045. }
  1046. }
  1047. }
  1048. bool Debugger::DumpTensorToFile(const std::string &tensor_name, bool trans_flag, const std::string &filepath,
  1049. const std::string &host_fmt, const std::vector<int64_t> &host_shape, TypeId host_type,
  1050. TypeId device_type, const std::string &addr_format, size_t slot) const {
  1051. return debug_services_.get()->DumpTensorToFile(tensor_name, trans_flag, filepath, host_fmt, host_shape, host_type,
  1052. device_type, addr_format, slot);
  1053. }
  1054. bool Debugger::DebugServicesIsWatchPoint(const std::string &kernel_name, const CNodePtr &kernel) const {
  1055. return debug_services_.get()->IsWatchPoint(kernel_name, kernel);
  1056. }
  1057. void Debugger::EmptyTensor() { debug_services_.get()->EmptyTensor(); }
  1058. void Debugger::SetTensorLoaderIterNum(uint32_t iter_num) { debug_services_.get()->SetTensorLoaderIterNum(iter_num); }
  1059. void Debugger::EmptyPrevTensor() { debug_services_.get()->EmptyPrevTensor(); }
  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