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.

492 lines
24KB

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