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.

tensor_handler.py 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. """Define the tensor stream handler."""
  16. import numpy as np
  17. from mindinsight.datavisual.data_transform.graph.node import NodeTypeEnum
  18. from mindinsight.debugger.common.exceptions.exceptions import DebuggerParamValueError
  19. from mindinsight.debugger.common.log import LOGGER as log
  20. from mindinsight.debugger.proto.ms_graph_pb2 import DataType
  21. from mindinsight.debugger.stream_cache.tensor import OpTensor, ConstTensor
  22. from mindinsight.debugger.stream_handler.base_handler import StreamHandlerBase
  23. from mindinsight.utils.tensor import TensorUtils, TensorComparison
  24. class TensorHandler(StreamHandlerBase):
  25. """Metadata Handler."""
  26. def __init__(self):
  27. self._const_vals = {}
  28. self._tensors = {}
  29. self._cur_step = 0
  30. @property
  31. def cur_step(self):
  32. """The property of current step."""
  33. return self._cur_step
  34. @property
  35. def prev_step(self):
  36. """The property of previous step."""
  37. return self._cur_step - 1
  38. def put(self, value):
  39. """
  40. Put value into tensor cache. Called by grpc server.
  41. Args:
  42. value (dict): The Tensor proto message.
  43. - step (int): The current step of tensor.
  44. - tensor_protos (list[TensorProto]): The tensor proto.
  45. Returns:
  46. bool, the tensor has updated successfully.
  47. """
  48. tensor_protos = value.get('tensor_protos')
  49. merged_tensor = self._get_merged_tensor(tensor_protos)
  50. step = value.get('step', 0)
  51. if merged_tensor.iter and step > 0:
  52. log.debug("Received previous tensor.")
  53. step -= 1
  54. tensor = OpTensor(merged_tensor, step)
  55. flag = self._put_tensor_into_cache(tensor, step)
  56. log.info("Put tensor %s of step: %d, into cache. Flag: %s", tensor.name, step, flag)
  57. return flag
  58. @staticmethod
  59. def _get_merged_tensor(tensor_protos):
  60. """
  61. Merged list of parsed tensor value into one.
  62. Args:
  63. tensor_protos (list[TensorProto]): List of tensor proto.
  64. Returns:
  65. TensorProto, merged tensor proto.
  66. """
  67. merged_tensor = tensor_protos[-1]
  68. if len(tensor_protos) > 1:
  69. tensor_value = bytes()
  70. for tensor_proto in tensor_protos:
  71. if not tensor_proto.tensor_content:
  72. log.warning("Doesn't find tensor value for %s:%s",
  73. tensor_proto.node_name, tensor_proto.slot)
  74. break
  75. tensor_value += tensor_proto.tensor_content
  76. merged_tensor.tensor_content = tensor_value
  77. log.debug("Merge multi tensor values into one.")
  78. return merged_tensor
  79. def _put_tensor_into_cache(self, tensor, step):
  80. """
  81. Put tensor into cache.
  82. Args:
  83. tensor (OpTensor): The tensor value.
  84. step (int): The step of tensor.
  85. Returns:
  86. bool, the tensor has updated successfully.
  87. """
  88. cache_tensor = self._tensors.get(tensor.name)
  89. if cache_tensor is None:
  90. cache_tensor = {}
  91. self._tensors[tensor.name] = cache_tensor
  92. old_tensor = cache_tensor.get(step)
  93. if old_tensor and not self._is_value_diff(old_tensor.value, tensor.value):
  94. log.debug("Tensor %s of step %s has no change. Ignore it.", tensor.name, step)
  95. return False
  96. cache_tensor[step] = tensor
  97. log.debug("Put updated tensor value for %s of step %s.", tensor.name, step)
  98. return True
  99. @staticmethod
  100. def _is_value_diff(old_value, new_value):
  101. """Check tensor value if there are equal."""
  102. log.debug("old value type: %s, new_value type: %s", type(old_value), type(new_value))
  103. if old_value is None and new_value is None:
  104. return False
  105. flag = old_value != new_value
  106. if isinstance(flag, np.ndarray):
  107. return flag.any()
  108. return flag
  109. def put_const_vals(self, const_vals):
  110. """
  111. Put const value into tensor cache.
  112. Args:
  113. const_vals (list[NamedValueProto]): List of const values.
  114. """
  115. for const_val in const_vals:
  116. if not (const_val.value and const_val.key):
  117. continue
  118. if DataType.Name(const_val.value.dtype) == "DT_TENSOR":
  119. tensor_proto = const_val.value.tensor_val
  120. tensor_proto.node_name = const_val.key
  121. tensor_proto.slot = '0'
  122. const_tensor = OpTensor(tensor_proto)
  123. else:
  124. const_tensor = ConstTensor(const_val)
  125. self._const_vals[const_tensor.name] = const_tensor
  126. def get(self, filter_condition=None):
  127. """
  128. Get full tensor value.
  129. Args:
  130. filter_condition (dict): Filter condition.
  131. - name (str): The full name of tensor.
  132. - node_type (str): The type of the node.
  133. - prev (bool): Whether to get previous tensor.
  134. Returns:
  135. dict, the tensor_value.
  136. """
  137. name = filter_condition.get('name')
  138. node_type = filter_condition.get('node_type')
  139. shape = filter_condition.get('shape')
  140. if filter_condition.get('prev'):
  141. step = self.prev_step
  142. else:
  143. step = self.cur_step
  144. tensor = self._get_tensor(name, node_type, step)
  145. if not tensor:
  146. log.error("No tensor named %s at the step %s", name, step)
  147. raise DebuggerParamValueError("No tensor named {}".format(name))
  148. tensor_info = tensor.get_full_info(shape)
  149. self._update_has_prev_step_field(tensor_info, name, node_type, step)
  150. return {'tensor_value': tensor_info}
  151. def _get_tensor(self, tensor_name, node_type=None, step=None):
  152. """
  153. Get tensor according to tensor name and node_type.
  154. Args:
  155. tensor_name (str): Tensor name, format like `node_name:slot`.
  156. node_type (str): Node type.
  157. step (int): The step of tensor info. Default: None.
  158. Returns:
  159. Union[OPTensor, ConstTensor], the tensor object.
  160. """
  161. if step is None:
  162. step = self._cur_step
  163. tensor = self._tensors.get(tensor_name, {}).get(step)
  164. if not tensor and node_type == NodeTypeEnum.CONST.value:
  165. const_name = tensor_name.rsplit('/', 1)[-1]
  166. tensor = self._const_vals.get(const_name)
  167. if tensor:
  168. self._tensors[tensor_name] = {step: tensor}
  169. return tensor
  170. def _get_basic_info(self, tensor_name, node_type=None):
  171. """Get the latest basic tensor info by tensor name."""
  172. tensor = self._get_tensor(tensor_name, node_type)
  173. if tensor:
  174. return tensor.get_basic_info()
  175. return None
  176. def update_tensor_history(self, tensor_history):
  177. """
  178. Add tensor basic info in tensor_history.
  179. Args:
  180. tensor_history (dict): Tensor history, including a list of tensor name and type.
  181. Returns:
  182. list[dict], the list of tensor basic info cache.
  183. """
  184. missed_tensors = []
  185. for tensor_info in tensor_history.get('tensor_history'):
  186. tensor_name = tensor_info.get('full_name')
  187. node_type = tensor_info.get('node_type')
  188. basic_info = self._get_basic_info(tensor_name, node_type)
  189. flag = self._update_has_prev_step_field(basic_info, tensor_name, node_type, self.cur_step)
  190. if flag is False:
  191. missed_tensor = tensor_info.copy()
  192. missed_tensor['iter'] = 'prev'
  193. missed_tensors.append(missed_tensor)
  194. log.debug("Add previous view cmd for %s", tensor_name)
  195. # add `has_prev_step` field to tensor basic info.
  196. if basic_info:
  197. tensor_info.update(basic_info)
  198. if basic_info.get('value') is None:
  199. missed_tensors.append(tensor_info)
  200. log.debug("Add view cmd for %s", tensor_name)
  201. else:
  202. missed_tensors.append(tensor_info)
  203. log.debug("Add view cmd for %s", tensor_name)
  204. return missed_tensors
  205. def _update_has_prev_step_field(self, tensor_info, tensor_name, node_type, step):
  206. """Update has_prev_step field in tensor info."""
  207. flag = None
  208. cur_tensor_value = bool(tensor_info and tensor_info.get('value') is not None)
  209. if node_type == NodeTypeEnum.PARAMETER.value:
  210. flag = self._get_prev_tensor_value_status(tensor_name, step)
  211. if flag and cur_tensor_value:
  212. tensor_info['has_prev_step'] = True
  213. return flag
  214. def _get_prev_tensor_value_status(self, tensor_name, step):
  215. """
  216. Get the status of tensor value of previous step.
  217. Args:
  218. tensor_name (str): Tensor name.
  219. step (int): The step of the tensor.
  220. Returns:
  221. Union[None, bool], the status of previous tensor value. If True, there is valid previous
  222. tensor value. If False, the tensor value should be queried from client.
  223. If None, ignore.
  224. """
  225. flag = None
  226. # check if the tensor has previous step value.
  227. prev_step = step - 1
  228. if prev_step < 0:
  229. return flag
  230. tensor = self._get_tensor(tensor_name, step=prev_step)
  231. return bool(tensor and not tensor.empty)
  232. def get_tensor_value_by_name(self, tensor_name, prev=False):
  233. """Get tensor value by name in numpy type."""
  234. cur_step = self._cur_step
  235. step = cur_step - 1 if prev else cur_step
  236. if step < 0:
  237. log.warning("%d step has no previous value for tensor: %s", cur_step, tensor_name)
  238. return None
  239. tensor = self._get_tensor(tensor_name, step=step)
  240. return tensor
  241. def clean_tensors(self, cur_step):
  242. """Clean the tensor cache."""
  243. self._cur_step = cur_step
  244. expired_tensor = []
  245. for tensor_name, tensor in self._tensors.items():
  246. expired_step = [step for step in tensor.keys() if step <= cur_step - 2]
  247. for step in expired_step:
  248. tensor.pop(step)
  249. if not tensor:
  250. expired_tensor.append(tensor_name)
  251. for tensor_name in expired_tensor:
  252. self._tensors.pop(tensor_name)
  253. def get_tensors_diff(self, tensor_name, shape, tolerance=0):
  254. """
  255. Get tensor comparisons data for given name, detail, shape and tolerance.
  256. Args:
  257. tensor_name (str): The name of tensor for cache.
  258. shape (tuple): Specify concrete dimensions of shape.
  259. tolerance (str): Specify tolerance of difference between current step tensor and previous
  260. step tensor. Default value is 0. Its is a percentage. The boundary value is equal to
  261. max(abs(min),abs(max)) * tolerance. The function of min and max is being used to
  262. calculate the min value and max value of the result of the current step tensor subtract
  263. the previous step tensor. If the absolute value of result is less than or equal to
  264. boundary value, the result will set to be zero.
  265. Raises:
  266. DebuggerParamValueError, If get current step node and previous step node failed or
  267. the type of tensor value is not numpy.ndarray."
  268. Returns:
  269. dict, the retrieved data.
  270. """
  271. curr_tensor = self.get_tensor_value_by_name(tensor_name)
  272. prev_tensor = self.get_tensor_value_by_name(tensor_name, prev=True)
  273. if not (curr_tensor and prev_tensor):
  274. log.error("Get current step and previous step for this tensor name %s failed.", tensor_name)
  275. raise DebuggerParamValueError(f"Get current step and previous step for this tensor name "
  276. f"{tensor_name} failed.")
  277. curr_tensor_slice = curr_tensor.get_tensor_value_by_shape(shape)
  278. prev_tensor_slice = prev_tensor.get_tensor_value_by_shape(shape)
  279. tensor_info = curr_tensor.get_basic_info()
  280. if isinstance(tensor_info, dict):
  281. tensor_info.pop('has_prev_step')
  282. tensor_info.pop('value')
  283. tensor_comparison = curr_tensor.tensor_comparison
  284. if not tensor_comparison or tensor_comparison.tolerance != tolerance:
  285. if isinstance(curr_tensor.value, np.ndarray) and isinstance(prev_tensor.value, np.ndarray):
  286. if curr_tensor.value.shape != prev_tensor.value.shape:
  287. raise DebuggerParamValueError("The shape of these two step tensors is not the same.")
  288. tensor_diff = TensorUtils.calc_diff_between_two_tensor(curr_tensor.value, prev_tensor.value, tolerance)
  289. if not tensor_comparison:
  290. stats = TensorUtils.get_statistics_from_tensor(tensor_diff)
  291. tensor_comparison = TensorComparison(tolerance, stats, tensor_diff)
  292. curr_tensor.update_tensor_comparisons(tensor_comparison)
  293. else:
  294. tensor_comparison.update(tolerance=tolerance, value=tensor_diff)
  295. else:
  296. raise DebuggerParamValueError("The type of tensor value should be numpy.ndarray.")
  297. # the type of curr_tensor_slice is one of None, np.ndarray or str
  298. if isinstance(curr_tensor_slice, np.ndarray) and isinstance(prev_tensor_slice, np.ndarray):
  299. if not shape:
  300. tensor_diff_slice = tensor_comparison.value
  301. else:
  302. tensor_diff_slice = tensor_comparison.value[shape]
  303. result = np.stack([prev_tensor_slice, curr_tensor_slice, tensor_diff_slice], axis=-1)
  304. tensor_info['diff'] = result.tolist()
  305. stats = TensorUtils.get_statistics_from_tensor(tensor_diff_slice)
  306. curr_tensor_stats = TensorUtils.get_statistics_from_tensor(curr_tensor.value)
  307. curr_tensor_slice_stats = TensorUtils.get_statistics_from_tensor(curr_tensor_slice)
  308. prev_tensor_stats = TensorUtils.get_statistics_from_tensor(prev_tensor.value)
  309. prev_tensor_slice_stats = TensorUtils.get_statistics_from_tensor(prev_tensor_slice)
  310. tensor_info['curr_step_statistics'] = TensorUtils.get_statistics_dict(stats=curr_tensor_slice_stats,
  311. overall_stats=curr_tensor_stats)
  312. tensor_info['prev_step_statistics'] = TensorUtils.get_statistics_dict(stats=prev_tensor_slice_stats,
  313. overall_stats=prev_tensor_stats)
  314. tensor_info['statistics'] = TensorUtils.get_statistics_dict(stats=stats,
  315. overall_stats=tensor_comparison.stats)
  316. elif isinstance(curr_tensor_slice, str):
  317. tensor_info['diff'] = curr_tensor_slice
  318. reply = {'tensor_value': tensor_info}
  319. return reply
  320. def get_tensor_statistics(self, tensor_name, node_type):
  321. """
  322. Get Tensor statistics.
  323. Args:
  324. tensor_name (str): Tensor name, format like `node_name:slot`.
  325. node_type (str): Node type.
  326. Returns:
  327. dict, overall statistics.
  328. """
  329. res = {}
  330. tensor = self._get_tensor(tensor_name, node_type)
  331. if tensor:
  332. res = tensor.get_tensor_statistics()
  333. return res