|
| 1 | +import json |
| 2 | +import shutil |
| 3 | +import sys |
| 4 | +from datetime import datetime |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import torch |
| 8 | + |
| 9 | +sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path |
| 10 | +from utils.general import colorstr, xywh2xyxy |
| 11 | + |
| 12 | +try: |
| 13 | + import wandb |
| 14 | +except ImportError: |
| 15 | + wandb = None |
| 16 | + print(f"{colorstr('wandb: ')}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)") |
| 17 | + |
| 18 | +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' |
| 19 | + |
| 20 | + |
| 21 | +def remove_prefix(from_string, prefix): |
| 22 | + return from_string[len(prefix):] |
| 23 | + |
| 24 | + |
| 25 | +class WandbLogger(): |
| 26 | + def __init__(self, opt, name, run_id, data_dict, job_type='Training'): |
| 27 | + self.wandb = wandb |
| 28 | + self.wandb_run = wandb.init(config=opt, resume="allow", |
| 29 | + project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, |
| 30 | + name=name, |
| 31 | + job_type=job_type, |
| 32 | + id=run_id) if self.wandb else None |
| 33 | + |
| 34 | + if job_type == 'Training': |
| 35 | + self.setup_training(opt, data_dict) |
| 36 | + if opt.bbox_interval == -1: |
| 37 | + opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else opt.epochs |
| 38 | + if opt.save_period == -1: |
| 39 | + opt.save_period = (opt.epochs // 10) if opt.epochs > 10 else opt.epochs |
| 40 | + |
| 41 | + def setup_training(self, opt, data_dict): |
| 42 | + self.log_dict = {} |
| 43 | + self.train_artifact_path, self.trainset_artifact = \ |
| 44 | + self.download_dataset_artifact(data_dict['train'], opt.artifact_alias) |
| 45 | + self.test_artifact_path, self.testset_artifact = \ |
| 46 | + self.download_dataset_artifact(data_dict['val'], opt.artifact_alias) |
| 47 | + self.result_artifact, self.result_table, self.weights = None, None, None |
| 48 | + if self.train_artifact_path is not None: |
| 49 | + train_path = Path(self.train_artifact_path) / 'data/images/' |
| 50 | + data_dict['train'] = str(train_path) |
| 51 | + if self.test_artifact_path is not None: |
| 52 | + test_path = Path(self.test_artifact_path) / 'data/images/' |
| 53 | + data_dict['val'] = str(test_path) |
| 54 | + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") |
| 55 | + self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"]) |
| 56 | + if opt.resume_from_artifact: |
| 57 | + modeldir, _ = self.download_model_artifact(opt.resume_from_artifact) |
| 58 | + if modeldir: |
| 59 | + self.weights = Path(modeldir) / "best.pt" |
| 60 | + opt.weights = self.weights |
| 61 | + |
| 62 | + def download_dataset_artifact(self, path, alias): |
| 63 | + if path.startswith(WANDB_ARTIFACT_PREFIX): |
| 64 | + dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) |
| 65 | + assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" |
| 66 | + datadir = dataset_artifact.download() |
| 67 | + labels_zip = Path(datadir) / "data/labels.zip" |
| 68 | + shutil.unpack_archive(labels_zip, Path(datadir) / 'data/labels', 'zip') |
| 69 | + print("Downloaded dataset to : ", datadir) |
| 70 | + return datadir, dataset_artifact |
| 71 | + return None, None |
| 72 | + |
| 73 | + def download_model_artifact(self, name): |
| 74 | + model_artifact = wandb.use_artifact(name + ":latest") |
| 75 | + assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' |
| 76 | + modeldir = model_artifact.download() |
| 77 | + print("Downloaded model to : ", modeldir) |
| 78 | + return modeldir, model_artifact |
| 79 | + |
| 80 | + def log_model(self, path, opt, epoch): |
| 81 | + datetime_suffix = datetime.today().strftime('%Y-%m-%d-%H-%M-%S') |
| 82 | + model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={ |
| 83 | + 'original_url': str(path), |
| 84 | + 'epoch': epoch + 1, |
| 85 | + 'save period': opt.save_period, |
| 86 | + 'project': opt.project, |
| 87 | + 'datetime': datetime_suffix |
| 88 | + }) |
| 89 | + model_artifact.add_file(str(path / 'last.pt'), name='last.pt') |
| 90 | + model_artifact.add_file(str(path / 'best.pt'), name='best.pt') |
| 91 | + wandb.log_artifact(model_artifact) |
| 92 | + print("Saving model artifact on epoch ", epoch + 1) |
| 93 | + |
| 94 | + def log_dataset_artifact(self, dataset, class_to_id, name='dataset'): |
| 95 | + artifact = wandb.Artifact(name=name, type="dataset") |
| 96 | + image_path = dataset.path |
| 97 | + artifact.add_dir(image_path, name='data/images') |
| 98 | + table = wandb.Table(columns=["id", "train_image", "Classes"]) |
| 99 | + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) |
| 100 | + for si, (img, labels, paths, shapes) in enumerate(dataset): |
| 101 | + height, width = shapes[0] |
| 102 | + labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) |
| 103 | + labels[:, 2:] *= torch.Tensor([width, height, width, height]) |
| 104 | + box_data = [] |
| 105 | + img_classes = {} |
| 106 | + for cls, *xyxy in labels[:, 1:].tolist(): |
| 107 | + cls = int(cls) |
| 108 | + box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, |
| 109 | + "class_id": cls, |
| 110 | + "box_caption": "%s" % (class_to_id[cls]), |
| 111 | + "scores": {"acc": 1}, |
| 112 | + "domain": "pixel"}) |
| 113 | + img_classes[cls] = class_to_id[cls] |
| 114 | + boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space |
| 115 | + table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes)) |
| 116 | + artifact.add(table, name) |
| 117 | + labels_path = 'labels'.join(image_path.rsplit('images', 1)) |
| 118 | + zip_path = Path(labels_path).parent / (name + '_labels.zip') |
| 119 | + if not zip_path.is_file(): # make_archive won't check if file exists |
| 120 | + shutil.make_archive(zip_path.with_suffix(''), 'zip', labels_path) |
| 121 | + artifact.add_file(str(zip_path), name='data/labels.zip') |
| 122 | + wandb.log_artifact(artifact) |
| 123 | + print("Saving data to W&B...") |
| 124 | + |
| 125 | + def log(self, log_dict): |
| 126 | + if self.wandb_run: |
| 127 | + for key, value in log_dict.items(): |
| 128 | + self.log_dict[key] = value |
| 129 | + |
| 130 | + def end_epoch(self): |
| 131 | + if self.wandb_run and self.log_dict: |
| 132 | + wandb.log(self.log_dict) |
| 133 | + self.log_dict = {} |
| 134 | + |
| 135 | + def finish_run(self): |
| 136 | + if self.wandb_run: |
| 137 | + if self.result_artifact: |
| 138 | + print("Add Training Progress Artifact") |
| 139 | + self.result_artifact.add(self.result_table, 'result') |
| 140 | + train_results = wandb.JoinedTable(self.testset_artifact.get("val"), self.result_table, "id") |
| 141 | + self.result_artifact.add(train_results, 'joined_result') |
| 142 | + wandb.log_artifact(self.result_artifact) |
| 143 | + if self.log_dict: |
| 144 | + wandb.log(self.log_dict) |
| 145 | + wandb.run.finish() |
0 commit comments