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 10 kB

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