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.

data_manager.py 33 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. # Copyright 2019 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. """
  16. Management of all events data.
  17. This module exists to all loaders.
  18. It can read events data through the DataLoader.
  19. This module also acts as a thread pool manager.
  20. """
  21. import abc
  22. import datetime
  23. import enum
  24. import threading
  25. import time
  26. import os
  27. from typing import Iterable, Optional
  28. from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
  29. from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  30. from mindinsight.conf import settings
  31. from mindinsight.datavisual.common import exceptions
  32. from mindinsight.datavisual.common.log import logger
  33. from mindinsight.datavisual.common.enums import DataManagerStatus
  34. from mindinsight.datavisual.common.enums import PluginNameEnum
  35. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  36. from mindinsight.datavisual.data_transform.loader_generators.loader_generator import MAX_DATA_LOADER_SIZE
  37. from mindinsight.datavisual.data_transform.loader_generators.data_loader_generator import DataLoaderGenerator
  38. from mindinsight.utils.exceptions import MindInsightException
  39. from mindinsight.utils.exceptions import ParamValueError
  40. @enum.unique
  41. class _CacheStatus(enum.Enum):
  42. """Train job cache status."""
  43. NOT_IN_CACHE = "NOT_IN_CACHE"
  44. CACHING = "CACHING"
  45. CACHED = "CACHED"
  46. class _BasicTrainJob:
  47. """
  48. Basic info about train job.
  49. Args:
  50. train_id (str): Id of the train job.
  51. abs_summary_base_dir (str): The canonical path of summary base directory. It should be the return value of
  52. realpath().
  53. abs_summary_dir (str): The canonical path of summary directory. It should be the return value of realpath().
  54. create_time (DateTime): The create time of summary directory.
  55. update_time (DateTime): The latest modify time of summary files directly in the summary directory.
  56. """
  57. def __init__(self, train_id, abs_summary_base_dir, abs_summary_dir, create_time, update_time):
  58. self._train_id = train_id
  59. self._abs_summary_base_dir = abs_summary_base_dir
  60. self._abs_summary_dir = abs_summary_dir
  61. self._create_time = create_time
  62. self._update_time = update_time
  63. @property
  64. def summary_dir(self):
  65. """Get summary directory path."""
  66. return self._abs_summary_dir
  67. @property
  68. def summary_base_dir(self):
  69. """Get summary base directory path."""
  70. return self._abs_summary_base_dir
  71. @property
  72. def train_id(self):
  73. """Get train id."""
  74. return self._train_id
  75. @property
  76. def update_time(self):
  77. """Get update time."""
  78. return self._update_time
  79. class CachedTrainJob:
  80. """
  81. Cache item for BriefCacheManager.
  82. DetailCacheManager will also wrap it's return value with this class.
  83. Args:
  84. basic_info (_BasicTrainJob): Basic info about the train job.
  85. """
  86. def __init__(self, basic_info: _BasicTrainJob):
  87. self._basic_info = basic_info
  88. self._last_access_time = datetime.datetime.utcnow()
  89. # Other cached content is stored here.
  90. self._content = {}
  91. self._cache_status = _CacheStatus.NOT_IN_CACHE
  92. self._key_locks = {}
  93. @property
  94. def cache_status(self):
  95. """Get cache status."""
  96. return self._cache_status
  97. @cache_status.setter
  98. def cache_status(self, value):
  99. """Set cache status."""
  100. self._cache_status = value
  101. def update_access_time(self):
  102. """Update last access time of this cache item."""
  103. self._last_access_time = datetime.datetime.utcnow()
  104. @property
  105. def last_access_time(self):
  106. """Get last access time for purposes such as LRU."""
  107. return self._last_access_time
  108. @property
  109. def summary_dir(self):
  110. """Get summary directory path."""
  111. return self._basic_info.summary_dir
  112. @property
  113. def summary_base_dir(self):
  114. """Get summary base directory path."""
  115. return self._basic_info.summary_base_dir
  116. def set(self, key, value):
  117. """Set value to cache."""
  118. self._content[key] = value
  119. def get(self, key):
  120. """Get value from cache."""
  121. try:
  122. return self._content[key]
  123. except KeyError:
  124. raise ParamValueError("Invalid cache key({}).".format(key))
  125. @property
  126. def basic_info(self):
  127. """Get basic train job info."""
  128. return self._basic_info
  129. @basic_info.setter
  130. def basic_info(self, value):
  131. """Set basic train job info."""
  132. self._basic_info = value
  133. def lock_key(self, key):
  134. """Threading lock with given key."""
  135. if key not in self._key_locks:
  136. self._key_locks[key] = threading.Lock()
  137. return self._key_locks[key]
  138. class TrainJob:
  139. """
  140. Train job object.
  141. You must not create TrainJob objects manually. You should always get TrainJob objects from DataManager.
  142. Args:
  143. brief_train_job (CachedTrainJob): Brief info about train job.
  144. detail_train_job (Optional[CachedTrainJob]): Detailed info about train job. Default: None.
  145. """
  146. def __init__(self,
  147. brief_train_job: CachedTrainJob,
  148. detail_train_job: Optional[CachedTrainJob] = None):
  149. self._brief = brief_train_job
  150. self._detail = detail_train_job
  151. if self._detail is None:
  152. self._cache_status = _CacheStatus.NOT_IN_CACHE
  153. else:
  154. self._cache_status = self._detail.cache_status
  155. def has_detail(self):
  156. """Whether this train job has detailed info in cache."""
  157. return bool(self._detail is not None)
  158. def get_detail(self, key):
  159. """
  160. Get detail content.
  161. Args:
  162. key (Any): Cache key.
  163. Returns:
  164. Any, cache content.
  165. Raises:
  166. TrainJobDetailNotInCacheError: when this train job has no detail cache.
  167. """
  168. if not self.has_detail():
  169. raise exceptions.TrainJobDetailNotInCacheError()
  170. return self._detail.get(key)
  171. def get_brief(self, key):
  172. """
  173. Get brief content.
  174. Args:
  175. key (Any): Cache key.
  176. Returns:
  177. Any, cache content.
  178. """
  179. return self._brief.get(key)
  180. class BaseCacheItemUpdater(abc.ABC):
  181. """Abstract base class for other modules to update cache content."""
  182. def update_item(self, cache_item: CachedTrainJob):
  183. """
  184. Update cache item in place.
  185. Args:
  186. cache_item (CachedTrainJob): The cache item to be processed.
  187. """
  188. raise NotImplementedError()
  189. class _BaseCacheManager:
  190. """Base class for cache manager."""
  191. def __init__(self):
  192. # Use dict to remove duplicate updaters.
  193. self._updaters = {}
  194. # key is train_id
  195. self._lock = threading.Lock()
  196. self._cache_items = {}
  197. def size(self):
  198. """Gets used cache slots."""
  199. return len(self._cache_items)
  200. def register_cache_item_updater(self, updater: BaseCacheItemUpdater):
  201. """Register cache item updater."""
  202. self._updaters[updater.__class__.__qualname__] = updater
  203. def get_train_jobs(self):
  204. """Get cached train jobs."""
  205. copied_train_jobs = dict(self._cache_items)
  206. return copied_train_jobs
  207. def get_train_job(self, train_id):
  208. """Get cached train job."""
  209. try:
  210. return self._cache_items[train_id]
  211. except KeyError:
  212. raise TrainJobNotExistError(train_id)
  213. def cache_train_job(self, train_id) -> bool:
  214. """
  215. Cache given train job and update train job's last access time.
  216. This method should return true if reload actions should be taken to cache the train job.
  217. Args:
  218. train_id (str): Train Id.
  219. """
  220. raise NotImplementedError()
  221. def delete_train_job(self, train_id):
  222. """Delete train job from cache."""
  223. if train_id in self._cache_items:
  224. del self._cache_items[train_id]
  225. def has_content(self):
  226. """Whether this cache manager has train jobs."""
  227. return bool(self._cache_items)
  228. def update_cache(self, disk_train_jobs: Iterable[_BasicTrainJob]):
  229. """
  230. Update cache according to given train jobs on disk.
  231. Different cache manager should implement different cache update policies in this method.
  232. Args:
  233. disk_train_jobs (Iterable[_BasicTrainJob]): Train jobs on disk.
  234. """
  235. raise NotImplementedError()
  236. def _merge_with_disk(self, disk_train_jobs: Iterable[_BasicTrainJob]):
  237. """
  238. Merge train jobs in cache with train jobs from disk
  239. This method will remove train jobs not on disk. Call this function with lock for thread safety.
  240. Args:
  241. disk_train_jobs (Iterable[_BasicTrainJob]): Basic train jobs info from disk.
  242. Returns:
  243. dict, a dict containing train jobs to be cached.
  244. """
  245. new_cache_items = {}
  246. for train_job in disk_train_jobs:
  247. if train_job.train_id not in self._cache_items:
  248. new_cache_items[train_job.train_id] = CachedTrainJob(train_job)
  249. else:
  250. reused_train_job = self._cache_items[train_job.train_id]
  251. reused_train_job.basic_info = train_job
  252. new_cache_items[train_job.train_id] = reused_train_job
  253. return new_cache_items
  254. class _BriefCacheManager(_BaseCacheManager):
  255. """A cache manager that holds all disk train jobs on disk."""
  256. def cache_train_job(self, train_id):
  257. """
  258. Cache given train job.
  259. All disk train jobs are cached on every reload, so this method always return false.
  260. Args:
  261. train_id (str): Train Id.
  262. """
  263. if train_id in self._cache_items:
  264. self._cache_items[train_id].update_access_time()
  265. return False
  266. def update_cache(self, disk_train_jobs):
  267. """Update cache."""
  268. with self._lock:
  269. new_cache_items = self._merge_with_disk(disk_train_jobs)
  270. self._cache_items = new_cache_items
  271. for updater in self._updaters.values():
  272. for cache_item in self._cache_items.values():
  273. updater.update_item(cache_item)
  274. @property
  275. def cache_items(self):
  276. """Get cache items."""
  277. return self._cache_items
  278. # Key for plugin tags.
  279. DATAVISUAL_PLUGIN_KEY = "tag_mapping"
  280. # Detail train job cache key for datavisual content.
  281. DATAVISUAL_CACHE_KEY = "datavisual"
  282. class _DetailCacheManager(_BaseCacheManager):
  283. """A cache manager that holds detailed info for most recently used train jobs."""
  284. def __init__(self, loader_generators):
  285. super().__init__()
  286. self._loader_pool = {}
  287. self._deleted_id_list = []
  288. self._loader_pool_mutex = threading.Lock()
  289. self._max_threads_count = 30
  290. self._loader_generators = loader_generators
  291. def size(self):
  292. """
  293. Get the number of items in this cache manager.
  294. To be implemented.
  295. Returns:
  296. int, the number of items in this cache manager.
  297. """
  298. raise NotImplementedError()
  299. def loader_pool_size(self):
  300. """Get loader pool size."""
  301. return len(self._loader_pool)
  302. def update_cache(self, disk_train_jobs: Iterable[_BasicTrainJob]):
  303. """
  304. Update cache.
  305. Will switch to using disk_train_jobs in the future.
  306. Args:
  307. disk_train_jobs (Iterable[_BasicTrainJob]): Basic info about train jobs on disk.
  308. """
  309. self._generate_loaders()
  310. self._execute_load_data()
  311. def cache_train_job(self, train_id):
  312. """Cache given train job."""
  313. loader = None
  314. need_reload = False
  315. with self._loader_pool_mutex:
  316. if self._is_loader_in_loader_pool(train_id, self._loader_pool):
  317. loader = self._loader_pool.get(train_id)
  318. if loader is None:
  319. for generator in self._loader_generators:
  320. tmp_loader = generator.generate_loader_by_train_id(train_id)
  321. if loader and loader.latest_update_time > tmp_loader.latest_update_time:
  322. continue
  323. loader = tmp_loader
  324. if loader is None:
  325. raise TrainJobNotExistError(train_id)
  326. self._add_loader(loader)
  327. need_reload = True
  328. self._update_loader_latest_update_time(loader.loader_id)
  329. return need_reload
  330. def get_train_jobs(self):
  331. """
  332. Get train jobs
  333. To be implemented.
  334. """
  335. def _add_loader(self, loader):
  336. """
  337. Add a loader to load data.
  338. Args:
  339. loader (LoaderStruct): A object of `Loader`.
  340. """
  341. if len(self._loader_pool) >= MAX_DATA_LOADER_SIZE:
  342. delete_number = len(self._loader_pool) - MAX_DATA_LOADER_SIZE + 1
  343. sorted_loaders = sorted(self._loader_pool.items(),
  344. key=lambda loader: loader[1].latest_update_time)
  345. for index in range(delete_number):
  346. delete_loader_id = sorted_loaders[index][0]
  347. self._delete_loader(delete_loader_id)
  348. self._loader_pool.update({loader.loader_id: loader})
  349. def _delete_loader(self, loader_id):
  350. """
  351. Delete loader from loader pool by loader id.
  352. Args:
  353. loader_id (str): ID of loader.
  354. """
  355. if self._loader_pool.get(loader_id) is not None:
  356. logger.debug("delete loader %s", loader_id)
  357. self._loader_pool.pop(loader_id)
  358. def _execute_loader(self, loader_id):
  359. """
  360. Load data form data_loader.
  361. If there is something wrong by loading, add logs and delete the loader.
  362. Args:
  363. loader_id (str): An ID for `Loader`.
  364. """
  365. try:
  366. with self._loader_pool_mutex:
  367. loader = self._loader_pool.get(loader_id, None)
  368. if loader is None:
  369. logger.debug("Loader %r has been deleted, will not load data.", loader_id)
  370. return
  371. loader.data_loader.load()
  372. except MindInsightException as ex:
  373. logger.warning("Data loader %r load data failed. "
  374. "Delete data_loader. Detail: %s", loader_id, ex)
  375. with self._loader_pool_mutex:
  376. self._delete_loader(loader_id)
  377. def _generate_loaders(self):
  378. """This function generates the loader from given path."""
  379. loader_dict = {}
  380. for generator in self._loader_generators:
  381. loader_dict.update(generator.generate_loaders(self._loader_pool))
  382. sorted_loaders = sorted(loader_dict.items(), key=lambda loader: loader[1].latest_update_time)
  383. latest_loaders = sorted_loaders[-MAX_DATA_LOADER_SIZE:]
  384. self._deal_loaders(latest_loaders)
  385. def _deal_loaders(self, latest_loaders):
  386. """
  387. This function determines which loaders to keep or remove or added.
  388. It is based on the given dict of loaders.
  389. Args:
  390. latest_loaders (list[dict]): A list of <loader_id: LoaderStruct>.
  391. """
  392. with self._loader_pool_mutex:
  393. for loader_id, loader in latest_loaders:
  394. if self._loader_pool.get(loader_id, None) is None:
  395. self._add_loader(loader)
  396. continue
  397. # If this loader was updated manually before,
  398. # its latest_update_time may bigger than update_time in summary.
  399. if self._loader_pool[loader_id].latest_update_time < loader.latest_update_time:
  400. self._update_loader_latest_update_time(loader_id, loader.latest_update_time)
  401. def _execute_load_data(self):
  402. """Load data through multiple threads."""
  403. threads_count = self._get_threads_count()
  404. if not threads_count:
  405. logger.info("Can not find any valid train log path to load, loader pool is empty.")
  406. return
  407. logger.info("Start to execute load data. threads_count: %s.", threads_count)
  408. with ThreadPoolExecutor(max_workers=threads_count) as executor:
  409. futures = []
  410. loader_pool = self._get_snapshot_loader_pool()
  411. for loader_id in loader_pool:
  412. future = executor.submit(self._execute_loader, loader_id)
  413. futures.append(future)
  414. wait(futures, return_when=ALL_COMPLETED)
  415. def _get_threads_count(self):
  416. """
  417. Use the maximum number of threads available.
  418. Returns:
  419. int, number of threads.
  420. """
  421. threads_count = min(self._max_threads_count, len(self._loader_pool))
  422. return threads_count
  423. def delete_train_job(self, train_id):
  424. """
  425. Delete train job with a train id.
  426. Args:
  427. train_id (str): ID for train job.
  428. """
  429. with self._loader_pool_mutex:
  430. self._delete_loader(train_id)
  431. def list_tensors(self, train_id, tag):
  432. """
  433. List tensors of the given train job and tag.
  434. If the tensor can not find by the given tag, will raise exception.
  435. Args:
  436. train_id (str): ID for train job.
  437. tag (str): The tag name.
  438. Returns:
  439. NamedTuple, the tuple format is `collections.namedtuple('_Tensor', ['wall_time', 'event_step', 'value'])`.
  440. the value will contain the given tag data.
  441. """
  442. loader_pool = self._get_snapshot_loader_pool()
  443. if not self._is_loader_in_loader_pool(train_id, loader_pool):
  444. raise TrainJobNotExistError("Can not find the given train job in cache.")
  445. data_loader = loader_pool[train_id].data_loader
  446. events_data = data_loader.get_events_data()
  447. try:
  448. tensors = events_data.tensors(tag)
  449. except KeyError:
  450. error_msg = "Can not find any data in this train job by given tag."
  451. raise ParamValueError(error_msg)
  452. return tensors
  453. def _check_train_job_exist(self, train_id, loader_pool):
  454. """
  455. Check train job exist, if not exist, will raise exception.
  456. Args:
  457. train_id (str): The given train job id.
  458. loader_pool (dict[str, LoaderStruct]): Refer to self._loader_pool.
  459. Raises:
  460. TrainJobNotExistError: Can not find train job in data manager.
  461. """
  462. is_exist = False
  463. if train_id in loader_pool:
  464. return
  465. for generator in self._loader_generators:
  466. if generator.check_train_job_exist(train_id):
  467. is_exist = True
  468. break
  469. if not is_exist:
  470. raise TrainJobNotExistError("Can not find the train job in data manager.")
  471. def _is_loader_in_loader_pool(self, train_id, loader_pool):
  472. """
  473. Check train job exist, if not exist, return False. Else, return True.
  474. Args:
  475. train_id (str): The given train job id.
  476. loader_pool (dict): See self._loader_pool.
  477. Returns:
  478. bool, if loader in loader pool, return True.
  479. """
  480. if train_id in loader_pool:
  481. return True
  482. return False
  483. def _get_snapshot_loader_pool(self):
  484. """
  485. Create a snapshot of data loader pool to avoid concurrent mutation and iteration issues.
  486. Returns:
  487. dict, a copy of `self._loader_pool`.
  488. """
  489. with self._loader_pool_mutex:
  490. return dict(self._loader_pool)
  491. def get_train_job(self, train_id):
  492. """
  493. Get train job by train ID.
  494. This method overrides parent method.
  495. Args:
  496. train_id (str): Train ID for train job.
  497. Returns:
  498. dict, single train job, if can not find any data, will return None.
  499. """
  500. self._check_train_job_exist(train_id, self._loader_pool)
  501. loader = self._get_loader(train_id)
  502. if loader is None:
  503. logger.warning("No valid summary log in train job %s, "
  504. "or it is not in the cache.", train_id)
  505. return None
  506. train_job = loader.to_dict()
  507. train_job.pop('data_loader')
  508. plugin_data = {}
  509. for plugin_name in PluginNameEnum.list_members():
  510. job = self.get_train_job_by_plugin(train_id, plugin_name=plugin_name)
  511. if job is None:
  512. plugin_data[plugin_name] = []
  513. else:
  514. plugin_data[plugin_name] = job['tags']
  515. train_job.update({DATAVISUAL_PLUGIN_KEY: plugin_data})
  516. # Will fill basic_info value in future.
  517. train_job_obj = CachedTrainJob(basic_info=None)
  518. train_job_obj.set(DATAVISUAL_CACHE_KEY, train_job)
  519. # Will assign real value in future.
  520. train_job_obj.cache_status = _CacheStatus.CACHED
  521. return train_job_obj
  522. def _get_loader(self, train_id):
  523. """
  524. Get loader by train id.
  525. Args:
  526. train_id (str): Train Id.
  527. Returns:
  528. LoaderStruct, the loader.
  529. """
  530. loader = None
  531. with self._loader_pool_mutex:
  532. if self._is_loader_in_loader_pool(train_id, self._loader_pool):
  533. loader = self._loader_pool.get(train_id)
  534. return loader
  535. def _update_loader_latest_update_time(self, loader_id, latest_update_time=None):
  536. """
  537. Update loader with latest_update_time.
  538. Args:
  539. loader_id (str): ID of loader.
  540. latest_update_time (float): Timestamp.
  541. """
  542. if latest_update_time is None:
  543. latest_update_time = time.time()
  544. self._loader_pool[loader_id].latest_update_time = latest_update_time
  545. def get_train_job_by_plugin(self, train_id, plugin_name):
  546. """
  547. Get a train job by train job id.
  548. If the given train job does not has the given plugin data, the tag list will be empty.
  549. Args:
  550. train_id (str): Get train job info by the given id.
  551. plugin_name (str): Get tags by given plugin.
  552. Returns:
  553. TypedDict('TrainJobEntity', {'id': str, 'name': str, 'tags': List[str]}),
  554. a train job object.
  555. """
  556. self._check_train_job_exist(train_id, self._loader_pool)
  557. loader = self._get_loader(train_id)
  558. if loader is None:
  559. logger.warning("No valid summary log in train job %s, "
  560. "or it is not in the cache.", train_id)
  561. return None
  562. name = loader.name
  563. data_loader = loader.data_loader
  564. tags = []
  565. try:
  566. events_data = data_loader.get_events_data()
  567. tags = events_data.list_tags_by_plugin(plugin_name)
  568. except KeyError:
  569. logger.debug("Plugin name %r does not exist "
  570. "in train job %r, and set tags to empty list.", plugin_name, name)
  571. except AttributeError:
  572. logger.debug("Train job %r has been deleted or it has not loaded data, "
  573. "and set tags to empty list.", name)
  574. result = dict(id=train_id, name=name, tags=tags)
  575. return result
  576. class DataManager:
  577. """
  578. DataManager manages a pool of loader which help access events data.
  579. Each loader helps deal the data of the events.
  580. A loader corresponds to an events_data.
  581. The DataManager build a pool including all the data_loader.
  582. The data_loader provides extracting
  583. method to get the information of events.
  584. """
  585. def __init__(self, summary_base_dir):
  586. """
  587. Initialize the pool of loader and the dict of name-to-path.
  588. Args:
  589. summary_base_dir (str): Base summary directory.
  590. self._status: Refer `datavisual.common.enums.DataManagerStatus`.
  591. """
  592. self._summary_base_dir = os.path.realpath(summary_base_dir)
  593. self._status = DataManagerStatus.INIT.value
  594. self._status_mutex = threading.Lock()
  595. self._reload_interval = 3
  596. loader_generators = [DataLoaderGenerator(self._summary_base_dir)]
  597. self._detail_cache = _DetailCacheManager(loader_generators)
  598. self._brief_cache = _BriefCacheManager()
  599. @property
  600. def summary_base_dir(self):
  601. """Get summary base dir."""
  602. return self._summary_base_dir
  603. def start_load_data(self,
  604. reload_interval=settings.RELOAD_INTERVAL,
  605. max_threads_count=MAX_DATA_LOADER_SIZE):
  606. """
  607. Start threads for loading data.
  608. Args:
  609. reload_interval (int): Time to reload data once.
  610. max_threads_count (int): Max number of threads of execution.
  611. """
  612. logger.info("Start to load data, reload_interval: %s, "
  613. "max_threads_count: %s.", reload_interval, max_threads_count)
  614. DataManager.check_reload_interval(reload_interval)
  615. DataManager.check_max_threads_count(max_threads_count)
  616. self._reload_interval = reload_interval
  617. self._max_threads_count = max_threads_count
  618. thread = threading.Thread(target=self._reload_data,
  619. name='start_load_data_thread')
  620. thread.daemon = True
  621. thread.start()
  622. def _reload_data(self):
  623. """This function periodically loads the data."""
  624. # Let gunicorn load other modules first.
  625. time.sleep(1)
  626. while True:
  627. self._load_data()
  628. if not self._reload_interval:
  629. break
  630. time.sleep(self._reload_interval)
  631. def reload_data(self):
  632. """
  633. Reload the data once.
  634. This function needs to be used after `start_load_data` function.
  635. """
  636. logger.debug("start to reload data")
  637. thread = threading.Thread(target=self._load_data,
  638. name='reload_data_thread')
  639. thread.daemon = False
  640. thread.start()
  641. def _load_data(self):
  642. """This function will load data once and ignore it if the status is loading."""
  643. logger.info("Start to load data, reload interval: %r.", self._reload_interval)
  644. with self._status_mutex:
  645. if self.status == DataManagerStatus.LOADING.value:
  646. logger.debug("Current status is %s , will ignore to load data.", self.status)
  647. return
  648. self.status = DataManagerStatus.LOADING.value
  649. summaries_info = SummaryWatcher().list_summary_directories(self._summary_base_dir)
  650. basic_train_jobs = []
  651. for info in summaries_info:
  652. basic_train_jobs.append(_BasicTrainJob(
  653. train_id=info['relative_path'],
  654. abs_summary_base_dir=self._summary_base_dir,
  655. abs_summary_dir=os.path.realpath(os.path.join(
  656. self._summary_base_dir,
  657. info['relative_path']
  658. )),
  659. create_time=info['create_time'],
  660. update_time=info['update_time']
  661. ))
  662. self._brief_cache.update_cache(basic_train_jobs)
  663. self._detail_cache.update_cache(basic_train_jobs)
  664. if not self._brief_cache.has_content() and not self._detail_cache.has_content():
  665. self.status = DataManagerStatus.INVALID.value
  666. else:
  667. self.status = DataManagerStatus.DONE.value
  668. logger.info("Load event data end, status: %r, and loader pool size is %r.",
  669. self.status, self._detail_cache.loader_pool_size())
  670. @staticmethod
  671. def check_reload_interval(reload_interval):
  672. """
  673. Check reload interval is valid.
  674. Args:
  675. reload_interval (int): Reload interval >= 0.
  676. """
  677. if not isinstance(reload_interval, int):
  678. raise ParamValueError("The value of reload interval should be integer.")
  679. if reload_interval < 0:
  680. raise ParamValueError("The value of reload interval should be >= 0.")
  681. @staticmethod
  682. def check_max_threads_count(max_threads_count):
  683. """
  684. Threads count should be a integer, and should > 0.
  685. Args:
  686. max_threads_count (int), should > 0.
  687. """
  688. if not isinstance(max_threads_count, int):
  689. raise ParamValueError("The value of max threads count should be integer.")
  690. if max_threads_count <= 0:
  691. raise ParamValueError("The value of max threads count should be > 0.")
  692. def get_train_job_by_plugin(self, train_id, plugin_name):
  693. """
  694. Get a train job by train job id.
  695. If the given train job does not has the given plugin data, the tag list will be empty.
  696. Args:
  697. train_id (str): Get train job info by the given id.
  698. plugin_name (str): Get tags by given plugin.
  699. Returns:
  700. TypedDict('TrainJobEntity', {'id': str, 'name': str, 'tags': List[str]}),
  701. a train job object.
  702. """
  703. self._check_status_valid()
  704. return self._detail_cache.get_train_job_by_plugin(train_id, plugin_name)
  705. def delete_train_job(self, train_id, only_delete_from_cache=True):
  706. """
  707. Delete train job with a train id.
  708. Args:
  709. train_id (str): ID for train job.
  710. """
  711. if not only_delete_from_cache:
  712. raise NotImplementedError("Delete from both cache and disk is not supported.")
  713. self._brief_cache.delete_train_job(train_id)
  714. self._detail_cache.delete_train_job(train_id)
  715. def list_tensors(self, train_id, tag):
  716. """
  717. List tensors of the given train job and tag.
  718. If the tensor can not find by the given tag, will raise exception.
  719. Args:
  720. train_id (str): ID for train job.
  721. tag (str): The tag name.
  722. Returns:
  723. NamedTuple, the tuple format is `collections.namedtuple('_Tensor', ['wall_time', 'event_step', 'value'])`.
  724. the value will contain the given tag data.
  725. """
  726. self._check_status_valid()
  727. return self._detail_cache.list_tensors(train_id, tag)
  728. def _check_status_valid(self):
  729. """Check if the status is valid to load data."""
  730. if self.status == DataManagerStatus.INIT.value:
  731. raise exceptions.SummaryLogIsLoading("Data is being loaded, current status: %s." % self._status)
  732. def get_train_job(self, train_id):
  733. """
  734. Get train job by train ID.
  735. Args:
  736. train_id (str): Train ID for train job.
  737. Returns:
  738. dict, single train job, if can not find any data, will return None.
  739. """
  740. self._check_status_valid()
  741. detail_train_job = self._detail_cache.get_train_job(train_id)
  742. brief_train_job = self._brief_cache.get_train_job(train_id)
  743. return TrainJob(brief_train_job, detail_train_job)
  744. def list_train_jobs(self):
  745. """
  746. List train jobs.
  747. To be implemented.
  748. """
  749. raise NotImplementedError()
  750. @property
  751. def status(self):
  752. """
  753. Get the status of data manager.
  754. Returns:
  755. DataManagerStatus, the status of data manager.
  756. """
  757. return self._status
  758. @status.setter
  759. def status(self, status):
  760. """Set data manger status."""
  761. self._status = status
  762. def cache_train_job(self, train_id):
  763. """Cache given train job (async)."""
  764. brief_need_reload = self._brief_cache.cache_train_job(train_id)
  765. detail_need_reload = self._detail_cache.cache_train_job(train_id)
  766. if brief_need_reload or detail_need_reload:
  767. self.reload_data()
  768. def register_brief_cache_item_updater(self, updater: BaseCacheItemUpdater):
  769. """Register brief cache item updater for brief cache manager."""
  770. self._brief_cache.register_cache_item_updater(updater)
  771. def get_brief_cache(self):
  772. """Get brief cache."""
  773. return self._brief_cache
  774. def get_brief_train_job(self, train_id):
  775. """Get brief train job."""
  776. return self._brief_cache.get_train_job(train_id)
  777. DATA_MANAGER = DataManager(settings.SUMMARY_BASE_DIR)

MindInsight为MindSpore提供了简单易用的调优调试能力。在训练过程中,可以将标量、张量、图像、计算图、模型超参、训练耗时等数据记录到文件中,通过MindInsight可视化页面进行查看及分析。