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.

528 lines
25KB

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