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.

explain_job.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. """ExplainJob."""
  16. import os
  17. from collections import defaultdict
  18. from datetime import datetime
  19. from typing import Union
  20. from mindinsight.explainer.common.enums import PluginNameEnum
  21. from mindinsight.explainer.common.log import logger
  22. from mindinsight.explainer.manager.explain_parser import _ExplainParser
  23. from mindinsight.explainer.manager.event_parse import EventParser
  24. from mindinsight.datavisual.data_access.file_handler import FileHandler
  25. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  26. _NUM_DIGIT = 7
  27. class ExplainJob:
  28. """ExplainJob which manage the record in the summary file."""
  29. def __init__(self,
  30. job_id: str,
  31. summary_dir: str,
  32. create_time: float,
  33. latest_update_time: float):
  34. self._job_id = job_id
  35. self._summary_dir = summary_dir
  36. self._parser = _ExplainParser(summary_dir)
  37. self._event_parser = EventParser(self)
  38. self._latest_update_time = latest_update_time
  39. self._create_time = create_time
  40. self._labels = []
  41. self._metrics = []
  42. self._explainers = []
  43. self._samples_info = {}
  44. self._labels_info = {}
  45. self._explainer_score_dict = defaultdict(list)
  46. self._label_score_dict = defaultdict(dict)
  47. self._overlay_dict = {}
  48. self._image_dict = {}
  49. @property
  50. def all_classes(self):
  51. """
  52. Return a list of label info
  53. Returns:
  54. class_objs (List[ClassObj]): a list of class_objects, each object
  55. contains:
  56. - id (int): label id
  57. - label (str): label name
  58. - sample_count (int): number of samples for each label
  59. """
  60. all_classes_return = []
  61. for label_id, label_info in self._labels_info.items():
  62. single_info = {
  63. 'id': label_id,
  64. 'label': label_info['label'],
  65. 'sample_count': len(label_info['sample_ids'])}
  66. all_classes_return.append(single_info)
  67. return all_classes_return
  68. @property
  69. def explainers(self):
  70. """
  71. Return a list of explainer names
  72. Returns:
  73. list(str), explainer names
  74. """
  75. return self._explainers
  76. @property
  77. def explainer_scores(self):
  78. """Return evaluation results for every explainer."""
  79. merged_scores = []
  80. for explainer, explainer_score_on_metric in self._explainer_score_dict.items():
  81. label_scores = []
  82. for label, label_score_on_metric in self._label_score_dict[explainer].items():
  83. score_single_label = {
  84. 'label': self._labels[label],
  85. 'evaluations': label_score_on_metric,
  86. }
  87. label_scores.append(score_single_label)
  88. merged_scores.append({
  89. 'explainer': explainer,
  90. 'evaluations': explainer_score_on_metric,
  91. 'class_scores': label_scores,
  92. })
  93. return merged_scores
  94. @property
  95. def sample_count(self):
  96. """
  97. Return total number of samples in the job.
  98. Return:
  99. int, total number of samples
  100. """
  101. return len(self._samples_info)
  102. @property
  103. def train_id(self):
  104. """
  105. Return ID of explain job
  106. Returns:
  107. str, id of ExplainJob object
  108. """
  109. return self._job_id
  110. @property
  111. def metrics(self):
  112. """
  113. Return a list of metric names
  114. Returns:
  115. list(str), metric names
  116. """
  117. return self._metrics
  118. @property
  119. def min_confidence(self):
  120. """
  121. Return minimum confidence
  122. Returns:
  123. min_confidence (float):
  124. """
  125. return None
  126. @property
  127. def create_time(self):
  128. """
  129. Return the create time of summary file
  130. Returns:
  131. creation timestamp (float)
  132. """
  133. return self._create_time
  134. @property
  135. def labels(self):
  136. """Return the label contained in the job."""
  137. return self._labels
  138. @property
  139. def latest_update_time(self):
  140. """
  141. Return last modification time stamp of summary file.
  142. Returns:
  143. float, last_modification_time stamp
  144. """
  145. return self._latest_update_time
  146. @latest_update_time.setter
  147. def latest_update_time(self, new_time: Union[float, datetime]):
  148. """
  149. Update the latest_update_time timestamp manually.
  150. Args:
  151. new_time stamp (union[float, datetime]): updated time for the job
  152. """
  153. if isinstance(new_time, datetime):
  154. self._latest_update_time = new_time.timestamp()
  155. elif isinstance(new_time, float):
  156. self._latest_update_time = new_time
  157. else:
  158. raise TypeError('new_time should have type of float or datetime')
  159. @property
  160. def loader_id(self):
  161. """Return the job id."""
  162. return self._job_id
  163. @property
  164. def samples(self):
  165. """Return the information of all samples in the job."""
  166. return self._samples_info
  167. @staticmethod
  168. def get_create_time(file_path: str) -> float:
  169. """Return timestamp of create time of specific path."""
  170. create_time = os.stat(file_path).st_ctime
  171. return create_time
  172. @staticmethod
  173. def get_update_time(file_path: str) -> float:
  174. """Return timestamp of update time of specific path."""
  175. update_time = os.stat(file_path).st_mtime
  176. return update_time
  177. def _initialize_labels_info(self):
  178. """Initialize a dict for labels in the job."""
  179. if self._labels is None:
  180. logger.warning('No labels is provided in job %s', self._job_id)
  181. return
  182. for label_id, label in enumerate(self._labels):
  183. self._labels_info[label_id] = {'label': label,
  184. 'sample_ids': set()}
  185. def _explanation_to_dict(self, explanation, sample_id):
  186. """Transfer the explanation from event to dict storage."""
  187. explainer_name = explanation.explain_method
  188. explain_label = explanation.label
  189. saliency = explanation.heatmap
  190. saliency_id = '{}_{}_{}'.format(
  191. sample_id, explain_label, explainer_name)
  192. explain_info = {
  193. 'explainer': explainer_name,
  194. 'overlay': saliency_id,
  195. }
  196. self._overlay_dict[saliency_id] = saliency
  197. return explain_info
  198. def _image_container_to_dict(self, sample_data):
  199. """Transfer the image container to dict storage."""
  200. sample_id = sample_data.image_id
  201. sample_info = {
  202. 'id': sample_id,
  203. 'name': sample_id,
  204. 'labels': [self._labels_info[x]['label']
  205. for x in sample_data.ground_truth_label],
  206. 'inferences': []}
  207. self._image_dict[sample_id] = sample_data.image_data
  208. ground_truth_labels = list(sample_data.ground_truth_label)
  209. ground_truth_probs = list(sample_data.inference.ground_truth_prob)
  210. predicted_labels = list(sample_data.inference.predicted_label)
  211. predicted_probs = list(sample_data.inference.predicted_prob)
  212. inference_info = {}
  213. for label, prob in zip(
  214. ground_truth_labels + predicted_labels,
  215. ground_truth_probs + predicted_probs):
  216. inference_info[label] = {
  217. 'label': self._labels_info[label]['label'],
  218. 'confidence': round(prob, _NUM_DIGIT),
  219. 'saliency_maps': []}
  220. if EventParser.is_attr_ready(sample_data, 'explanation'):
  221. for explanation in sample_data.explanation:
  222. explanation_dict = self._explanation_to_dict(
  223. explanation, sample_id)
  224. inference_info[explanation.label]['saliency_maps'].append(explanation_dict)
  225. sample_info['inferences'] = list(inference_info.values())
  226. return sample_info
  227. def _import_sample(self, sample):
  228. """Add sample object of given sample id."""
  229. for label_id in sample.ground_truth_label:
  230. self._labels_info[label_id]['sample_ids'].add(sample.image_id)
  231. sample_info = self._image_container_to_dict(sample)
  232. self._samples_info.update({sample_info['id']: sample_info})
  233. def retrieve_image(self, image_id: str):
  234. """
  235. Retrieve image data from the job given image_id.
  236. Return:
  237. string, image data in base64 byte
  238. """
  239. return self._image_dict.get(image_id, None)
  240. def retrieve_overlay(self, overlay_id: str):
  241. """
  242. Retrieve sample map from the job given overlay_id.
  243. Return:
  244. string, saliency_map data in base64 byte
  245. """
  246. return self._overlay_dict.get(overlay_id, None)
  247. def get_all_samples(self):
  248. """
  249. Return a list of sample information cachced in the explain job
  250. Returns:
  251. sample_list (List[SampleObj]): a list of sample objects, each object
  252. consists of:
  253. - id (int): sample id
  254. - name (str): basename of image
  255. - labels (list[str]): list of labels
  256. - inferences list[dict])
  257. """
  258. samples_in_list = list(self._samples_info.values())
  259. return samples_in_list
  260. def _is_metadata_empty(self):
  261. """Check whether metadata is loaded first."""
  262. if not self._explainers or not self._metrics or not self._labels:
  263. return True
  264. return False
  265. def _import_data_from_event(self, event):
  266. """Parse and import data from the event data."""
  267. tags = {
  268. 'image_id': PluginNameEnum.IMAGE_ID,
  269. 'benchmark': PluginNameEnum.BENCHMARK,
  270. 'metadata': PluginNameEnum.METADATA
  271. }
  272. if 'metadata' not in event and self._is_metadata_empty():
  273. raise ValueError('metadata is empty, should write metadata first in the summary.')
  274. for tag in tags:
  275. if tag not in event:
  276. continue
  277. if tag == PluginNameEnum.IMAGE_ID.value:
  278. sample_event = event[tag]
  279. sample_data = self._event_parser.parse_sample(sample_event)
  280. if sample_data is not None:
  281. self._import_sample(sample_data)
  282. continue
  283. if tag == PluginNameEnum.BENCHMARK.value:
  284. benchmark_event = event[tag].benchmark
  285. explain_score_dict, label_score_dict = EventParser.parse_benchmark(benchmark_event)
  286. self._update_benchmark(explain_score_dict, label_score_dict)
  287. elif tag == PluginNameEnum.METADATA.value:
  288. metadata_event = event[tag].metadata
  289. metadata = EventParser.parse_metadata(metadata_event)
  290. self._explainers, self._metrics, self._labels = metadata
  291. self._initialize_labels_info()
  292. def load(self):
  293. """
  294. Start loading data from parser.
  295. """
  296. valid_file_names = []
  297. for filename in FileHandler.list_dir(self._summary_dir):
  298. if FileHandler.is_file(
  299. FileHandler.join(self._summary_dir, filename)):
  300. valid_file_names.append(filename)
  301. if not valid_file_names:
  302. raise TrainJobNotExistError('No summary file found in %s, explain job will be delete.' % self._summary_dir)
  303. is_end = False
  304. while not is_end:
  305. is_clean, is_end, event = self._parser.parse_explain(valid_file_names)
  306. if is_clean:
  307. logger.info('Summary file in %s update, reload the clean the loaded data.', self._summary_dir)
  308. self._clean_job()
  309. if event:
  310. self._import_data_from_event(event)
  311. def _clean_job(self):
  312. """Clean the cached data in job."""
  313. self._latest_update_time = ExplainJob.get_update_time(self._summary_dir)
  314. self._create_time = ExplainJob.get_update_time(self._summary_dir)
  315. self._labels.clear()
  316. self._metrics.clear()
  317. self._explainers.clear()
  318. self._samples_info.clear()
  319. self._labels_info.clear()
  320. self._explainer_score_dict.clear()
  321. self._label_score_dict.clear()
  322. self._overlay_dict.clear()
  323. self._image_dict.clear()
  324. self._event_parser.clear()
  325. def _update_benchmark(self, explainer_score_dict, labels_score_dict):
  326. """Update the benchmark info."""
  327. for explainer, score in explainer_score_dict.items():
  328. self._explainer_score_dict[explainer].extend(score)
  329. for explainer, score in labels_score_dict.items():
  330. for label, score_of_label in score.items():
  331. self._label_score_dict[explainer][label] = (self._label_score_dict[explainer].get(label, [])
  332. + score_of_label)