-
Notifications
You must be signed in to change notification settings - Fork 7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add --backend and --use-v2 support to detection refs #7732
Changes from all commits
6443e6a
d10dd56
f956d01
06ab751
c6913d2
72da655
56dc431
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,7 @@ | |
import transforms as T | ||
from pycocotools import mask as coco_mask | ||
from pycocotools.coco import COCO | ||
from torchvision.datasets import wrap_dataset_for_transforms_v2 | ||
|
||
|
||
class FilterAndRemapCocoCategories: | ||
|
@@ -49,7 +50,6 @@ def __call__(self, image, target): | |
w, h = image.size | ||
|
||
image_id = target["image_id"] | ||
image_id = torch.tensor([image_id]) | ||
|
||
anno = target["annotations"] | ||
|
||
|
@@ -126,10 +126,6 @@ def _has_valid_annotation(anno): | |
return True | ||
return False | ||
|
||
if not isinstance(dataset, torchvision.datasets.CocoDetection): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of removing this (seemingly useless check) I could just add the same workaround as elsewhere i.e. add of isinstance(
getattr(dataset, "_dataset", None), torchvision.datasets.CocoDetection
): There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We still have #7239. Maybe we should go at it again? |
||
raise TypeError( | ||
f"This function expects dataset of type torchvision.datasets.CocoDetection, instead got {type(dataset)}" | ||
) | ||
ids = [] | ||
for ds_idx, img_id in enumerate(dataset.ids): | ||
ann_ids = dataset.coco.getAnnIds(imgIds=img_id, iscrowd=None) | ||
|
@@ -196,12 +192,15 @@ def convert_to_coco_api(ds): | |
|
||
|
||
def get_coco_api_from_dataset(dataset): | ||
# FIXME: This is... awful? | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah. Happy for you to address it here, but not required. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would if I knew what to do lol. (I'm gonna leave this out for now I think) |
||
for _ in range(10): | ||
if isinstance(dataset, torchvision.datasets.CocoDetection): | ||
break | ||
if isinstance(dataset, torch.utils.data.Subset): | ||
dataset = dataset.dataset | ||
if isinstance(dataset, torchvision.datasets.CocoDetection): | ||
if isinstance(dataset, torchvision.datasets.CocoDetection) or isinstance( | ||
getattr(dataset, "_dataset", None), torchvision.datasets.CocoDetection | ||
): | ||
return dataset.coco | ||
return convert_to_coco_api(dataset) | ||
|
||
|
@@ -220,25 +219,29 @@ def __getitem__(self, idx): | |
return img, target | ||
|
||
|
||
def get_coco(root, image_set, transforms, mode="instances"): | ||
def get_coco(root, image_set, transforms, mode="instances", use_v2=False): | ||
anno_file_template = "{}_{}2017.json" | ||
PATHS = { | ||
"train": ("train2017", os.path.join("annotations", anno_file_template.format(mode, "train"))), | ||
"val": ("val2017", os.path.join("annotations", anno_file_template.format(mode, "val"))), | ||
# "train": ("val2017", os.path.join("annotations", anno_file_template.format(mode, "val"))) | ||
} | ||
|
||
t = [ConvertCocoPolysToMask()] | ||
|
||
if transforms is not None: | ||
t.append(transforms) | ||
transforms = T.Compose(t) | ||
|
||
img_folder, ann_file = PATHS[image_set] | ||
img_folder = os.path.join(root, img_folder) | ||
ann_file = os.path.join(root, ann_file) | ||
|
||
dataset = CocoDetection(img_folder, ann_file, transforms=transforms) | ||
if use_v2: | ||
dataset = torchvision.datasets.CocoDetection(img_folder, ann_file, transforms=transforms) | ||
# TODO: need to update target_keys to handle masks for segmentation! | ||
dataset = wrap_dataset_for_transforms_v2(dataset, target_keys={"boxes", "labels", "image_id"}) | ||
else: | ||
t = [ConvertCocoPolysToMask()] | ||
if transforms is not None: | ||
t.append(transforms) | ||
transforms = T.Compose(t) | ||
|
||
dataset = CocoDetection(img_folder, ann_file, transforms=transforms) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wonder if we could get rid of this custom Not sure what to do to clean that up. |
||
|
||
if image_set == "train": | ||
dataset = _coco_remove_images_without_annotations(dataset) | ||
|
@@ -248,5 +251,7 @@ def get_coco(root, image_set, transforms, mode="instances"): | |
return dataset | ||
|
||
|
||
def get_coco_kp(root, image_set, transforms): | ||
def get_coco_kp(root, image_set, transforms, use_v2=False): | ||
if use_v2: | ||
raise ValueError("KeyPoints aren't supported by transforms V2 yet.") | ||
return get_coco(root, image_set, transforms, mode="person_keypoints") |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,7 +26,7 @@ def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq, sc | |
|
||
for images, targets in metric_logger.log_every(data_loader, print_freq, header): | ||
images = list(image.to(device) for image in images) | ||
targets = [{k: v.to(device) for k, v in t.items()} for t in targets] | ||
targets = [{k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in t.items()} for t in targets] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is for the image ID, right? |
||
with torch.cuda.amp.autocast(enabled=scaler is not None): | ||
loss_dict = model(images, targets) | ||
losses = sum(loss for loss in loss_dict.values()) | ||
|
@@ -97,7 +97,7 @@ def evaluate(model, data_loader, device): | |
outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs] | ||
model_time = time.time() - model_time | ||
|
||
res = {target["image_id"].item(): output for target, output in zip(targets, outputs)} | ||
res = {target["image_id"]: output for target, output in zip(targets, outputs)} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is for consistency with the V2 wrapper which leaves |
||
evaluator_time = time.time() | ||
coco_evaluator.update(res) | ||
evaluator_time = time.time() - evaluator_time | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,73 +1,109 @@ | ||
from collections import defaultdict | ||
|
||
import torch | ||
import transforms as T | ||
import transforms as reference_transforms | ||
|
||
|
||
def get_modules(use_v2): | ||
# We need a protected import to avoid the V2 warning in case just V1 is used | ||
if use_v2: | ||
import torchvision.datapoints | ||
import torchvision.transforms.v2 | ||
|
||
return torchvision.transforms.v2, torchvision.datapoints | ||
else: | ||
return reference_transforms, None | ||
|
||
|
||
class DetectionPresetTrain: | ||
def __init__(self, *, data_augmentation, hflip_prob=0.5, mean=(123.0, 117.0, 104.0)): | ||
# Note: this transform assumes that the input to forward() are always PIL | ||
# images, regardless of the backend parameter. | ||
def __init__( | ||
self, | ||
*, | ||
data_augmentation, | ||
hflip_prob=0.5, | ||
mean=(123.0, 117.0, 104.0), | ||
backend="pil", | ||
use_v2=False, | ||
): | ||
|
||
T, datapoints = get_modules(use_v2) | ||
|
||
transforms = [] | ||
backend = backend.lower() | ||
if backend == "datapoint": | ||
transforms.append(T.ToImageTensor()) | ||
elif backend == "tensor": | ||
transforms.append(T.PILToTensor()) | ||
elif backend != "pil": | ||
raise ValueError(f"backend can be 'datapoint', 'tensor' or 'pil', but got {backend}") | ||
NicolasHug marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if data_augmentation == "hflip": | ||
self.transforms = T.Compose( | ||
[ | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
T.PILToTensor(), | ||
T.ConvertImageDtype(torch.float), | ||
] | ||
) | ||
transforms += [T.RandomHorizontalFlip(p=hflip_prob)] | ||
elif data_augmentation == "lsj": | ||
self.transforms = T.Compose( | ||
[ | ||
T.ScaleJitter(target_size=(1024, 1024)), | ||
T.FixedSizeCrop(size=(1024, 1024), fill=mean), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
T.PILToTensor(), | ||
T.ConvertImageDtype(torch.float), | ||
] | ||
) | ||
transforms += [ | ||
T.ScaleJitter(target_size=(1024, 1024), antialias=True), | ||
# TODO: FixedSizeCrop below doesn't work on tensors! | ||
reference_transforms.FixedSizeCrop(size=(1024, 1024), fill=mean), | ||
Comment on lines
+47
to
+48
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In v2 we have |
||
T.RandomHorizontalFlip(p=hflip_prob), | ||
] | ||
elif data_augmentation == "multiscale": | ||
self.transforms = T.Compose( | ||
[ | ||
T.RandomShortestSize( | ||
min_size=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), max_size=1333 | ||
), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
T.PILToTensor(), | ||
T.ConvertImageDtype(torch.float), | ||
] | ||
) | ||
transforms += [ | ||
T.RandomShortestSize(min_size=(480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800), max_size=1333), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
] | ||
elif data_augmentation == "ssd": | ||
self.transforms = T.Compose( | ||
[ | ||
T.RandomPhotometricDistort(), | ||
T.RandomZoomOut(fill=list(mean)), | ||
T.RandomIoUCrop(), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
T.PILToTensor(), | ||
T.ConvertImageDtype(torch.float), | ||
] | ||
) | ||
fill = defaultdict(lambda: mean, {datapoints.Mask: 0}) if use_v2 else list(mean) | ||
transforms += [ | ||
T.RandomPhotometricDistort(), | ||
T.RandomZoomOut(fill=fill), | ||
T.RandomIoUCrop(), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
] | ||
elif data_augmentation == "ssdlite": | ||
self.transforms = T.Compose( | ||
[ | ||
T.RandomIoUCrop(), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
T.PILToTensor(), | ||
T.ConvertImageDtype(torch.float), | ||
] | ||
) | ||
transforms += [ | ||
T.RandomIoUCrop(), | ||
T.RandomHorizontalFlip(p=hflip_prob), | ||
] | ||
else: | ||
raise ValueError(f'Unknown data augmentation policy "{data_augmentation}"') | ||
|
||
if backend == "pil": | ||
# Note: we could just convert to pure tensors even in v2. | ||
transforms += [T.ToImageTensor() if use_v2 else T.PILToTensor()] | ||
|
||
transforms += [T.ConvertImageDtype(torch.float)] | ||
|
||
if use_v2: | ||
transforms += [ | ||
T.ConvertBoundingBoxFormat(datapoints.BoundingBoxFormat.XYXY), | ||
T.SanitizeBoundingBox(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we also need There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think so since we established that all transforms should clamp already (those that need to, at least)? |
||
] | ||
|
||
self.transforms = T.Compose(transforms) | ||
|
||
def __call__(self, img, target): | ||
return self.transforms(img, target) | ||
|
||
|
||
class DetectionPresetEval: | ||
def __init__(self): | ||
self.transforms = T.Compose( | ||
[ | ||
T.PILToTensor(), | ||
T.ConvertImageDtype(torch.float), | ||
] | ||
) | ||
def __init__(self, backend="pil", use_v2=False): | ||
T, _ = get_modules(use_v2) | ||
transforms = [] | ||
backend = backend.lower() | ||
if backend == "pil": | ||
# Note: we could just convert to pure tensors even in v2? | ||
transforms += [T.ToImageTensor() if use_v2 else T.PILToTensor()] | ||
elif backend == "tensor": | ||
transforms += [T.PILToTensor()] | ||
elif backend == "datapoint": | ||
transforms += [T.ToImageTensor()] | ||
else: | ||
raise ValueError(f"backend can be 'datapoint', 'tensor' or 'pil', but got {backend}") | ||
|
||
transforms += [T.ConvertImageDtype(torch.float)] | ||
self.transforms = T.Compose(transforms) | ||
|
||
def __call__(self, img, target): | ||
return self.transforms(img, target) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I just did
s/module/T/
in the file to make it consistent with the detection one