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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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.debugger.common.exceptions.exceptions import DebuggerParamValueError
  19. from mindinsight.debugger.common.log import LOGGER as log
  20. from mindinsight.debugger.common.utils import NUMPY_TYPE_MAP
  21. from mindinsight.debugger.proto.ms_graph_pb2 import DataType
  22. from mindinsight.utils.tensor import TensorUtils
  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. """
  98. Tensor data structure for operator Node.
  99. Args:
  100. tensor_proto (TensorProto): Tensor proto contains tensor basic info.
  101. tensor_content (byte): Tensor content value in byte format.
  102. step (int): The step of the tensor.
  103. """
  104. max_number_data_show_on_ui = 100000
  105. def __init__(self, tensor_proto, tensor_content, step=0):
  106. # the type of tensor_proto is TensorProto
  107. super(OpTensor, self).__init__(step)
  108. self._tensor_proto = tensor_proto
  109. self._value = self.to_numpy(tensor_content)
  110. self._stats = None
  111. self._tensor_comparison = None
  112. @property
  113. def name(self):
  114. """The property of tensor name."""
  115. node_name = self._tensor_proto.node_name
  116. slot = self._tensor_proto.slot
  117. return ':'.join([node_name, slot])
  118. @property
  119. def dtype(self):
  120. """The property of tensor dtype."""
  121. tensor_type = DataType.Name(self._tensor_proto.data_type)
  122. return tensor_type
  123. @property
  124. def shape(self):
  125. """The property of tensor shape."""
  126. return list(self._tensor_proto.dims)
  127. @property
  128. def value(self):
  129. """The property of tensor value."""
  130. return self._value
  131. @property
  132. def stats(self):
  133. """The property of tensor stats."""
  134. return self._stats
  135. @stats.setter
  136. def stats(self, stats):
  137. """
  138. Update tensor stats.
  139. Args:
  140. stats (Statistics): Instance of Statistics.
  141. """
  142. self._stats = stats
  143. @property
  144. def tensor_comparison(self):
  145. """The property of tensor_comparison."""
  146. return self._tensor_comparison
  147. def to_numpy(self, tensor_content):
  148. """
  149. Construct tensor content from byte to numpy.
  150. Args:
  151. tensor_content (byte): The tensor content.
  152. Returns:
  153. Union[None, np.ndarray], the value of the tensor.
  154. """
  155. tensor_value = None
  156. if tensor_content:
  157. np_type = NUMPY_TYPE_MAP.get(self.dtype)
  158. tensor_value = np.frombuffer(tensor_content, dtype=np_type)
  159. tensor_value = tensor_value.reshape(self.shape)
  160. return tensor_value
  161. def get_tensor_statistics(self):
  162. """
  163. Get Tensor statistics.
  164. Returns:
  165. dict, overall statistics.
  166. """
  167. if self.empty:
  168. return {}
  169. if not self.stats:
  170. self.stats = TensorUtils.get_statistics_from_tensor(self.value)
  171. statistics = TensorUtils.get_overall_statistic_dict(self.stats)
  172. return statistics
  173. def update_tensor_comparisons(self, tensor_comparison):
  174. """
  175. Update tensor comparison for tensor.
  176. Args:
  177. tensor_comparison (TensorComparison) instance of TensorComparison.
  178. """
  179. self._tensor_comparison = tensor_comparison
  180. def get_tensor_value_by_shape(self, shape=None):
  181. """
  182. Get tensor value by shape.
  183. Args:
  184. shape (tuple): The specified shape.
  185. Returns:
  186. Union[None, str, numpy.ndarray], the value of parsed tensor.
  187. """
  188. if self._value is None:
  189. log.warning("%s has no value yet.", self.name)
  190. return None
  191. if shape is None or not isinstance(shape, tuple):
  192. log.info("Get the whole tensor value with shape is %s", shape)
  193. return self._value
  194. if len(shape) != len(self.shape):
  195. log.error("Invalid shape. Received: %s, tensor shape: %s", shape, self.shape)
  196. raise DebuggerParamValueError("Invalid shape. Shape unmatched.")
  197. try:
  198. value = self._value[shape]
  199. except IndexError as err:
  200. log.error("Invalid shape. Received: %s, tensor shape: %s", shape, self.shape)
  201. log.exception(err)
  202. raise DebuggerParamValueError("Invalid shape. Shape unmatched.")
  203. if isinstance(value, np.ndarray):
  204. if value.size > self.max_number_data_show_on_ui:
  205. log.info("The tensor size is %d, which is too large to show on UI.", value.size)
  206. value = "Too large to show."
  207. else:
  208. value = np.asarray(value)
  209. return value
  210. class ConstTensor(BaseTensor):
  211. """Tensor data structure for Const Node."""
  212. _STRING_TYPE = 'DT_STRING'
  213. def __init__(self, const_proto):
  214. # the type of const_proto is NamedValueProto
  215. super(ConstTensor, self).__init__()
  216. self._const_proto = const_proto
  217. self._value = self.generate_value_from_proto(const_proto)
  218. def set_step(self, step):
  219. """Set step value."""
  220. self._step = step
  221. @property
  222. def name(self):
  223. """The property of tensor name."""
  224. return self._const_proto.key + ':0'
  225. @property
  226. def dtype(self):
  227. """The property of tensor dtype."""
  228. return DataType.Name(self._const_proto.value.dtype)
  229. @property
  230. def shape(self):
  231. """The property of tensor shape."""
  232. return []
  233. @property
  234. def value(self):
  235. """The property of tensor shape."""
  236. return self._value
  237. def generate_value_from_proto(self, tensor_proto):
  238. """
  239. Generate tensor value from proto.
  240. Args:
  241. tensor_proto (TensorProto): The tensor proto.
  242. Returns:
  243. Union[None, str, np.ndarray], the value of the tensor.
  244. """
  245. fields = tensor_proto.value.ListFields()
  246. if len(fields) != 2:
  247. log.warning("Unexpected const proto <%s>.\n Please check offline.", tensor_proto)
  248. tensor_value = None
  249. for field_obj, field_value in fields:
  250. if field_obj.name != 'dtype':
  251. tensor_value = field_value
  252. break
  253. if tensor_value is not None and self.dtype != self._STRING_TYPE:
  254. tensor_value = np.array(tensor_value, dtype=NUMPY_TYPE_MAP.get(self.dtype))
  255. return tensor_value
  256. def get_tensor_value_by_shape(self, shape=None):
  257. """
  258. Get tensor value by shape.
  259. Args:
  260. shape (tuple): The specified shape.
  261. Returns:
  262. Union[None, str, int, float], the value of parsed tensor.
  263. """
  264. if shape:
  265. log.warning("Invalid shape for const value.")
  266. return self._value
  267. def get_tensor_statistics(self):
  268. """
  269. Get Tensor statistics.
  270. Returns:
  271. dict, overall statistics.
  272. """
  273. if self.empty or self.dtype == self._STRING_TYPE:
  274. return {}
  275. stats = TensorUtils.get_statistics_from_tensor(self.value)
  276. statistics = TensorUtils.get_overall_statistic_dict(stats)
  277. return statistics