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.py 9.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. """The definition of tensor stream."""
  16. from abc import abstractmethod, ABC
  17. import numpy as np
  18. from mindinsight.utils.tensor import TensorUtils
  19. from mindinsight.debugger.common.exceptions.exceptions import DebuggerParamValueError
  20. from mindinsight.debugger.common.log import LOGGER as log
  21. from mindinsight.debugger.common.utils import NUMPY_TYPE_MAP
  22. from mindinsight.debugger.proto.ms_graph_pb2 import DataType
  23. class BaseTensor(ABC):
  24. """Tensor data structure."""
  25. def __init__(self, step=0):
  26. self._step = step
  27. @property
  28. @abstractmethod
  29. def name(self):
  30. """The property of tensor name."""
  31. @property
  32. @abstractmethod
  33. def dtype(self):
  34. """The property of tensor dtype."""
  35. @property
  36. @abstractmethod
  37. def shape(self):
  38. """The property of tensor shape."""
  39. @property
  40. @abstractmethod
  41. def value(self):
  42. """The property of tensor shape."""
  43. @property
  44. def empty(self):
  45. """If the tensor value is valid."""
  46. return self.value is None
  47. @abstractmethod
  48. def get_tensor_serializable_value_by_shape(self, shape=None):
  49. """Get tensor value by shape."""
  50. def _to_dict(self):
  51. """Get tensor info in dict format."""
  52. res = {
  53. 'full_name': self.name,
  54. 'step': self._step,
  55. 'dtype': self.dtype,
  56. 'shape': self.shape,
  57. 'has_prev_step': False
  58. }
  59. return res
  60. def get_basic_info(self):
  61. """Return basic info about tensor info."""
  62. tensor_value = self.value
  63. if not self.shape:
  64. value = tensor_value.tolist() if isinstance(tensor_value, np.ndarray) else tensor_value
  65. else:
  66. value = 'click to view'
  67. res = self._to_dict()
  68. res['value'] = value
  69. return res
  70. def get_full_info(self, shape=None):
  71. """Get tensor info with value."""
  72. res = self._to_dict()
  73. value_info = self.get_tensor_serializable_value_by_shape(shape)
  74. res.update(value_info)
  75. return res
  76. class OpTensor(BaseTensor):
  77. """Tensor data structure for operator Node."""
  78. max_number_data_show_on_ui = 100000
  79. def __init__(self, tensor_proto, step=0):
  80. # the type of tensor_proto is TensorProto
  81. super(OpTensor, self).__init__(step)
  82. self._tensor_proto = tensor_proto
  83. self._value = self.generate_value_from_proto(tensor_proto)
  84. self._stats = None
  85. self._tensor_comparison = None
  86. @property
  87. def name(self):
  88. """The property of tensor name."""
  89. node_name = self._tensor_proto.node_name
  90. slot = self._tensor_proto.slot
  91. return ':'.join([node_name, slot])
  92. @property
  93. def dtype(self):
  94. """The property of tensor dtype."""
  95. tensor_type = DataType.Name(self._tensor_proto.data_type)
  96. return tensor_type
  97. @property
  98. def shape(self):
  99. """The property of tensor shape."""
  100. return list(self._tensor_proto.dims)
  101. @property
  102. def value(self):
  103. """The property of tensor value."""
  104. return self._value
  105. @property
  106. def stats(self):
  107. """The property of tensor stats."""
  108. return self._stats
  109. @stats.setter
  110. def stats(self, stats):
  111. """
  112. Update tensor stats.
  113. Args:
  114. stats (Statistics): Instance of Statistics.
  115. """
  116. self._stats = stats
  117. @property
  118. def tensor_comparison(self):
  119. """The property of tensor_comparison."""
  120. return self._tensor_comparison
  121. def generate_value_from_proto(self, tensor_proto):
  122. """
  123. Generate tensor value from proto.
  124. Args:
  125. tensor_proto (TensorProto): The tensor proto.
  126. Returns:
  127. Union[None, np.ndarray], the value of the tensor.
  128. """
  129. tensor_value = None
  130. if tensor_proto.tensor_content:
  131. tensor_value = tensor_proto.tensor_content
  132. np_type = NUMPY_TYPE_MAP.get(self.dtype)
  133. tensor_value = np.frombuffer(tensor_value, dtype=np_type)
  134. tensor_value = tensor_value.reshape(self.shape)
  135. return tensor_value
  136. def get_tensor_serializable_value_by_shape(self, shape=None):
  137. """
  138. Get tensor value info by shape.
  139. Args:
  140. shape (tuple): The specified range of tensor value.
  141. Returns:
  142. dict, the specified tensor value and value statistics.
  143. """
  144. tensor_value = self.get_tensor_value_by_shape(shape)
  145. res = {}
  146. # the type of tensor_value is one of None, np.ndarray or str
  147. if isinstance(tensor_value, np.ndarray):
  148. res['value'] = tensor_value.tolist()
  149. elif isinstance(tensor_value, str):
  150. res['value'] = tensor_value
  151. else:
  152. res['value'] = None
  153. res['statistics'] = self.get_tensor_statistics()
  154. return res
  155. def get_tensor_statistics(self):
  156. """
  157. Get Tensor statistics.
  158. Returns:
  159. dict, overall statistics.
  160. """
  161. if self.empty:
  162. return {}
  163. if not self.stats:
  164. self.stats = TensorUtils.get_statistics_from_tensor(self.value)
  165. statistics = TensorUtils.get_overall_statistic_dict(self.stats)
  166. return statistics
  167. def update_tensor_comparisons(self, tensor_comparison):
  168. """
  169. Update tensor comparison for tensor.
  170. Args:
  171. tensor_comparison (TensorComparison) instance of TensorComparison.
  172. """
  173. self._tensor_comparison = tensor_comparison
  174. def get_tensor_value_by_shape(self, shape=None):
  175. """
  176. Get tensor value by shape.
  177. Args:
  178. shape (tuple): The specified shape.
  179. Returns:
  180. Union[None, str, numpy.ndarray], the value of parsed tensor.
  181. """
  182. if self._value is None:
  183. log.warning("%s has no value yet.", self.name)
  184. return None
  185. if shape is None or not isinstance(shape, tuple):
  186. log.info("Get the whole tensor value with shape is %s", shape)
  187. return self._value
  188. if len(shape) != len(self.shape):
  189. log.error("Invalid shape. Received: %s, tensor shape: %s", shape, self.shape)
  190. raise DebuggerParamValueError("Invalid shape. Shape unmatched.")
  191. try:
  192. value = self._value[shape]
  193. except IndexError as err:
  194. log.error("Invalid shape. Received: %s, tensor shape: %s", shape, self.shape)
  195. log.exception(err)
  196. raise DebuggerParamValueError("Invalid shape. Shape unmatched.")
  197. if isinstance(value, np.ndarray):
  198. if value.size > self.max_number_data_show_on_ui:
  199. log.info("The tensor size is %d, which is too large to show on UI.", value.size)
  200. value = "Too large to show."
  201. else:
  202. value = np.asarray(value)
  203. return value
  204. class ConstTensor(BaseTensor):
  205. """Tensor data structure for Const Node."""
  206. def __init__(self, const_proto):
  207. # the type of const_proto is NamedValueProto
  208. super(ConstTensor, self).__init__()
  209. self._const_proto = const_proto
  210. self._value = self.generate_value_from_proto(const_proto)
  211. def set_step(self, step):
  212. """Set step value."""
  213. self._step = step
  214. @property
  215. def name(self):
  216. """The property of tensor name."""
  217. return self._const_proto.key + ':0'
  218. @property
  219. def dtype(self):
  220. """The property of tensor dtype."""
  221. return DataType.Name(self._const_proto.value.dtype)
  222. @property
  223. def shape(self):
  224. """The property of tensor shape."""
  225. return []
  226. @property
  227. def value(self):
  228. """The property of tensor shape."""
  229. return self._value
  230. @staticmethod
  231. def generate_value_from_proto(tensor_proto):
  232. """
  233. Generate tensor value from proto.
  234. Args:
  235. tensor_proto (TensorProto): The tensor proto.
  236. Returns:
  237. Union[None, np.ndarray], the value of the tensor.
  238. """
  239. fields = tensor_proto.value.ListFields()
  240. if len(fields) != 2:
  241. log.warning("Unexpected const proto <%s>.\n Please check offline.", tensor_proto)
  242. for field_name, field_value in fields:
  243. if field_name != 'dtype':
  244. return field_value
  245. return None
  246. def get_tensor_serializable_value_by_shape(self, shape=None):
  247. """Get tensor info with value."""
  248. if shape is not None:
  249. log.warning("Invalid shape for const value.")
  250. return self._value