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_grpc_server.py 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Implement the debugger grpc server."""
  16. import copy
  17. from functools import wraps
  18. import mindinsight
  19. from mindinsight.debugger.common.log import LOGGER as log
  20. from mindinsight.debugger.common.utils import get_ack_reply, ServerStatus, \
  21. Streams, RunLevel
  22. from mindinsight.debugger.conditionmgr.condition import TargetTypeEnum
  23. from mindinsight.debugger.proto import debug_grpc_pb2_grpc as grpc_server_base
  24. from mindinsight.debugger.proto.ms_graph_pb2 import GraphProto
  25. def debugger_wrap(func):
  26. """Wrapper for catch exception."""
  27. @wraps(func)
  28. def record_log(*args, **kwargs):
  29. try:
  30. return func(*args, **kwargs)
  31. except Exception as err:
  32. log.exception(err)
  33. raise err
  34. return record_log
  35. class DebuggerGrpcServer(grpc_server_base.EventListenerServicer):
  36. """The grpc server used to interactive with grpc client."""
  37. def __init__(self, cache_store, condition_mgr):
  38. """
  39. Initialize.
  40. Args:
  41. cache_store (DebuggerCache): Debugger cache store.
  42. """
  43. cache_store.initialize()
  44. self._cache_store = cache_store
  45. self._condition_mgr = condition_mgr
  46. # the next position of command queue to be queried
  47. self._pos = None
  48. # the status of grpc server, the value is in ServerStatus
  49. self._status = None
  50. # the run command cache, used to deal with left continue steps or nodes
  51. self._old_run_cmd = None
  52. # the view command cache, used to update tensor history through data queue
  53. self._received_view_cmd = None
  54. # the flag of receiving watch point hit
  55. self._received_hit = None
  56. self.init()
  57. def init(self):
  58. """Init debugger grpc server."""
  59. self._pos = '0'
  60. self._status = ServerStatus.PENDING
  61. self._old_run_cmd = {}
  62. self._received_view_cmd = {}
  63. self._received_hit = []
  64. self._cache_store.clean()
  65. @debugger_wrap
  66. def WaitCMD(self, request, context):
  67. """Wait for a command in DebuggerCache."""
  68. # check if graph have already received.
  69. log.info("Received WaitCMD at %s-th step.", request.cur_step)
  70. if self._status == ServerStatus.PENDING:
  71. log.warning("No graph received before WaitCMD.")
  72. reply = get_ack_reply(1)
  73. return reply
  74. # send graph if it has not been sent before
  75. self._pre_process(request)
  76. # deal with old command
  77. reply = self._deal_with_old_command()
  78. # wait for next command
  79. if reply is None:
  80. reply = self._wait_for_next_command()
  81. # check the reply
  82. if reply is None:
  83. reply = get_ack_reply(1)
  84. log.warning("Failed to get command event.")
  85. else:
  86. log.debug("Reply to WaitCMD: %s", reply)
  87. return reply
  88. def _pre_process(self, request):
  89. """Pre-process before dealing with command."""
  90. # check if version is mismatch, if mismatch, send mismatch info to UI
  91. if self._status == ServerStatus.MISMATCH:
  92. log.warning("Version of Mindspore and Mindinsight re unmatched,"
  93. "waiting for user to terminate the script.")
  94. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  95. # put metadata into data queue
  96. metadata = metadata_stream.get(['state', 'debugger_version'])
  97. self._cache_store.put_data(metadata)
  98. return
  99. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  100. is_new_step = metadata_stream.step < request.cur_step
  101. is_new_node = metadata_stream.full_name != request.cur_node
  102. # clean cache data at the beginning of new step or node has been changed.
  103. if is_new_step or is_new_node:
  104. self._cache_store.clean_data()
  105. self._cache_store.get_stream_handler(Streams.TENSOR).clean_tensors(request.cur_step)
  106. if is_new_step:
  107. self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()
  108. # receive graph at the beginning of the training
  109. if self._status == ServerStatus.RECEIVE_GRAPH:
  110. self._send_graph_flag(metadata_stream)
  111. # receive new metadata
  112. if is_new_step or is_new_node:
  113. self._update_metadata(metadata_stream, request)
  114. self._send_received_tensor_tag()
  115. self._send_watchpoint_hit_flag()
  116. def _send_graph_flag(self, metadata_stream):
  117. """
  118. Send graph and metadata to UI.
  119. Args:
  120. metadata_stream (MetadataHandler): Metadata handler stream.
  121. """
  122. self._cache_store.clean_command()
  123. # receive graph in the beginning of the training
  124. self._status = ServerStatus.WAITING
  125. metadata_stream.state = 'waiting'
  126. metadata = metadata_stream.get()
  127. res = self._cache_store.get_stream_handler(Streams.GRAPH).get()
  128. res.update(metadata)
  129. self._cache_store.put_data(res)
  130. log.debug("Put graph into data queue.")
  131. def _update_metadata(self, metadata_stream, metadata_proto):
  132. """
  133. Update metadata.
  134. Args:
  135. metadata_stream (MetadataHandler): Metadata handler stream.
  136. metadata_proto (MetadataProto): Metadata proto send by client.
  137. """
  138. # put new metadata into cache
  139. metadata_stream.put(metadata_proto)
  140. # update current node name and graph name
  141. graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)
  142. full_name = metadata_proto.cur_node
  143. graph_name = graph_stream.get_graph_id_by_full_name(
  144. full_name) if full_name else metadata_stream.graph_name
  145. cur_node = graph_stream.get_node_name_by_full_name(full_name, graph_name)
  146. metadata_stream.node_name = cur_node
  147. metadata_stream.graph_name = graph_name
  148. metadata = metadata_stream.get()
  149. self._cache_store.put_data(metadata)
  150. log.debug("Put new metadata into data queue.")
  151. def _send_received_tensor_tag(self):
  152. """Send received_finish_tag."""
  153. node_info = self._received_view_cmd.get('node_info')
  154. if not node_info or self._received_view_cmd.get('wait_for_tensor'):
  155. return
  156. metadata = self._cache_store.get_stream_handler(Streams.METADATA).get(['step', 'state'])
  157. ret = {'receive_tensor': node_info.copy()}
  158. ret.update(metadata)
  159. self._cache_store.put_data(ret)
  160. self._received_view_cmd.clear()
  161. log.debug("Send receive tensor flag for %s", node_info)
  162. def _send_watchpoint_hit_flag(self):
  163. """Send Watchpoint hit flag."""
  164. watchpoint_hit_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT)
  165. if not self._received_hit:
  166. return
  167. watchpoint_hits = self._received_hit
  168. self._received_hit = []
  169. for watchpoint_hit in watchpoint_hits:
  170. watchpoint_hit_stream.put(watchpoint_hit)
  171. watchpoint_hits_info = watchpoint_hit_stream.get()
  172. self._cache_store.put_data(watchpoint_hits_info)
  173. log.debug("Send the watchpoint hits to DataQueue.\nSend the reply.")
  174. def _deal_with_old_command(self):
  175. """Deal with old command."""
  176. event = None
  177. while self._cache_store.has_command(self._pos) and event is None:
  178. event = self._get_next_command()
  179. log.debug("Deal with old %s-th command:\n%s.", self._pos, event)
  180. # deal with continue run command
  181. if event is None and self._old_run_cmd:
  182. left_step_count = self._old_run_cmd.get('left_step_count')
  183. node_name = self._old_run_cmd.get('node_name')
  184. # node_name and left_step_count should not set at the same time
  185. if not (left_step_count or node_name) or (left_step_count and node_name):
  186. log.warning("Invalid old run command. %s", self._old_run_cmd)
  187. self._old_run_cmd.clear()
  188. return None
  189. if left_step_count:
  190. event = self._deal_with_left_continue_step(left_step_count)
  191. else:
  192. event = self._deal_with_left_continue_node(node_name)
  193. log.debug("Send old RunCMD. Clean watchpoint hit.")
  194. return event
  195. def _deal_with_left_continue_step(self, left_step_count):
  196. """
  197. Construct run command with left continue step count.
  198. Args:
  199. left_step_count (int): The count of left steps to be executed.
  200. Returns:
  201. Event, the run command event.
  202. """
  203. event = get_ack_reply()
  204. event.run_cmd.run_steps = 1
  205. event.run_cmd.run_level = 'step'
  206. left_step_count = left_step_count - 1 if left_step_count > 0 else -1
  207. if not left_step_count:
  208. self._old_run_cmd.clear()
  209. else:
  210. self._old_run_cmd['left_step_count'] = left_step_count
  211. log.debug("Send old step RunCMD. Left step count: %s", left_step_count)
  212. return event
  213. def _deal_with_left_continue_node(self, node_name):
  214. """
  215. Construct run command with left continue nodes.
  216. Args:
  217. node_name (str): The target node name.
  218. Returns:
  219. Union[None, Event], the run command event.
  220. """
  221. cur_full_name = self._cache_store.get_stream_handler(Streams.METADATA).full_name
  222. if cur_full_name == node_name:
  223. log.info("Execute to target node: %s", node_name)
  224. self._old_run_cmd.clear()
  225. return None
  226. event = get_ack_reply()
  227. event.run_cmd.run_level = 'node'
  228. event.run_cmd.node_name = ''
  229. log.debug("Send old node RunCMD, cur node: %s, target node: %s", cur_full_name, node_name)
  230. return event
  231. def _wait_for_next_command(self):
  232. """
  233. Wait for next command.
  234. Returns:
  235. EventReply, the command event.
  236. """
  237. log.info("Start to wait for command.")
  238. if self._status != ServerStatus.MISMATCH:
  239. self._cache_store.get_stream_handler(Streams.METADATA).state = ServerStatus.WAITING.value
  240. self._cache_store.put_data({'metadata': {'state': 'waiting'}})
  241. event = None
  242. while event is None and self._status in [ServerStatus.MISMATCH, ServerStatus.WAITING]:
  243. log.debug("Wait for %s-th command", self._pos)
  244. event = self._get_next_command()
  245. return event
  246. def _get_next_command(self):
  247. """Get next command."""
  248. self._pos, event = self._cache_store.get_command(self._pos)
  249. if event is None:
  250. return event
  251. if isinstance(event, dict):
  252. event = self._deal_with_view_cmd(event)
  253. elif event.HasField('run_cmd'):
  254. event = self._deal_with_run_cmd(event)
  255. elif event.HasField('exit'):
  256. self._cache_store.clean()
  257. log.debug("Clean cache for exit cmd.")
  258. else:
  259. self._cache_store.get_stream_handler(Streams.WATCHPOINT).clean_cache_set_cmd(event.set_cmd)
  260. log.debug("get set cmd.")
  261. return event
  262. def _deal_with_view_cmd(self, event):
  263. """
  264. Deal with view cmd.
  265. Args:
  266. event (dict): View command params.
  267. - view_cmd (EventReply): EventReply with view command.
  268. - node_name (str): The center node name for view command.
  269. - tensor_name (str): The center tensor name for view command.
  270. - graph_name (str): The graph name of center node.
  271. Returns:
  272. EventReply, view command to be sent to client.
  273. """
  274. view_cmd = event.pop('view_cmd', None)
  275. log.debug("Receive view cmd for node: %s.", event)
  276. if not (view_cmd and event):
  277. log.debug("Invalid view command. Ignore it.")
  278. return None
  279. self._received_view_cmd['node_info'] = event
  280. self._received_view_cmd['wait_for_tensor'] = True
  281. return view_cmd
  282. def _deal_with_run_cmd(self, event):
  283. """Deal with run cmd."""
  284. run_cmd = event.run_cmd
  285. # receive step command
  286. if run_cmd.run_level == 'step':
  287. # receive pause cmd
  288. if not run_cmd.run_steps:
  289. log.debug("Pause training and wait for next command.")
  290. self._old_run_cmd.clear()
  291. return None
  292. # receive step cmd
  293. left_steps = run_cmd.run_steps - 1
  294. event.run_cmd.run_steps = 1
  295. if left_steps:
  296. self._old_run_cmd['left_step_count'] = left_steps if left_steps > 0 else -1
  297. elif run_cmd.node_name:
  298. self._old_run_cmd['node_name'] = run_cmd.node_name
  299. run_cmd.node_name = ''
  300. # clean watchpoint hit cache
  301. if run_cmd.run_level == RunLevel.RECHECK.value:
  302. self._cache_store.get_stream_handler(Streams.WATCHPOINT_HIT).clean()
  303. log.debug("Receive RunCMD. Clean watchpoint hit cache.")
  304. return event
  305. @debugger_wrap
  306. def SendMetadata(self, request, context):
  307. """Send metadata into DebuggerCache."""
  308. log.info("Received Metadata.")
  309. if self._status != ServerStatus.PENDING:
  310. log.info("Re-initialize cache store when new session comes.")
  311. self.init()
  312. client_ip = context.peer().split(':', 1)[-1]
  313. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  314. reply = get_ack_reply()
  315. if request.training_done:
  316. log.info("The training from %s has finished.", client_ip)
  317. else:
  318. ms_version = request.ms_version
  319. if not ms_version:
  320. ms_version = '1.0.x'
  321. if version_match(ms_version, mindinsight.__version__) is False:
  322. log.info("Version is mismatched, mindspore is: %s, mindinsight is: %s",
  323. ms_version, mindinsight.__version__)
  324. self._status = ServerStatus.MISMATCH
  325. reply.version_matched = False
  326. metadata_stream.state = 'mismatch'
  327. else:
  328. log.info("version is matched.")
  329. reply.version_matched = True
  330. metadata_stream.debugger_version = {'ms': ms_version, 'mi': mindinsight.__version__}
  331. log.debug("Put ms_version from %s into cache.", client_ip)
  332. metadata_stream.put(request)
  333. metadata_stream.client_ip = client_ip
  334. log.debug("Put new metadata from %s into cache.", client_ip)
  335. # put metadata into data queue
  336. metadata = metadata_stream.get()
  337. self._cache_store.put_data(metadata)
  338. log.debug("Send the reply to %s.", client_ip)
  339. return reply
  340. @debugger_wrap
  341. def SendGraph(self, request_iterator, context):
  342. """Send graph into DebuggerCache."""
  343. log.info("Received graph.")
  344. reply = get_ack_reply()
  345. if self._status == ServerStatus.MISMATCH:
  346. log.info("Mindspore and Mindinsight is unmatched, waiting for user to terminate the service.")
  347. return reply
  348. serial_graph = b""
  349. for chunk in request_iterator:
  350. serial_graph += chunk.buffer
  351. graph = GraphProto.FromString(serial_graph)
  352. log.debug("Deserialize the graph %s. Receive %s nodes", graph.name, len(graph.node))
  353. graph_dict = {graph.name: graph}
  354. self._cache_store.get_stream_handler(Streams.GRAPH).put(graph_dict)
  355. self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(graph.const_vals)
  356. self._cache_store.get_stream_handler(Streams.METADATA).graph_name = graph.name
  357. self._record_parameter_names()
  358. self._status = ServerStatus.RECEIVE_GRAPH
  359. log.debug("Send the reply for graph.")
  360. return reply
  361. @debugger_wrap
  362. def SendMultiGraphs(self, request_iterator, context):
  363. """Send graph into DebuggerCache."""
  364. log.info("Received multi_graphs.")
  365. reply = get_ack_reply()
  366. if self._status == ServerStatus.MISMATCH:
  367. log.info("Mindspore and Mindinsight is unmatched, waiting for user to terminate the service.")
  368. return reply
  369. serial_graph = b""
  370. graph_dict = {}
  371. for chunk in request_iterator:
  372. serial_graph += chunk.buffer
  373. if chunk.finished:
  374. sub_graph = GraphProto.FromString(serial_graph)
  375. graph_dict[sub_graph.name] = sub_graph
  376. log.debug("Deserialize the graph %s. Receive %s nodes", sub_graph.name,
  377. len(sub_graph.node))
  378. serial_graph = b""
  379. self._cache_store.get_stream_handler(Streams.TENSOR).put_const_vals(
  380. sub_graph.const_vals)
  381. self._cache_store.get_stream_handler(Streams.GRAPH).put(graph_dict)
  382. self._record_parameter_names()
  383. self._status = ServerStatus.RECEIVE_GRAPH
  384. log.debug("Send the reply for graph.")
  385. return reply
  386. def _record_parameter_names(self):
  387. """Record parameter full names in tensor handler."""
  388. parameter_nodes = self._cache_store.get_stream_handler(Streams.GRAPH).search_in_graph(
  389. pattern={'node_category': TargetTypeEnum.PARAMETER.value})
  390. tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)
  391. for node in parameter_nodes:
  392. tensor_name = [node.full_name + ':0']
  393. tensor_stream.record_parameter_names(tensor_name)
  394. @debugger_wrap
  395. def SendTensors(self, request_iterator, context):
  396. """Send tensors into DebuggerCache."""
  397. log.info("Received tensor.")
  398. tensor_construct = []
  399. tensor_stream = self._cache_store.get_stream_handler(Streams.TENSOR)
  400. metadata_stream = self._cache_store.get_stream_handler(Streams.METADATA)
  401. tensor_names = []
  402. step = metadata_stream.step
  403. for tensor in request_iterator:
  404. tensor_construct.append(tensor)
  405. if tensor.finished:
  406. update_flag = tensor_stream.put({'step': step, 'tensor_protos': tensor_construct})
  407. if self._received_view_cmd.get('wait_for_tensor') and update_flag:
  408. # update_flag is used to avoid querying empty tensors again
  409. self._received_view_cmd['wait_for_tensor'] = False
  410. log.debug("Set wait for tensor flag to False.")
  411. tensor_construct = []
  412. tensor_names.append(':'.join([tensor.node_name, tensor.slot]))
  413. continue
  414. reply = get_ack_reply()
  415. return reply
  416. @debugger_wrap
  417. def SendWatchpointHits(self, request_iterator, context):
  418. """Send watchpoint hits info DebuggerCache."""
  419. log.info("Received WatchpointHits. Left run cmd %s change to emtpy.", self._old_run_cmd)
  420. self._old_run_cmd.clear()
  421. if self._cache_store.get_stream_handler(Streams.METADATA).state == ServerStatus.RUNNING.value:
  422. # if the client session is running a script, all the cached command should be cleared
  423. # when received watchpoint_hits.
  424. self._cache_store.clean_command()
  425. # save the watchpoint_hits data
  426. watchpoint_hits = []
  427. watchpoint_stream = self._cache_store.get_stream_handler(Streams.WATCHPOINT)
  428. graph_stream = self._cache_store.get_stream_handler(Streams.GRAPH)
  429. for watchpoint_hit_proto in request_iterator:
  430. node_full_name = watchpoint_hit_proto.tensor.node_name
  431. graph_name = graph_stream.get_graph_id_by_full_name(node_full_name)
  432. if not graph_name:
  433. log.warning("Cannot find node %s in graph. Skip it.", node_full_name)
  434. continue
  435. ui_node_name = graph_stream.get_node_name_by_full_name(node_full_name, graph_name)
  436. log.debug("Receive watch point hit: %s", watchpoint_hit_proto)
  437. if not ui_node_name:
  438. log.info("Not support to show %s on graph.", node_full_name)
  439. continue
  440. watchpoint_hit = {
  441. 'tensor_proto': watchpoint_hit_proto.tensor,
  442. 'watchpoint': copy.deepcopy(watchpoint_stream.get_watchpoint_by_id(watchpoint_hit_proto.id)),
  443. 'node_name': ui_node_name,
  444. 'graph_name': graph_name
  445. }
  446. hit_params = {}
  447. for param in watchpoint_hit_proto.watch_condition.params:
  448. if param.actual_value:
  449. hit_params[param.name] = param.actual_value
  450. for i, param in enumerate(watchpoint_hit['watchpoint'].condition['params']):
  451. name = param['name']
  452. if name in hit_params.keys():
  453. watchpoint_hit['watchpoint'].condition['params'][i]['actual_value'] = hit_params[name]
  454. else:
  455. watchpoint_hit['watchpoint'].condition['params'][i]['actual_value'] = None
  456. if watchpoint_hit_proto.error_code:
  457. watchpoint_hit['error_code'] = watchpoint_hit_proto.error_code
  458. watchpoint_hits.append(watchpoint_hit)
  459. self._received_hit = watchpoint_hits
  460. reply = get_ack_reply()
  461. return reply
  462. def version_match(mi_version, ms_version):
  463. """Judge if the version of Mindinsight and Mindspore is matched"""
  464. mi_major, mi_minor = mi_version.split('.')[:2]
  465. ms_major, ms_minor = ms_version.split('.')[:2]
  466. return mi_major == ms_major and mi_minor == ms_minor