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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. res['statistics'] = self.get_tensor_statistics()
  152. return res
  153. def get_tensor_statistics(self):
  154. """
  155. Get Tensor statistics.
  156. Returns:
  157. dict, overall statistics.
  158. """
  159. if self.empty:
  160. return {}
  161. if not self.stats:
  162. self.stats = TensorUtils.get_statistics_from_tensor(self.value)
  163. statistics = TensorUtils.get_overall_statistic_dict(self.stats)
  164. return statistics
  165. def update_tensor_comparisons(self, tensor_comparison):
  166. """
  167. Update tensor comparison for tensor.
  168. Args:
  169. tensor_comparison (TensorComparison) instance of TensorComparison.
  170. """
  171. self._tensor_comparison = tensor_comparison
  172. def get_tensor_value_by_shape(self, shape=None):
  173. """
  174. Get tensor value by shape.
  175. Args:
  176. shape (tuple): The specified shape.
  177. Returns:
  178. Union[None, str, numpy.ndarray], the value of parsed tensor.
  179. """
  180. if self._value is None:
  181. log.warning("%s has no value yet.", self.name)
  182. return None
  183. if shape is None or not isinstance(shape, tuple):
  184. log.info("Get the whole tensor value with shape is %s", shape)
  185. return self._value
  186. if len(shape) != len(self.shape):
  187. log.error("Invalid shape. Received: %s, tensor shape: %s", shape, self.shape)
  188. raise DebuggerParamValueError("Invalid shape. Shape unmatched.")
  189. try:
  190. value = self._value[shape]
  191. except IndexError as err:
  192. log.error("Invalid shape. Received: %s, tensor shape: %s", shape, self.shape)
  193. log.exception(err)
  194. raise DebuggerParamValueError("Invalid shape. Shape unmatched.")
  195. if isinstance(value, np.ndarray):
  196. if value.size > self.max_number_data_show_on_ui:
  197. log.info("The tensor size is %d, which is too large to show on UI.", value.size)
  198. value = "Too large to show."
  199. else:
  200. value = np.asarray(value)
  201. return value
  202. class ConstTensor(BaseTensor):
  203. """Tensor data structure for Const Node."""
  204. def __init__(self, const_proto):
  205. # the type of const_proto is NamedValueProto
  206. super(ConstTensor, self).__init__()
  207. self._const_proto = const_proto
  208. self._value = self.generate_value_from_proto(const_proto)
  209. def set_step(self, step):
  210. """Set step value."""
  211. self._step = step
  212. @property
  213. def name(self):
  214. """The property of tensor name."""
  215. return self._const_proto.key + ':0'
  216. @property
  217. def dtype(self):
  218. """The property of tensor dtype."""
  219. return DataType.Name(self._const_proto.value.dtype)
  220. @property
  221. def shape(self):
  222. """The property of tensor shape."""
  223. return []
  224. @property
  225. def value(self):
  226. """The property of tensor shape."""
  227. return self._value
  228. @staticmethod
  229. def generate_value_from_proto(tensor_proto):
  230. """
  231. Generate tensor value from proto.
  232. Args:
  233. tensor_proto (TensorProto): The tensor proto.
  234. Returns:
  235. Union[None, np.ndarray], the value of the tensor.
  236. """
  237. fields = tensor_proto.value.ListFields()
  238. if len(fields) != 2:
  239. log.warning("Unexpected const proto <%s>.\n Please check offline.", tensor_proto)
  240. for field_name, field_value in fields:
  241. if field_name != 'dtype':
  242. return field_value
  243. return None
  244. def get_tensor_serializable_value_by_shape(self, shape=None):
  245. """Get tensor info with value."""
  246. if shape is not None:
  247. log.warning("Invalid shape for const value.")
  248. return self._value