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_loader.py 25 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. """ExplainLoader."""
  16. from collections import defaultdict
  17. from enum import Enum
  18. import math
  19. import os
  20. import re
  21. import threading
  22. from datetime import datetime
  23. from typing import Dict, Iterable, List, Optional, Union
  24. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  25. from mindinsight.datavisual.data_access.file_handler import FileHandler
  26. from mindinsight.explainer.common.enums import ExplainFieldsEnum
  27. from mindinsight.explainer.common.log import logger
  28. from mindinsight.explainer.manager.explain_parser import ExplainParser
  29. from mindinsight.utils.exceptions import ParamValueError
  30. _NAN_CONSTANT = 'NaN'
  31. _NUM_DIGITS = 6
  32. _EXPLAIN_FIELD_NAMES = [
  33. ExplainFieldsEnum.SAMPLE_ID,
  34. ExplainFieldsEnum.BENCHMARK,
  35. ExplainFieldsEnum.METADATA,
  36. ]
  37. _SAMPLE_FIELD_NAMES = [
  38. ExplainFieldsEnum.GROUND_TRUTH_LABEL,
  39. ExplainFieldsEnum.INFERENCE,
  40. ExplainFieldsEnum.EXPLANATION,
  41. ]
  42. class _LoaderStatus(Enum):
  43. STOP = 'STOP'
  44. LOADING = 'LOADING'
  45. def _round(score):
  46. """Take round of a number to given precision."""
  47. try:
  48. return round(score, _NUM_DIGITS)
  49. except TypeError:
  50. return score
  51. class ExplainLoader:
  52. """ExplainLoader which manage the record in the summary file."""
  53. def __init__(self,
  54. loader_id: str,
  55. summary_dir: str):
  56. self._parser = ExplainParser(summary_dir)
  57. self._loader_info = {
  58. 'loader_id': loader_id,
  59. 'summary_dir': summary_dir,
  60. 'create_time': os.stat(summary_dir).st_ctime,
  61. 'update_time': os.stat(summary_dir).st_mtime,
  62. 'query_time': os.stat(summary_dir).st_ctime,
  63. 'uncertainty_enabled': False,
  64. }
  65. self._samples = defaultdict(dict)
  66. self._metadata = {'explainers': [], 'metrics': [], 'labels': []}
  67. self._benchmark = {'explainer_score': defaultdict(dict), 'label_score': defaultdict(dict)}
  68. self._status = _LoaderStatus.STOP.value
  69. self._status_mutex = threading.Lock()
  70. @property
  71. def all_classes(self) -> List[Dict]:
  72. """
  73. Return a list of detailed label information, including label id, label name and sample count of each label.
  74. Returns:
  75. list[dict], a list of dict, each dict contains:
  76. - id (int): label id
  77. - label (str): label name
  78. - sample_count (int): number of samples for each label
  79. """
  80. sample_count_per_label = defaultdict(int)
  81. samples_copy = self._samples.copy()
  82. for sample in samples_copy.values():
  83. if sample.get('image', False) and sample.get('ground_truth_label', False):
  84. for label in sample['ground_truth_label']:
  85. sample_count_per_label[label] += 1
  86. all_classes_return = []
  87. for label_id, label_name in enumerate(self._metadata['labels']):
  88. single_info = {
  89. 'id': label_id,
  90. 'label': label_name,
  91. 'sample_count': sample_count_per_label[label_id]
  92. }
  93. all_classes_return.append(single_info)
  94. return all_classes_return
  95. @property
  96. def query_time(self) -> float:
  97. """Return query timestamp of explain loader."""
  98. return self._loader_info['query_time']
  99. @query_time.setter
  100. def query_time(self, new_time: Union[datetime, float]):
  101. """
  102. Update the query_time timestamp manually.
  103. Args:
  104. new_time (datetime.datetime or float): Updated query_time for the explain loader.
  105. """
  106. if isinstance(new_time, datetime):
  107. self._loader_info['query_time'] = new_time.timestamp()
  108. elif isinstance(new_time, float):
  109. self._loader_info['query_time'] = new_time
  110. else:
  111. raise TypeError('new_time should have type of datetime.datetime or float, but receive {}'
  112. .format(type(new_time)))
  113. @property
  114. def create_time(self) -> float:
  115. """Return the create timestamp of summary file."""
  116. return self._loader_info['create_time']
  117. @create_time.setter
  118. def create_time(self, new_time: Union[datetime, float]):
  119. """
  120. Update the create_time manually
  121. Args:
  122. new_time (datetime.datetime or float): Updated create_time of summary_file.
  123. """
  124. if isinstance(new_time, datetime):
  125. self._loader_info['create_time'] = new_time.timestamp()
  126. elif isinstance(new_time, float):
  127. self._loader_info['create_time'] = new_time
  128. else:
  129. raise TypeError('new_time should have type of datetime.datetime or float, but receive {}'
  130. .format(type(new_time)))
  131. @property
  132. def explainers(self) -> List[str]:
  133. """Return a list of explainer names recorded in the summary file."""
  134. return self._metadata['explainers']
  135. @property
  136. def explainer_scores(self) -> List[Dict]:
  137. """
  138. Return evaluation results for every explainer.
  139. Returns:
  140. list[dict], A list of evaluation results of each explainer. Each item contains:
  141. - explainer (str): Name of evaluated explainer.
  142. - evaluations (list[dict]): A list of evaluation results by different metrics.
  143. - class_scores (list[dict]): A list of evaluation results on different labels.
  144. Each item in the evaluations contains:
  145. - metric (str): name of metric method
  146. - score (float): evaluation result
  147. Each item in the class_scores contains:
  148. - label (str): Name of label
  149. - evaluations (list[dict]): A list of evaluation results on different labels by different metrics.
  150. Each item in evaluations contains:
  151. - metric (str): Name of metric method
  152. - score (float): Evaluation scores of explainer on specific label by the metric.
  153. """
  154. explainer_scores = []
  155. for explainer, explainer_score_on_metric in self._benchmark['explainer_score'].copy().items():
  156. metric_scores = [{'metric': metric, 'score': _round(score)}
  157. for metric, score in explainer_score_on_metric.items()]
  158. label_scores = []
  159. for label, label_score_on_metric in self._benchmark['label_score'][explainer].copy().items():
  160. score_of_single_label = {
  161. 'label': self._metadata['labels'][label],
  162. 'evaluations': [
  163. {'metric': metric, 'score': _round(score)} for metric, score in label_score_on_metric.items()
  164. ],
  165. }
  166. label_scores.append(score_of_single_label)
  167. explainer_scores.append({
  168. 'explainer': explainer,
  169. 'evaluations': metric_scores,
  170. 'class_scores': label_scores,
  171. })
  172. return explainer_scores
  173. @property
  174. def labels(self) -> List[str]:
  175. """Return the label recorded in the summary."""
  176. return self._metadata['labels']
  177. @property
  178. def metrics(self) -> List[str]:
  179. """Return a list of metric names recorded in the summary file."""
  180. return self._metadata['metrics']
  181. @property
  182. def min_confidence(self) -> Optional[float]:
  183. """Return minimum confidence used to filter the predicted labels."""
  184. return None
  185. @property
  186. def sample_count(self) -> int:
  187. """
  188. Return total number of samples in the loader.
  189. Since the loader only return available samples (i.e. with original image data and ground_truth_label loaded in
  190. cache), the returned count only takes the available samples into account.
  191. Return:
  192. int, total number of available samples in the loading job.
  193. """
  194. sample_count = 0
  195. samples_copy = self._samples.copy()
  196. for sample in samples_copy.values():
  197. if sample.get('image', False) and sample.get('ground_truth_label', False):
  198. sample_count += 1
  199. return sample_count
  200. @property
  201. def samples(self) -> List[Dict]:
  202. """Return the information of all samples in the job."""
  203. return self.get_all_samples()
  204. @property
  205. def train_id(self) -> str:
  206. """Return ID of explain loader."""
  207. return self._loader_info['loader_id']
  208. @property
  209. def uncertainty_enabled(self):
  210. """Whether uncertainty is enabled."""
  211. return self._loader_info['uncertainty_enabled']
  212. @property
  213. def update_time(self) -> float:
  214. """Return latest modification timestamp of summary file."""
  215. return self._loader_info['update_time']
  216. @update_time.setter
  217. def update_time(self, new_time: Union[datetime, float]):
  218. """
  219. Update the update_time manually.
  220. Args:
  221. new_time stamp (datetime.datetime or float): Updated time for the summary file.
  222. """
  223. if isinstance(new_time, datetime):
  224. self._loader_info['update_time'] = new_time.timestamp()
  225. elif isinstance(new_time, float):
  226. self._loader_info['update_time'] = new_time
  227. else:
  228. raise TypeError('new_time should have type of datetime.datetime or float, but receive {}'
  229. .format(type(new_time)))
  230. def load(self):
  231. """Start loading data from the latest summary file to the loader."""
  232. self.status = _LoaderStatus.LOADING.value
  233. filenames = []
  234. for filename in FileHandler.list_dir(self._loader_info['summary_dir']):
  235. if FileHandler.is_file(FileHandler.join(self._loader_info['summary_dir'], filename)):
  236. filenames.append(filename)
  237. filenames = ExplainLoader._filter_files(filenames)
  238. if not filenames:
  239. raise TrainJobNotExistError('No summary file found in %s, explain job will be delete.'
  240. % self._loader_info['summary_dir'])
  241. is_end = False
  242. while not is_end and self.status != _LoaderStatus.STOP.value:
  243. file_changed, is_end, event_dict = self._parser.list_events(filenames)
  244. if file_changed:
  245. logger.info('Summary file in %s update, reload the data in the summary.',
  246. self._loader_info['summary_dir'])
  247. self._clear_job()
  248. if event_dict:
  249. self._import_data_from_event(event_dict)
  250. @property
  251. def status(self):
  252. """Get the status of this class with lock."""
  253. with self._status_mutex:
  254. return self._status
  255. @status.setter
  256. def status(self, status):
  257. """Set the status of this class with lock."""
  258. with self._status_mutex:
  259. self._status = status
  260. def stop(self):
  261. """Stop load data."""
  262. self.status = _LoaderStatus.STOP.value
  263. def get_all_samples(self) -> List[Dict]:
  264. """
  265. Return a list of sample information cachced in the explain job
  266. Returns:
  267. sample_list (List[SampleObj]): a list of sample objects, each object
  268. consists of:
  269. - id (int): sample id
  270. - name (str): basename of image
  271. - labels (list[str]): list of labels
  272. - inferences list[dict])
  273. """
  274. returned_samples = []
  275. samples_copy = self._samples.copy()
  276. for sample_id, sample_info in samples_copy.items():
  277. if not sample_info.get('image', False) and not sample_info.get('ground_truth_label', False):
  278. continue
  279. returned_sample = {
  280. 'id': sample_id,
  281. 'name': str(sample_id),
  282. 'image': sample_info['image'],
  283. 'labels': [self._metadata['labels'][i] for i in sample_info['ground_truth_label']],
  284. }
  285. # Check whether the sample has valid label-prob pairs.
  286. if not ExplainLoader._is_inference_valid(sample_info):
  287. continue
  288. inferences = {}
  289. for label, prob in zip(sample_info['ground_truth_label'] + sample_info['predicted_label'],
  290. sample_info['ground_truth_prob'] + sample_info['predicted_prob']):
  291. inferences[label] = {
  292. 'label': self._metadata['labels'][label],
  293. 'confidence': _round(prob),
  294. 'saliency_maps': []
  295. }
  296. if sample_info['ground_truth_prob_sd'] or sample_info['predicted_prob_sd']:
  297. for label, std, low, high in zip(
  298. sample_info['ground_truth_label'] + sample_info['predicted_label'],
  299. sample_info['ground_truth_prob_sd'] + sample_info['predicted_prob_sd'],
  300. sample_info['ground_truth_prob_itl95_low'] + sample_info['predicted_prob_itl95_low'],
  301. sample_info['ground_truth_prob_itl95_hi'] + sample_info['predicted_prob_itl95_hi']
  302. ):
  303. inferences[label]['confidence_sd'] = _round(std)
  304. inferences[label]['confidence_itl95'] = [_round(low), _round(high)]
  305. for explainer, label_heatmap_path_dict in sample_info['explanation'].items():
  306. for label, heatmap_path in label_heatmap_path_dict.items():
  307. if label in inferences:
  308. inferences[label]['saliency_maps'].append({'explainer': explainer, 'overlay': heatmap_path})
  309. returned_sample['inferences'] = list(inferences.values())
  310. returned_samples.append(returned_sample)
  311. return returned_samples
  312. def _import_data_from_event(self, event_dict: Dict):
  313. """Parse and import data from the event data."""
  314. if 'metadata' not in event_dict and self._is_metadata_empty():
  315. raise ParamValueError('metadata is incomplete, should write metadata first in the summary.')
  316. for tag, event in event_dict.items():
  317. if tag == ExplainFieldsEnum.METADATA.value:
  318. self._import_metadata_from_event(event.metadata)
  319. elif tag == ExplainFieldsEnum.BENCHMARK.value:
  320. self._import_benchmark_from_event(event.benchmark)
  321. elif tag == ExplainFieldsEnum.SAMPLE_ID.value:
  322. self._import_sample_from_event(event)
  323. else:
  324. logger.info('Unknown ExplainField: %s.', tag)
  325. def _is_metadata_empty(self):
  326. """Check whether metadata is completely loaded first."""
  327. if not self._metadata['labels']:
  328. return True
  329. return False
  330. def _import_metadata_from_event(self, metadata_event):
  331. """Import the metadata from event into loader."""
  332. def take_union(existed_list, imported_data):
  333. """Take union of existed_list and imported_data."""
  334. if isinstance(imported_data, Iterable):
  335. for sample in imported_data:
  336. if sample not in existed_list:
  337. existed_list.append(sample)
  338. take_union(self._metadata['explainers'], metadata_event.explain_method)
  339. take_union(self._metadata['metrics'], metadata_event.benchmark_method)
  340. take_union(self._metadata['labels'], metadata_event.label)
  341. def _import_benchmark_from_event(self, benchmarks):
  342. """
  343. Parse the benchmark event.
  344. Benchmark data are separated into 'explainer_score' and 'label_score'. 'explainer_score' contains overall
  345. evaluation results of each explainer by different metrics, while 'label_score' additionally divides the results
  346. w.r.t different labels.
  347. The structure of self._benchmark['explainer_score'] demonstrates below:
  348. {
  349. explainer_1: {metric_name_1: score_1, ...},
  350. explainer_2: {metric_name_1: score_1, ...},
  351. ...
  352. }
  353. The structure of self._benchmark['label_score'] is:
  354. {
  355. explainer_1: {label_id: {metric_1: score_1, metric_2: score_2, ...}, ...},
  356. explainer_2: {label_id: {metric_1: score_1, metric_2: score_2, ...}, ...},
  357. ...
  358. }
  359. Args:
  360. benchmarks (benchmark_container): Parsed benchmarks data from summary file.
  361. """
  362. explainer_score = self._benchmark['explainer_score']
  363. label_score = self._benchmark['label_score']
  364. for benchmark in benchmarks:
  365. explainer = benchmark.explain_method
  366. metric = benchmark.benchmark_method
  367. metric_score = benchmark.total_score
  368. label_score_event = benchmark.label_score
  369. explainer_score[explainer][metric] = _NAN_CONSTANT if math.isnan(metric_score) else metric_score
  370. new_label_score_dict = ExplainLoader._score_event_to_dict(label_score_event, metric)
  371. for label, scores_of_metric in new_label_score_dict.items():
  372. if label not in label_score[explainer]:
  373. label_score[explainer][label] = {}
  374. label_score[explainer][label].update(scores_of_metric)
  375. def _import_sample_from_event(self, sample):
  376. """
  377. Parse the sample event.
  378. Detailed data of each sample are store in self._samples, identified by sample_id. Each sample data are stored
  379. in the following structure.
  380. - ground_truth_labels (list[int]): A list of ground truth labels of the sample.
  381. - ground_truth_probs (list[float]): A list of confidences of ground-truth label from black-box model.
  382. - predicted_labels (list[int]): A list of predicted labels from the black-box model.
  383. - predicted_probs (list[int]): A list of confidences w.r.t the predicted labels.
  384. - explanations (dict): Explanations is a dictionary where the each explainer name mapping to a dictionary
  385. of saliency maps. The structure of explanations demonstrates below:
  386. {
  387. explainer_name_1: {label_1: saliency_id_1, label_2: saliency_id_2, ...},
  388. explainer_name_2: {label_1: saliency_id_1, label_2: saliency_id_2, ...},
  389. ...
  390. }
  391. """
  392. if getattr(sample, 'sample_id', None) is None:
  393. raise ParamValueError('sample_event has no sample_id')
  394. sample_id = sample.sample_id
  395. samples_copy = self._samples.copy()
  396. if sample_id not in samples_copy:
  397. self._samples[sample_id] = {
  398. 'ground_truth_label': [],
  399. 'ground_truth_prob': [],
  400. 'ground_truth_prob_sd': [],
  401. 'ground_truth_prob_itl95_low': [],
  402. 'ground_truth_prob_itl95_hi': [],
  403. 'predicted_label': [],
  404. 'predicted_prob': [],
  405. 'predicted_prob_sd': [],
  406. 'predicted_prob_itl95_low': [],
  407. 'predicted_prob_itl95_hi': [],
  408. 'explanation': defaultdict(dict)
  409. }
  410. if sample.image_path:
  411. self._samples[sample_id]['image'] = sample.image_path
  412. for tag in _SAMPLE_FIELD_NAMES:
  413. if tag == ExplainFieldsEnum.GROUND_TRUTH_LABEL:
  414. self._samples[sample_id]['ground_truth_label'].extend(list(sample.ground_truth_label))
  415. elif tag == ExplainFieldsEnum.INFERENCE:
  416. self._import_inference_from_event(sample, sample_id)
  417. else:
  418. self._import_explanation_from_event(sample, sample_id)
  419. def _import_inference_from_event(self, event, sample_id):
  420. """Parse the inference event."""
  421. inference = event.inference
  422. self._samples[sample_id]['ground_truth_prob'].extend(list(inference.ground_truth_prob))
  423. self._samples[sample_id]['ground_truth_prob_sd'].extend(list(inference.ground_truth_prob_sd))
  424. self._samples[sample_id]['ground_truth_prob_itl95_low'].extend(list(inference.ground_truth_prob_itl95_low))
  425. self._samples[sample_id]['ground_truth_prob_itl95_hi'].extend(list(inference.ground_truth_prob_itl95_hi))
  426. self._samples[sample_id]['predicted_label'].extend(list(inference.predicted_label))
  427. self._samples[sample_id]['predicted_prob'].extend(list(inference.predicted_prob))
  428. self._samples[sample_id]['predicted_prob_sd'].extend(list(inference.predicted_prob_sd))
  429. self._samples[sample_id]['predicted_prob_itl95_low'].extend(list(inference.predicted_prob_itl95_low))
  430. self._samples[sample_id]['predicted_prob_itl95_hi'].extend(list(inference.predicted_prob_itl95_hi))
  431. if self._samples[sample_id]['ground_truth_prob_sd'] or self._samples[sample_id]['predicted_prob_sd']:
  432. self._loader_info['uncertainty_enabled'] = True
  433. def _import_explanation_from_event(self, event, sample_id):
  434. """Parse the explanation event."""
  435. if self._samples[sample_id]['explanation'] is None:
  436. self._samples[sample_id]['explanation'] = defaultdict(dict)
  437. sample_explanation = self._samples[sample_id]['explanation']
  438. for explanation_item in event.explanation:
  439. explainer = explanation_item.explain_method
  440. label = explanation_item.label
  441. sample_explanation[explainer][label] = explanation_item.heatmap_path
  442. def _clear_job(self):
  443. """Clear the cached data and update the time info of the loader."""
  444. self._samples.clear()
  445. self._loader_info['create_time'] = os.stat(self._loader_info['summary_dir']).st_ctime
  446. self._loader_info['update_time'] = os.stat(self._loader_info['summary_dir']).st_mtime
  447. self._loader_info['query_time'] = max(self._loader_info['update_time'], self._loader_info['query_time'])
  448. def clear_inner_dict(outer_dict):
  449. """Clear the inner structured data of the given dict."""
  450. for item in outer_dict.values():
  451. item.clear()
  452. map(clear_inner_dict, [self._metadata, self._benchmark])
  453. @staticmethod
  454. def _filter_files(filenames):
  455. """
  456. Gets a list of summary files.
  457. Args:
  458. filenames (list[str]): File name list, like [filename1, filename2].
  459. Returns:
  460. list[str], filename list.
  461. """
  462. return list(filter(
  463. lambda filename: (re.search(r'summary\.\d+', filename) and filename.endswith("_explain")), filenames))
  464. @staticmethod
  465. def _is_inference_valid(sample):
  466. """
  467. Check whether the inference data is empty or have the same length.
  468. If probs have different length with the labels, it can be confusing when assigning each prob to label.
  469. '_is_inference_valid' returns True only when the data size of match to each other. Note that prob data could be
  470. empty, so empty prob will pass the check.
  471. """
  472. ground_truth_len = len(sample['ground_truth_label'])
  473. for name in ['ground_truth_prob', 'ground_truth_prob_sd',
  474. 'ground_truth_prob_itl95_low', 'ground_truth_prob_itl95_hi']:
  475. if sample[name] and len(sample[name]) != ground_truth_len:
  476. logger.info('Length of %s not match the ground_truth_label. Length of ground_truth_label: %d,'
  477. 'length of %s: %d', name, ground_truth_len, name, len(sample[name]))
  478. return False
  479. predicted_len = len(sample['predicted_label'])
  480. for name in ['predicted_prob', 'predicted_prob_sd',
  481. 'predicted_prob_itl95_low', 'predicted_prob_itl95_hi']:
  482. if sample[name] and len(sample[name]) != predicted_len:
  483. logger.info('Length of %s not match the predicted_labels. Length of predicted_label: %d,'
  484. 'length of %s: %d', name, predicted_len, name, len(sample[name]))
  485. return False
  486. return True
  487. @staticmethod
  488. def _score_event_to_dict(label_score_event, metric) -> Dict:
  489. """Transfer metric scores per label to pre-defined structure."""
  490. new_label_score_dict = defaultdict(dict)
  491. for label_id, label_score in enumerate(label_score_event):
  492. new_label_score_dict[label_id][metric] = _NAN_CONSTANT if math.isnan(label_score) else label_score
  493. return new_label_score_dict