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