forked from ultralytics/ultralytics
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add a naive DDP for model interface (ultralytics#78)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Ayush Chaurasia <[email protected]>
- Loading branch information
1 parent
48c95ba
commit 7690cae
Showing
4 changed files
with
94 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import os | ||
import shutil | ||
import socket | ||
import sys | ||
import tempfile | ||
import time | ||
|
||
|
||
def find_free_network_port() -> int: | ||
# https://github.com/Lightning-AI/lightning/blob/master/src/lightning_lite/plugins/environments/lightning.py | ||
"""Finds a free port on localhost. | ||
It is useful in single-node training when we don't want to connect to a real main node but have to set the | ||
`MASTER_PORT` environment variable. | ||
""" | ||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
s.bind(("", 0)) | ||
port = s.getsockname()[1] | ||
s.close() | ||
return port | ||
|
||
|
||
def generate_ddp_file(trainer): | ||
import_path = '.'.join(str(trainer.__class__).split(".")[1:-1]) | ||
|
||
# remove the save_dir | ||
shutil.rmtree(trainer.save_dir) | ||
content = f'''overrides = {dict(trainer.args)} \nif __name__ == "__main__": | ||
from ultralytics.{import_path} import {trainer.__class__.__name__} | ||
trainer = {trainer.__class__.__name__}(overrides=overrides) | ||
trainer.train()''' | ||
with tempfile.NamedTemporaryFile(prefix="_temp_", | ||
suffix=f"{id(trainer)}.py", | ||
mode="w+", | ||
encoding='utf-8', | ||
dir=os.path.curdir, | ||
delete=False) as file: | ||
file.write(content) | ||
return file.name | ||
|
||
|
||
def generate_ddp_command(world_size, trainer): | ||
import __main__ # local import to avoid https://github.com/Lightning-AI/lightning/issues/15218 | ||
file_name = os.path.abspath(sys.argv[0]) | ||
using_cli = not file_name.endswith(".py") | ||
if using_cli: | ||
file_name = generate_ddp_file(trainer) | ||
return [ | ||
sys.executable, "-m", "torch.distributed.launch", "--nproc_per_node", f"{world_size}", "--master_port", | ||
f"{find_free_network_port()}", file_name] + sys.argv[1:] | ||
|
||
|
||
def ddp_cleanup(command, trainer): | ||
# delete temp file if created | ||
# TODO: this is a temp solution in case the file is deleted before DDP launching | ||
time.sleep(5) | ||
tempfile_suffix = str(id(trainer)) + ".py" | ||
if tempfile_suffix in "".join(command): | ||
for chunk in command: | ||
if tempfile_suffix in chunk: | ||
os.remove(chunk) | ||
break |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,11 +25,8 @@ def __init__(self, dataloader=None, save_dir=None, pbar=None, logger=None, args= | |
self.class_map = None | ||
self.targets = None | ||
self.metrics = DetMetrics(save_dir=self.save_dir, plot=self.args.plots) | ||
self.iouv = torch.linspace(0.5, 0.95, 10, device=self.device) # iou vector for [email protected]:0.95 | ||
self.iouv = torch.linspace(0.5, 0.95, 10) # iou vector for [email protected]:0.95 | ||
self.niou = self.iouv.numel() | ||
self.seen = 0 | ||
self.jdict = [] | ||
self.stats = [] | ||
|
||
def preprocess(self, batch): | ||
batch["img"] = batch["img"].to(self.device, non_blocking=True) | ||
|
@@ -56,6 +53,9 @@ def init_metrics(self, model): | |
self.names = dict(enumerate(self.names)) | ||
self.metrics.names = self.names | ||
self.confusion_matrix = ConfusionMatrix(nc=self.nc) | ||
self.seen = 0 | ||
self.jdict = [] | ||
self.stats = [] | ||
|
||
def get_desc(self): | ||
return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', "R", "mAP50", "mAP50-95)") | ||
|
@@ -98,7 +98,7 @@ def update_metrics(self, preds, batch): | |
tbox = ops.xywh2xyxy(labels[:, 1:5]) # target boxes | ||
ops.scale_boxes(batch["img"][si].shape[1:], tbox, shape) # native-space labels | ||
labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels | ||
correct_bboxes = self._process_batch(predn, labelsn, self.iouv) | ||
correct_bboxes = self._process_batch(predn, labelsn) | ||
# TODO: maybe remove these `self.` arguments as they already are member variable | ||
if self.args.plots: | ||
self.confusion_matrix.process_batch(predn, labelsn) | ||
|
@@ -139,7 +139,7 @@ def print_results(self): | |
if self.args.plots: | ||
self.confusion_matrix.plot(save_dir=self.save_dir, names=list(self.names.values())) | ||
|
||
def _process_batch(self, detections, labels, iouv): | ||
def _process_batch(self, detections, labels): | ||
""" | ||
Return correct prediction matrix | ||
Arguments: | ||
|
@@ -149,10 +149,10 @@ def _process_batch(self, detections, labels, iouv): | |
correct (array[N, 10]), for 10 IoU levels | ||
""" | ||
iou = box_iou(labels[:, 1:], detections[:, :4]) | ||
correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool) | ||
correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool) | ||
correct_class = labels[:, 0:1] == detections[:, 5] | ||
for i in range(len(iouv)): | ||
x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match | ||
for i in range(len(self.iouv)): | ||
x = torch.where((iou >= self.iouv[i]) & correct_class) # IoU > threshold and classes match | ||
if x[0].shape[0]: | ||
matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), | ||
1).cpu().numpy() # [label, detect, iou] | ||
|
@@ -162,7 +162,7 @@ def _process_batch(self, detections, labels, iouv): | |
# matches = matches[matches[:, 2].argsort()[::-1]] | ||
matches = matches[np.unique(matches[:, 0], return_index=True)[1]] | ||
correct[matches[:, 1].astype(int), i] = True | ||
return torch.tensor(correct, dtype=torch.bool, device=iouv.device) | ||
return torch.tensor(correct, dtype=torch.bool, device=detections.device) | ||
|
||
def get_dataloader(self, dataset_path, batch_size): | ||
# TODO: manage splits differently | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters