TensorRT转化代码
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.

510 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. 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, 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. job_type (str) -- To set the job_type for this run
  87. """
  88. # Pre-training routine --
  89. self.job_type = job_type
  90. self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run
  91. self.val_artifact, self.train_artifact = None, None
  92. self.train_artifact_path, self.val_artifact_path = None, None
  93. self.result_artifact = None
  94. self.val_table, self.result_table = None, None
  95. self.bbox_media_panel_images = []
  96. self.val_table_path_map = None
  97. self.max_imgs_to_log = 16
  98. self.wandb_artifact_data_dict = None
  99. self.data_dict = None
  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. if opt.upload_dataset:
  126. self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt)
  127. elif opt.data.endswith('_wandb.yaml'): # When dataset is W&B artifact
  128. with open(opt.data, encoding='ascii', errors='ignore') as f:
  129. data_dict = yaml.safe_load(f)
  130. self.data_dict = data_dict
  131. else: # Local .yaml dataset file or .zip file
  132. self.data_dict = check_dataset(opt.data)
  133. else:
  134. self.data_dict = check_dataset(opt.data)
  135. self.setup_training(opt)
  136. if not self.wandb_artifact_data_dict:
  137. self.wandb_artifact_data_dict = self.data_dict
  138. # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming.
  139. if not opt.resume:
  140. self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict},
  141. allow_val_change=True)
  142. if self.job_type == 'Dataset Creation':
  143. self.data_dict = self.check_and_upload_dataset(opt)
  144. def check_and_upload_dataset(self, opt):
  145. """
  146. Check if the dataset format is compatible and upload it as W&B artifact
  147. arguments:
  148. opt (namespace)-- Commandline arguments for current run
  149. returns:
  150. Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links.
  151. """
  152. assert wandb, 'Install wandb to upload dataset'
  153. config_path = self.log_dataset_artifact(opt.data,
  154. opt.single_cls,
  155. 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
  156. print("Created dataset config file ", config_path)
  157. with open(config_path, encoding='ascii', errors='ignore') as f:
  158. wandb_data_dict = yaml.safe_load(f)
  159. return wandb_data_dict
  160. def setup_training(self, opt):
  161. """
  162. Setup the necessary processes for training YOLO models:
  163. - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
  164. - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
  165. - Setup log_dict, initialize bbox_interval
  166. arguments:
  167. opt (namespace) -- commandline arguments for this run
  168. """
  169. self.log_dict, self.current_epoch = {}, 0
  170. self.bbox_interval = opt.bbox_interval
  171. if isinstance(opt.resume, str):
  172. modeldir, _ = self.download_model_artifact(opt)
  173. if modeldir:
  174. self.weights = Path(modeldir) / "last.pt"
  175. config = self.wandb_run.config
  176. opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
  177. self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs, \
  178. config.hyp
  179. data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume
  180. else:
  181. data_dict = self.data_dict
  182. if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download
  183. self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
  184. opt.artifact_alias)
  185. self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
  186. opt.artifact_alias)
  187. if self.train_artifact_path is not None:
  188. train_path = Path(self.train_artifact_path) / 'data/images/'
  189. data_dict['train'] = str(train_path)
  190. if self.val_artifact_path is not None:
  191. val_path = Path(self.val_artifact_path) / 'data/images/'
  192. data_dict['val'] = str(val_path)
  193. if self.val_artifact is not None:
  194. self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
  195. self.result_table = wandb.Table(["epoch", "id", "ground truth", "prediction", "avg_confidence"])
  196. self.val_table = self.val_artifact.get("val")
  197. if self.val_table_path_map is None:
  198. self.map_val_table_path()
  199. if opt.bbox_interval == -1:
  200. self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
  201. train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None
  202. # Update the the data_dict to point to local artifacts dir
  203. if train_from_artifact:
  204. self.data_dict = data_dict
  205. def download_dataset_artifact(self, path, alias):
  206. """
  207. download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX
  208. arguments:
  209. path -- path of the dataset to be used for training
  210. alias (str)-- alias of the artifact to be download/used for training
  211. returns:
  212. (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset
  213. is found otherwise returns (None, None)
  214. """
  215. if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
  216. artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
  217. dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/"))
  218. assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
  219. datadir = dataset_artifact.download()
  220. return datadir, dataset_artifact
  221. return None, None
  222. def download_model_artifact(self, opt):
  223. """
  224. download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX
  225. arguments:
  226. opt (namespace) -- Commandline arguments for this run
  227. """
  228. if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
  229. model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
  230. assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
  231. modeldir = model_artifact.download()
  232. epochs_trained = model_artifact.metadata.get('epochs_trained')
  233. total_epochs = model_artifact.metadata.get('total_epochs')
  234. is_finished = total_epochs is None
  235. assert not is_finished, 'training is finished, can only resume incomplete runs.'
  236. return modeldir, model_artifact
  237. return None, None
  238. def log_model(self, path, opt, epoch, fitness_score, best_model=False):
  239. """
  240. Log the model checkpoint as W&B artifact
  241. arguments:
  242. path (Path) -- Path of directory containing the checkpoints
  243. opt (namespace) -- Command line arguments for this run
  244. epoch (int) -- Current epoch number
  245. fitness_score (float) -- fitness score for current epoch
  246. best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
  247. """
  248. model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
  249. 'original_url': str(path),
  250. 'epochs_trained': epoch + 1,
  251. 'save period': opt.save_period,
  252. 'project': opt.project,
  253. 'total_epochs': opt.epochs,
  254. 'fitness_score': fitness_score
  255. })
  256. model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
  257. wandb.log_artifact(model_artifact,
  258. aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
  259. print("Saving model artifact on epoch ", epoch + 1)
  260. def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
  261. """
  262. Log the dataset as W&B artifact and return the new data file with W&B links
  263. arguments:
  264. data_file (str) -- the .yaml file with information about the dataset like - path, classes etc.
  265. single_class (boolean) -- train multi-class data as single-class
  266. project (str) -- project name. Used to construct the artifact path
  267. overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new
  268. file with _wandb postfix. Eg -> data_wandb.yaml
  269. returns:
  270. the new .yaml file with artifact links. it can be used to start training directly from artifacts
  271. """
  272. self.data_dict = check_dataset(data_file) # parse and check
  273. data = dict(self.data_dict)
  274. nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
  275. names = {k: v for k, v in enumerate(names)} # to index dictionary
  276. self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
  277. data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None
  278. self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
  279. data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None
  280. if data.get('train'):
  281. data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
  282. if data.get('val'):
  283. data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
  284. path = Path(data_file).stem
  285. path = (path if overwrite_config else path + '_wandb') + '.yaml' # updated data.yaml path
  286. data.pop('download', None)
  287. data.pop('path', None)
  288. with open(path, 'w') as f:
  289. yaml.safe_dump(data, f)
  290. if self.job_type == 'Training': # builds correct artifact pipeline graph
  291. self.wandb_run.use_artifact(self.val_artifact)
  292. self.wandb_run.use_artifact(self.train_artifact)
  293. self.val_artifact.wait()
  294. self.val_table = self.val_artifact.get('val')
  295. self.map_val_table_path()
  296. else:
  297. self.wandb_run.log_artifact(self.train_artifact)
  298. self.wandb_run.log_artifact(self.val_artifact)
  299. return path
  300. def map_val_table_path(self):
  301. """
  302. Map the validation dataset Table like name of file -> it's id in the W&B Table.
  303. Useful for - referencing artifacts for evaluation.
  304. """
  305. self.val_table_path_map = {}
  306. print("Mapping dataset")
  307. for i, data in enumerate(tqdm(self.val_table.data)):
  308. self.val_table_path_map[data[3]] = data[0]
  309. def create_dataset_table(self, dataset, class_to_id, name='dataset'):
  310. """
  311. Create and return W&B artifact containing W&B Table of the dataset.
  312. arguments:
  313. dataset (LoadImagesAndLabels) -- instance of LoadImagesAndLabels class used to iterate over the data to build Table
  314. class_to_id (dict(int, str)) -- hash map that maps class ids to labels
  315. name (str) -- name of the artifact
  316. returns:
  317. dataset artifact to be logged or used
  318. """
  319. # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
  320. artifact = wandb.Artifact(name=name, type="dataset")
  321. img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
  322. img_files = tqdm(dataset.img_files) if not img_files else img_files
  323. for img_file in img_files:
  324. if Path(img_file).is_dir():
  325. artifact.add_dir(img_file, name='data/images')
  326. labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
  327. artifact.add_dir(labels_path, name='data/labels')
  328. else:
  329. artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
  330. label_file = Path(img2label_paths([img_file])[0])
  331. artifact.add_file(str(label_file),
  332. name='data/labels/' + label_file.name) if label_file.exists() else None
  333. table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
  334. class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
  335. for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
  336. box_data, img_classes = [], {}
  337. for cls, *xywh in labels[:, 1:].tolist():
  338. cls = int(cls)
  339. box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]},
  340. "class_id": cls,
  341. "box_caption": "%s" % (class_to_id[cls])})
  342. img_classes[cls] = class_to_id[cls]
  343. boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
  344. table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()),
  345. Path(paths).name)
  346. artifact.add(table, name)
  347. return artifact
  348. def log_training_progress(self, predn, path, names):
  349. """
  350. Build evaluation Table. Uses reference from validation dataset table.
  351. arguments:
  352. predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class]
  353. path (str): local path of the current evaluation image
  354. names (dict(int, str)): hash map that maps class ids to labels
  355. """
  356. class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
  357. box_data = []
  358. total_conf = 0
  359. for *xyxy, conf, cls in predn.tolist():
  360. if conf >= 0.25:
  361. box_data.append(
  362. {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
  363. "class_id": int(cls),
  364. "box_caption": "%s %.3f" % (names[cls], conf),
  365. "scores": {"class_score": conf},
  366. "domain": "pixel"})
  367. total_conf = total_conf + conf
  368. boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
  369. id = self.val_table_path_map[Path(path).name]
  370. self.result_table.add_data(self.current_epoch,
  371. id,
  372. self.val_table.data[id][1],
  373. wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
  374. total_conf / max(1, len(box_data))
  375. )
  376. def val_one_image(self, pred, predn, path, names, im):
  377. """
  378. Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel
  379. arguments:
  380. pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
  381. predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class]
  382. path (str): local path of the current evaluation image
  383. """
  384. if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact
  385. self.log_training_progress(predn, path, names)
  386. if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0:
  387. if self.current_epoch % self.bbox_interval == 0:
  388. box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
  389. "class_id": int(cls),
  390. "box_caption": "%s %.3f" % (names[cls], conf),
  391. "scores": {"class_score": conf},
  392. "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
  393. boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
  394. self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name))
  395. def log(self, log_dict):
  396. """
  397. save the metrics to the logging dictionary
  398. arguments:
  399. log_dict (Dict) -- metrics/media to be logged in current step
  400. """
  401. if self.wandb_run:
  402. for key, value in log_dict.items():
  403. self.log_dict[key] = value
  404. def end_epoch(self, best_result=False):
  405. """
  406. commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.
  407. arguments:
  408. best_result (boolean): Boolean representing if the result of this evaluation is best or not
  409. """
  410. if self.wandb_run:
  411. with all_logging_disabled():
  412. if self.bbox_media_panel_images:
  413. self.log_dict["Bounding Box Debugger/Images"] = self.bbox_media_panel_images
  414. wandb.log(self.log_dict)
  415. self.log_dict = {}
  416. self.bbox_media_panel_images = []
  417. if self.result_artifact:
  418. self.result_artifact.add(self.result_table, 'result')
  419. wandb.log_artifact(self.result_artifact, aliases=['latest', 'last', 'epoch ' + str(self.current_epoch),
  420. ('best' if best_result else '')])
  421. wandb.log({"evaluation": self.result_table})
  422. self.result_table = wandb.Table(["epoch", "id", "ground truth", "prediction", "avg_confidence"])
  423. self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
  424. def finish_run(self):
  425. """
  426. Log metrics if any and finish the current W&B run
  427. """
  428. if self.wandb_run:
  429. if self.log_dict:
  430. with all_logging_disabled():
  431. wandb.log(self.log_dict)
  432. wandb.run.finish()
  433. @contextmanager
  434. def all_logging_disabled(highest_level=logging.CRITICAL):
  435. """ source - https://gist.github.com/simon-weber/7853144
  436. A context manager that will prevent any logging messages triggered during the body from being processed.
  437. :param highest_level: the maximum logging level in use.
  438. This would only need to be changed if a custom level greater than CRITICAL is defined.
  439. """
  440. previous_level = logging.root.manager.disable
  441. logging.disable(highest_level)
  442. try:
  443. yield
  444. finally:
  445. logging.disable(previous_level)