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