You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

561 satır
26KB

  1. """Utilities and tools for tracking runs with Weights & Biases."""
  2. import logging
  3. import os
  4. import sys
  5. from contextlib import contextmanager
  6. from pathlib import Path
  7. from typing import Dict
  8. import yaml
  9. from tqdm import tqdm
  10. FILE = Path(__file__).resolve()
  11. ROOT = FILE.parents[3] # YOLOv5 root directory
  12. if str(ROOT) not in sys.path:
  13. sys.path.append(str(ROOT)) # add ROOT to PATH
  14. from utils.datasets import LoadImagesAndLabels, img2label_paths
  15. from utils.general import LOGGER, check_dataset, check_file
  16. try:
  17. import wandb
  18. assert hasattr(wandb, '__version__') # verify package import not local dir
  19. except (ImportError, AssertionError):
  20. wandb = None
  21. RANK = int(os.getenv('RANK', -1))
  22. WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
  23. def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
  24. return from_string[len(prefix):]
  25. def check_wandb_config_file(data_config_file):
  26. wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
  27. if Path(wandb_config).is_file():
  28. return wandb_config
  29. return data_config_file
  30. def check_wandb_dataset(data_file):
  31. is_trainset_wandb_artifact = False
  32. is_valset_wandb_artifact = False
  33. if check_file(data_file) and data_file.endswith('.yaml'):
  34. with open(data_file, errors='ignore') as f:
  35. data_dict = yaml.safe_load(f)
  36. is_trainset_wandb_artifact = (isinstance(data_dict['train'], str) and
  37. data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX))
  38. is_valset_wandb_artifact = (isinstance(data_dict['val'], str) and
  39. data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX))
  40. if is_trainset_wandb_artifact or is_valset_wandb_artifact:
  41. return data_dict
  42. else:
  43. return check_dataset(data_file)
  44. def get_run_info(run_path):
  45. run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
  46. run_id = run_path.stem
  47. project = run_path.parent.stem
  48. entity = run_path.parent.parent.stem
  49. model_artifact_name = 'run_' + run_id + '_model'
  50. return entity, project, run_id, model_artifact_name
  51. def check_wandb_resume(opt):
  52. process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None
  53. if isinstance(opt.resume, str):
  54. if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
  55. if RANK not in [-1, 0]: # For resuming DDP runs
  56. entity, project, run_id, model_artifact_name = get_run_info(opt.resume)
  57. api = wandb.Api()
  58. artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest')
  59. modeldir = artifact.download()
  60. opt.weights = str(Path(modeldir) / "last.pt")
  61. return True
  62. return None
  63. def process_wandb_config_ddp_mode(opt):
  64. with open(check_file(opt.data), errors='ignore') as f:
  65. data_dict = yaml.safe_load(f) # data dict
  66. train_dir, val_dir = None, None
  67. if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
  68. api = wandb.Api()
  69. train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
  70. train_dir = train_artifact.download()
  71. train_path = Path(train_dir) / 'data/images/'
  72. data_dict['train'] = str(train_path)
  73. if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
  74. api = wandb.Api()
  75. val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
  76. val_dir = val_artifact.download()
  77. val_path = Path(val_dir) / 'data/images/'
  78. data_dict['val'] = str(val_path)
  79. if train_dir or val_dir:
  80. ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
  81. with open(ddp_data_path, 'w') as f:
  82. yaml.safe_dump(data_dict, f)
  83. opt.data = ddp_data_path
  84. class WandbLogger():
  85. """Log training runs, datasets, models, and predictions to Weights & Biases.
  86. This logger sends information to W&B at wandb.ai. By default, this information
  87. includes hyperparameters, system configuration and metrics, model metrics,
  88. and basic data metrics and analyses.
  89. By providing additional command line arguments to train.py, datasets,
  90. models and predictions can also be logged.
  91. For more on how this logger is used, see the Weights & Biases documentation:
  92. https://docs.wandb.com/guides/integrations/yolov5
  93. """
  94. def __init__(self, opt, run_id=None, job_type='Training'):
  95. """
  96. - Initialize WandbLogger instance
  97. - Upload dataset if opt.upload_dataset is True
  98. - Setup trainig processes if job_type is 'Training'
  99. arguments:
  100. opt (namespace) -- Commandline arguments for this run
  101. run_id (str) -- Run ID of W&B run to be resumed
  102. job_type (str) -- To set the job_type for this run
  103. """
  104. # Pre-training routine --
  105. self.job_type = job_type
  106. self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run
  107. self.val_artifact, self.train_artifact = None, None
  108. self.train_artifact_path, self.val_artifact_path = None, None
  109. self.result_artifact = None
  110. self.val_table, self.result_table = None, None
  111. self.bbox_media_panel_images = []
  112. self.val_table_path_map = None
  113. self.max_imgs_to_log = 16
  114. self.wandb_artifact_data_dict = None
  115. self.data_dict = None
  116. # It's more elegant to stick to 1 wandb.init call,
  117. # but useful config data is overwritten in the WandbLogger's wandb.init call
  118. if isinstance(opt.resume, str): # checks resume from artifact
  119. if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
  120. entity, project, run_id, model_artifact_name = get_run_info(opt.resume)
  121. model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
  122. assert wandb, 'install wandb to resume wandb runs'
  123. # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
  124. self.wandb_run = wandb.init(id=run_id,
  125. project=project,
  126. entity=entity,
  127. resume='allow',
  128. allow_val_change=True)
  129. opt.resume = model_artifact_name
  130. elif self.wandb:
  131. self.wandb_run = wandb.init(config=opt,
  132. resume="allow",
  133. project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
  134. entity=opt.entity,
  135. name=opt.name if opt.name != 'exp' else None,
  136. job_type=job_type,
  137. id=run_id,
  138. allow_val_change=True) if not wandb.run else wandb.run
  139. if self.wandb_run:
  140. if self.job_type == 'Training':
  141. if opt.upload_dataset:
  142. if not opt.resume:
  143. self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt)
  144. if opt.resume:
  145. # resume from artifact
  146. if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
  147. self.data_dict = dict(self.wandb_run.config.data_dict)
  148. else: # local resume
  149. self.data_dict = check_wandb_dataset(opt.data)
  150. else:
  151. self.data_dict = check_wandb_dataset(opt.data)
  152. self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict
  153. # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming.
  154. self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict},
  155. allow_val_change=True)
  156. self.setup_training(opt)
  157. if self.job_type == 'Dataset Creation':
  158. self.wandb_run.config.update({"upload_dataset": True})
  159. self.data_dict = self.check_and_upload_dataset(opt)
  160. def check_and_upload_dataset(self, opt):
  161. """
  162. Check if the dataset format is compatible and upload it as W&B artifact
  163. arguments:
  164. opt (namespace)-- Commandline arguments for current run
  165. returns:
  166. Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links.
  167. """
  168. assert wandb, 'Install wandb to upload dataset'
  169. config_path = self.log_dataset_artifact(opt.data,
  170. opt.single_cls,
  171. 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
  172. with open(config_path, errors='ignore') as f:
  173. wandb_data_dict = yaml.safe_load(f)
  174. return wandb_data_dict
  175. def setup_training(self, opt):
  176. """
  177. Setup the necessary processes for training YOLO models:
  178. - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
  179. - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
  180. - Setup log_dict, initialize bbox_interval
  181. arguments:
  182. opt (namespace) -- commandline arguments for this run
  183. """
  184. self.log_dict, self.current_epoch = {}, 0
  185. self.bbox_interval = opt.bbox_interval
  186. if isinstance(opt.resume, str):
  187. modeldir, _ = self.download_model_artifact(opt)
  188. if modeldir:
  189. self.weights = Path(modeldir) / "last.pt"
  190. config = self.wandb_run.config
  191. opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
  192. self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs, \
  193. config.hyp
  194. data_dict = self.data_dict
  195. if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download
  196. self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
  197. opt.artifact_alias)
  198. self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
  199. opt.artifact_alias)
  200. if self.train_artifact_path is not None:
  201. train_path = Path(self.train_artifact_path) / 'data/images/'
  202. data_dict['train'] = str(train_path)
  203. if self.val_artifact_path is not None:
  204. val_path = Path(self.val_artifact_path) / 'data/images/'
  205. data_dict['val'] = str(val_path)
  206. if self.val_artifact is not None:
  207. self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
  208. columns = ["epoch", "id", "ground truth", "prediction"]
  209. columns.extend(self.data_dict['names'])
  210. self.result_table = wandb.Table(columns)
  211. self.val_table = self.val_artifact.get("val")
  212. if self.val_table_path_map is None:
  213. self.map_val_table_path()
  214. if opt.bbox_interval == -1:
  215. self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
  216. train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None
  217. # Update the the data_dict to point to local artifacts dir
  218. if train_from_artifact:
  219. self.data_dict = data_dict
  220. def download_dataset_artifact(self, path, alias):
  221. """
  222. download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX
  223. arguments:
  224. path -- path of the dataset to be used for training
  225. alias (str)-- alias of the artifact to be download/used for training
  226. returns:
  227. (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset
  228. is found otherwise returns (None, None)
  229. """
  230. if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
  231. artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
  232. dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/"))
  233. assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
  234. datadir = dataset_artifact.download()
  235. return datadir, dataset_artifact
  236. return None, None
  237. def download_model_artifact(self, opt):
  238. """
  239. download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX
  240. arguments:
  241. opt (namespace) -- Commandline arguments for this run
  242. """
  243. if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
  244. model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
  245. assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
  246. modeldir = model_artifact.download()
  247. epochs_trained = model_artifact.metadata.get('epochs_trained')
  248. total_epochs = model_artifact.metadata.get('total_epochs')
  249. is_finished = total_epochs is None
  250. assert not is_finished, 'training is finished, can only resume incomplete runs.'
  251. return modeldir, model_artifact
  252. return None, None
  253. def log_model(self, path, opt, epoch, fitness_score, best_model=False):
  254. """
  255. Log the model checkpoint as W&B artifact
  256. arguments:
  257. path (Path) -- Path of directory containing the checkpoints
  258. opt (namespace) -- Command line arguments for this run
  259. epoch (int) -- Current epoch number
  260. fitness_score (float) -- fitness score for current epoch
  261. best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
  262. """
  263. model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
  264. 'original_url': str(path),
  265. 'epochs_trained': epoch + 1,
  266. 'save period': opt.save_period,
  267. 'project': opt.project,
  268. 'total_epochs': opt.epochs,
  269. 'fitness_score': fitness_score
  270. })
  271. model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
  272. wandb.log_artifact(model_artifact,
  273. aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
  274. LOGGER.info(f"Saving model artifact on epoch {epoch + 1}")
  275. def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
  276. """
  277. Log the dataset as W&B artifact and return the new data file with W&B links
  278. arguments:
  279. data_file (str) -- the .yaml file with information about the dataset like - path, classes etc.
  280. single_class (boolean) -- train multi-class data as single-class
  281. project (str) -- project name. Used to construct the artifact path
  282. overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new
  283. file with _wandb postfix. Eg -> data_wandb.yaml
  284. returns:
  285. the new .yaml file with artifact links. it can be used to start training directly from artifacts
  286. """
  287. upload_dataset = self.wandb_run.config.upload_dataset
  288. log_val_only = isinstance(upload_dataset, str) and upload_dataset == 'val'
  289. self.data_dict = check_dataset(data_file) # parse and check
  290. data = dict(self.data_dict)
  291. nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
  292. names = {k: v for k, v in enumerate(names)} # to index dictionary
  293. # log train set
  294. if not log_val_only:
  295. self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
  296. data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None
  297. if data.get('train'):
  298. data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
  299. self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
  300. data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None
  301. if data.get('val'):
  302. data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
  303. path = Path(data_file)
  304. # create a _wandb.yaml file with artifacts links if both train and test set are logged
  305. if not log_val_only:
  306. path = (path.stem if overwrite_config else path.stem + '_wandb') + '.yaml' # updated data.yaml path
  307. path = Path('data') / path
  308. data.pop('download', None)
  309. data.pop('path', None)
  310. with open(path, 'w') as f:
  311. yaml.safe_dump(data, f)
  312. LOGGER.info(f"Created dataset config file {path}")
  313. if self.job_type == 'Training': # builds correct artifact pipeline graph
  314. if not log_val_only:
  315. self.wandb_run.log_artifact(
  316. self.train_artifact) # calling use_artifact downloads the dataset. NOT NEEDED!
  317. self.wandb_run.use_artifact(self.val_artifact)
  318. self.val_artifact.wait()
  319. self.val_table = self.val_artifact.get('val')
  320. self.map_val_table_path()
  321. else:
  322. self.wandb_run.log_artifact(self.train_artifact)
  323. self.wandb_run.log_artifact(self.val_artifact)
  324. return path
  325. def map_val_table_path(self):
  326. """
  327. Map the validation dataset Table like name of file -> it's id in the W&B Table.
  328. Useful for - referencing artifacts for evaluation.
  329. """
  330. self.val_table_path_map = {}
  331. LOGGER.info("Mapping dataset")
  332. for i, data in enumerate(tqdm(self.val_table.data)):
  333. self.val_table_path_map[data[3]] = data[0]
  334. def create_dataset_table(self, dataset: LoadImagesAndLabels, class_to_id: Dict[int, str], name: str = 'dataset'):
  335. """
  336. Create and return W&B artifact containing W&B Table of the dataset.
  337. arguments:
  338. dataset -- instance of LoadImagesAndLabels class used to iterate over the data to build Table
  339. class_to_id -- hash map that maps class ids to labels
  340. name -- name of the artifact
  341. returns:
  342. dataset artifact to be logged or used
  343. """
  344. # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
  345. artifact = wandb.Artifact(name=name, type="dataset")
  346. img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
  347. img_files = tqdm(dataset.img_files) if not img_files else img_files
  348. for img_file in img_files:
  349. if Path(img_file).is_dir():
  350. artifact.add_dir(img_file, name='data/images')
  351. labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
  352. artifact.add_dir(labels_path, name='data/labels')
  353. else:
  354. artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
  355. label_file = Path(img2label_paths([img_file])[0])
  356. artifact.add_file(str(label_file),
  357. name='data/labels/' + label_file.name) if label_file.exists() else None
  358. table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
  359. class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
  360. for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
  361. box_data, img_classes = [], {}
  362. for cls, *xywh in labels[:, 1:].tolist():
  363. cls = int(cls)
  364. box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]},
  365. "class_id": cls,
  366. "box_caption": "%s" % (class_to_id[cls])})
  367. img_classes[cls] = class_to_id[cls]
  368. boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
  369. table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()),
  370. Path(paths).name)
  371. artifact.add(table, name)
  372. return artifact
  373. def log_training_progress(self, predn, path, names):
  374. """
  375. Build evaluation Table. Uses reference from validation dataset table.
  376. arguments:
  377. predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class]
  378. path (str): local path of the current evaluation image
  379. names (dict(int, str)): hash map that maps class ids to labels
  380. """
  381. class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
  382. box_data = []
  383. avg_conf_per_class = [0] * len(self.data_dict['names'])
  384. pred_class_count = {}
  385. for *xyxy, conf, cls in predn.tolist():
  386. if conf >= 0.25:
  387. cls = int(cls)
  388. box_data.append(
  389. {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
  390. "class_id": cls,
  391. "box_caption": f"{names[cls]} {conf:.3f}",
  392. "scores": {"class_score": conf},
  393. "domain": "pixel"})
  394. avg_conf_per_class[cls] += conf
  395. if cls in pred_class_count:
  396. pred_class_count[cls] += 1
  397. else:
  398. pred_class_count[cls] = 1
  399. for pred_class in pred_class_count.keys():
  400. avg_conf_per_class[pred_class] = avg_conf_per_class[pred_class] / pred_class_count[pred_class]
  401. boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
  402. id = self.val_table_path_map[Path(path).name]
  403. self.result_table.add_data(self.current_epoch,
  404. id,
  405. self.val_table.data[id][1],
  406. wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
  407. *avg_conf_per_class
  408. )
  409. def val_one_image(self, pred, predn, path, names, im):
  410. """
  411. Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel
  412. arguments:
  413. pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
  414. predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class]
  415. path (str): local path of the current evaluation image
  416. """
  417. if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact
  418. self.log_training_progress(predn, path, names)
  419. if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0:
  420. if self.current_epoch % self.bbox_interval == 0:
  421. box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
  422. "class_id": int(cls),
  423. "box_caption": f"{names[cls]} {conf:.3f}",
  424. "scores": {"class_score": conf},
  425. "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
  426. boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
  427. self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name))
  428. def log(self, log_dict):
  429. """
  430. save the metrics to the logging dictionary
  431. arguments:
  432. log_dict (Dict) -- metrics/media to be logged in current step
  433. """
  434. if self.wandb_run:
  435. for key, value in log_dict.items():
  436. self.log_dict[key] = value
  437. def end_epoch(self, best_result=False):
  438. """
  439. commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.
  440. arguments:
  441. best_result (boolean): Boolean representing if the result of this evaluation is best or not
  442. """
  443. if self.wandb_run:
  444. with all_logging_disabled():
  445. if self.bbox_media_panel_images:
  446. self.log_dict["BoundingBoxDebugger"] = self.bbox_media_panel_images
  447. try:
  448. wandb.log(self.log_dict)
  449. except BaseException as e:
  450. LOGGER.info(
  451. f"An error occurred in wandb logger. The training will proceed without interruption. More info\n{e}")
  452. self.wandb_run.finish()
  453. self.wandb_run = None
  454. self.log_dict = {}
  455. self.bbox_media_panel_images = []
  456. if self.result_artifact:
  457. self.result_artifact.add(self.result_table, 'result')
  458. wandb.log_artifact(self.result_artifact, aliases=['latest', 'last', 'epoch ' + str(self.current_epoch),
  459. ('best' if best_result else '')])
  460. wandb.log({"evaluation": self.result_table})
  461. columns = ["epoch", "id", "ground truth", "prediction"]
  462. columns.extend(self.data_dict['names'])
  463. self.result_table = wandb.Table(columns)
  464. self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
  465. def finish_run(self):
  466. """
  467. Log metrics if any and finish the current W&B run
  468. """
  469. if self.wandb_run:
  470. if self.log_dict:
  471. with all_logging_disabled():
  472. wandb.log(self.log_dict)
  473. wandb.run.finish()
  474. @contextmanager
  475. def all_logging_disabled(highest_level=logging.CRITICAL):
  476. """ source - https://gist.github.com/simon-weber/7853144
  477. A context manager that will prevent any logging messages triggered during the body from being processed.
  478. :param highest_level: the maximum logging level in use.
  479. This would only need to be changed if a custom level greater than CRITICAL is defined.
  480. """
  481. previous_level = logging.root.manager.disable
  482. logging.disable(highest_level)
  483. try:
  484. yield
  485. finally:
  486. logging.disable(previous_level)