Skip to content

Trainers: add Instance Segmentation Task #2513

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

Merged
merged 58 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
d00c087
Add files via upload
ariannasole23 Jan 9, 2025
52daa1c
Add files via upload
ariannasole23 Jan 9, 2025
68756a7
Update instancesegmentation.py
ariannasole23 Jan 9, 2025
e249883
Merge branch 'microsoft:main' into main
ariannasole23 Jan 20, 2025
7676ac3
Update and rename instancesegmentation.py to instance_segmentation.py
ariannasole23 Jan 20, 2025
0fa7b07
Update test_instancesegmentation.py
ariannasole23 Jan 21, 2025
b4334f0
Update instance_segmentation.py
ariannasole23 Jan 21, 2025
a160baa
Update __init__.py
ariannasole23 Jan 21, 2025
fa8697b
Update instance_segmentation.py
ariannasole23 Jan 21, 2025
f6ceed1
Update instance_segmentation.py
ariannasole23 Jan 27, 2025
619760b
Add files via upload
ariannasole23 Jan 27, 2025
d9158a0
Update test_instancesegmentation.py
ariannasole23 Jan 27, 2025
9f48f50
Update and rename test_instancesegmentation.py to test_trainer_instan…
ariannasole23 Jan 28, 2025
63aefc8
Update instance_segmentation.py
ariannasole23 Jan 28, 2025
70074e7
Add files via upload
ariannasole23 Jan 28, 2025
b3de001
Creato con Colab
ariannasole23 Jan 28, 2025
d70f1e3
Creato con Colab
ariannasole23 Jan 28, 2025
1e68d2d
Creato con Colab
ariannasole23 Jan 28, 2025
98c836a
Merge branch 'microsoft:main' into main
ariannasole23 Feb 5, 2025
9664834
Update instance_segmentation.py
ariannasole23 Feb 5, 2025
f802574
Delete test_trainer.ipynb
ariannasole23 Feb 5, 2025
3c86306
Delete test_trainer_instancesegmentation.py
ariannasole23 Feb 5, 2025
7ec3930
Update and rename test_instancesegmentation.py to test_instance_segme…
ariannasole23 Feb 5, 2025
927f7fc
Update instance_segmentation.py
ariannasole23 Feb 5, 2025
4f1cecf
Update test_instance_segmentation.py
ariannasole23 Feb 5, 2025
21e0af2
Update instance_segmentation.py
ariannasole23 Feb 6, 2025
3956d23
Update instance_segmentation.py
ariannasole23 Feb 6, 2025
0e458a5
Update instance_segmentation.py run ruff
ariannasole23 Feb 6, 2025
870845b
Merge remote-tracking branch 'upstream/main'
adamjstewart Feb 20, 2025
fafb001
Ruff
adamjstewart Feb 20, 2025
ad7197d
dos2unix
adamjstewart Feb 20, 2025
954e898
Add support for MSI, weights
adamjstewart Feb 20, 2025
3c6ee68
Update tests
adamjstewart Feb 20, 2025
7c4e30c
timm and torchvision are not compatible
adamjstewart Feb 20, 2025
7c34d4a
Finalize trainer code, simpler
adamjstewart Feb 21, 2025
649a877
Update VHR10 tests
adamjstewart Feb 21, 2025
4f201fd
Uniformity
adamjstewart Feb 21, 2025
006cfa9
Fix most tests
adamjstewart Feb 21, 2025
b3a4e44
100% coverage
adamjstewart Feb 21, 2025
1d80adc
Fix datasets tests
adamjstewart Feb 21, 2025
d8e8fe6
Fix weight tests
adamjstewart Feb 21, 2025
f774875
Fix MSI support
adamjstewart Feb 21, 2025
c823fd0
Fix parameter replacement
adamjstewart Feb 21, 2025
94e8001
Fix minimum tests
adamjstewart Feb 21, 2025
5e01c96
Fix minimum tests
adamjstewart Feb 21, 2025
2460b26
Add all unpacked data
adamjstewart Feb 21, 2025
d63cf85
Fix tests
adamjstewart Feb 21, 2025
f85a72e
Undo FTW changes
adamjstewart Feb 21, 2025
683c162
Undo FTW changes
adamjstewart Feb 21, 2025
8a9c0e9
Undo FTW changes
adamjstewart Feb 21, 2025
b072a38
Remove dead code
adamjstewart Feb 21, 2025
c4b5d17
Remove dead code, match detection style
adamjstewart Feb 22, 2025
801c0ba
Try newer torchmetrics
adamjstewart Feb 22, 2025
4640d6c
Try newer torchmetrics
adamjstewart Feb 22, 2025
1d2a595
Try newer torchmetrics
adamjstewart Feb 22, 2025
8f165ab
More metrics
adamjstewart Feb 23, 2025
7b6182d
Fix mypy
adamjstewart Feb 23, 2025
335f072
Fix and test weights=True, num_classes!=91
adamjstewart Feb 25, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,16 @@ dependencies = [
"rasterio>=1.3,!=1.4.0,!=1.4.1,!=1.4.2",
# rtree 1+ required for Python 3.10 wheels
"rtree>=1",
# segmentation-models-pytorch 0.2+ required for smp.losses module
"segmentation-models-pytorch>=0.2",
# segmentation-models-pytorch 0.3.3+ required for timm 0.8+ support
"segmentation-models-pytorch>=0.3.3",
# shapely 1.8+ required for Python 3.10 wheels
"shapely>=1.8",
# timm 0.4.12 required by segmentation-models-pytorch
"timm>=0.4.12",
# timm 0.8+ required for timm.models.adapt_input_conv, 0.9.2 required by SMP
"timm>=0.9.2",
# torch 1.13+ required by torchvision
"torch>=1.13",
# torchmetrics 0.10+ required for binary/multiclass/multilabel classification metrics
"torchmetrics>=0.10",
# torchmetrics 1.2+ required for average argument in mAP metric
"torchmetrics>=1.2",
# torchvision 0.14+ required for torchvision.models.swin_v2_b
"torchvision>=0.14",
# typing-extensions 4.5+ required for typing_extensions.deprecated
Expand Down
6 changes: 3 additions & 3 deletions requirements/min-reqs.old
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ pillow==8.4.0
pyproj==3.3.0
rasterio==1.3.0.post1
rtree==1.0.0
segmentation-models-pytorch==0.2.0
segmentation-models-pytorch==0.3.3
shapely==1.8.0
timm==0.4.12
timm==0.9.2
torch==1.13.0
torchmetrics==0.10.0
torchmetrics==1.2.0
torchvision==0.14.0
typing-extensions==4.5.0

Expand Down
14 changes: 14 additions & 0 deletions tests/conf/vhr10_ins_seg.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
model:
class_path: InstanceSegmentationTask
init_args:
model: 'mask-rcnn'
backbone: 'resnet50'
num_classes: 11
data:
class_path: VHR10DataModule
init_args:
batch_size: 1
num_workers: 0
patch_size: 4
dict_kwargs:
root: 'tests/data/vhr10'
4 changes: 1 addition & 3 deletions tests/conf/vhr10.yaml → tests/conf/vhr10_obj_det.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ model:
class_path: ObjectDetectionTask
init_args:
model: 'faster-rcnn'
backbone: 'resnet50'
backbone: 'resnet18'
num_classes: 11
lr: 2.5e-5
patience: 10
data:
class_path: VHR10DataModule
init_args:
Expand Down
6 changes: 3 additions & 3 deletions tests/datasets/test_vhr10.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ def test_plot(self, dataset: VHR10) -> None:
scores = [0.7, 0.3, 0.7]
for i in range(3):
x = dataset[i]
x['prediction_labels'] = x['label']
x['prediction_label'] = x['label']
x['prediction_bbox_xyxy'] = x['bbox_xyxy']
x['prediction_scores'] = torch.Tensor([scores[i]])
x['prediction_score'] = torch.Tensor([scores[i]])
if 'mask' in x:
x['prediction_masks'] = x['mask']
x['prediction_mask'] = x['mask']
dataset.plot(x, show_feats='masks')
plt.close()
2 changes: 1 addition & 1 deletion tests/trainers/test_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def plot(*args: Any, **kwargs: Any) -> None:


class TestObjectDetectionTask:
@pytest.mark.parametrize('name', ['nasa_marine_debris', 'vhr10'])
@pytest.mark.parametrize('name', ['nasa_marine_debris', 'vhr10_obj_det'])
@pytest.mark.parametrize('model_name', ['faster-rcnn', 'fcos', 'retinanet'])
def test_trainer(
self, monkeypatch: MonkeyPatch, name: str, model_name: str, fast_dev_run: bool
Expand Down
125 changes: 125 additions & 0 deletions tests/trainers/test_instance_segmentation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import os
from typing import Any

import pytest
from lightning.pytorch import Trainer
from pytest import MonkeyPatch

from torchgeo.datamodules import MisconfigurationException, VHR10DataModule
from torchgeo.datasets import VHR10, RGBBandsMissingError
from torchgeo.main import main
from torchgeo.trainers import InstanceSegmentationTask

# mAP metric requires pycocotools to be installed
pytest.importorskip('pycocotools')


class PredictInstanceSegmentationDataModule(VHR10DataModule):
def setup(self, stage: str) -> None:
self.predict_dataset = VHR10(**self.kwargs)


def plot(*args: Any, **kwargs: Any) -> None:
return None


def plot_missing_bands(*args: Any, **kwargs: Any) -> None:
raise RGBBandsMissingError()


class TestInstanceSegmentationTask:
@pytest.mark.parametrize('name', ['vhr10_ins_seg'])
def test_trainer(
self, monkeypatch: MonkeyPatch, name: str, fast_dev_run: bool
) -> None:
config = os.path.join('tests', 'conf', name + '.yaml')

args = [
'--config',
config,
'--trainer.accelerator',
'cpu',
'--trainer.fast_dev_run',
str(fast_dev_run),
'--trainer.max_epochs',
'1',
'--trainer.log_every_n_steps',
'1',
]

main(['fit', *args])
try:
main(['test', *args])
except MisconfigurationException:
pass
try:
main(['predict', *args])
except MisconfigurationException:
pass

def test_invalid_model(self) -> None:
match = 'Invalid model type'
with pytest.raises(ValueError, match=match):
InstanceSegmentationTask(model='invalid_model')

def test_invalid_backbone(self) -> None:
match = 'Invalid backbone type'
with pytest.raises(ValueError, match=match):
InstanceSegmentationTask(backbone='invalid_backbone')

def test_weights(self) -> None:
InstanceSegmentationTask(weights=True, num_classes=3)
InstanceSegmentationTask(weights=True, num_classes=91)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yet another test that downloads data on the fly (#1088), but let's fix that another day when we figure out how to support custom weights.


def test_no_plot_method(self, monkeypatch: MonkeyPatch, fast_dev_run: bool) -> None:
monkeypatch.setattr(VHR10DataModule, 'plot', plot)
datamodule = VHR10DataModule(
root='tests/data/vhr10', batch_size=1, num_workers=0
)
model = InstanceSegmentationTask(in_channels=3, num_classes=11)
trainer = Trainer(
accelerator='cpu',
fast_dev_run=fast_dev_run,
log_every_n_steps=1,
max_epochs=1,
)
trainer.validate(model=model, datamodule=datamodule)

def test_no_rgb(self, monkeypatch: MonkeyPatch, fast_dev_run: bool) -> None:
monkeypatch.setattr(VHR10DataModule, 'plot', plot_missing_bands)
datamodule = VHR10DataModule(
root='tests/data/vhr10', batch_size=1, num_workers=0
)
model = InstanceSegmentationTask(in_channels=3, num_classes=11)
trainer = Trainer(
accelerator='cpu',
fast_dev_run=fast_dev_run,
log_every_n_steps=1,
max_epochs=1,
)
trainer.validate(model=model, datamodule=datamodule)

def test_predict(self, fast_dev_run: bool) -> None:
datamodule = PredictInstanceSegmentationDataModule(
root='tests/data/vhr10', batch_size=1, num_workers=0
)
model = InstanceSegmentationTask(num_classes=11)
trainer = Trainer(
accelerator='cpu',
fast_dev_run=fast_dev_run,
log_every_n_steps=1,
max_epochs=1,
)
trainer.predict(model=model, datamodule=datamodule)

def test_freeze_backbone(self) -> None:
task = InstanceSegmentationTask(freeze_backbone=True)
for param in task.model.backbone.parameters():
assert param.requires_grad is False

for head in ['rpn', 'roi_heads']:
for param in getattr(task.model, head).parameters():
assert param.requires_grad is True
20 changes: 10 additions & 10 deletions torchgeo/datasets/vhr10.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def __getitem__(self, index: int) -> dict[str, Any]:
sample = self.coco_convert(sample)
sample['class'] = sample['label']['labels']
sample['bbox_xyxy'] = sample['label']['boxes']
sample['mask'] = sample['label']['masks'].float()
sample['mask'] = sample['label']['masks']
sample['label'] = sample.pop('class')

if self.transforms is not None:
Expand Down Expand Up @@ -409,21 +409,21 @@ def plot(
n_gt = len(boxes)

ncols = 1
show_predictions = 'prediction_labels' in sample
show_predictions = 'prediction_label' in sample

if show_predictions:
show_pred_boxes = False
show_pred_masks = False
prediction_labels = sample['prediction_labels'].numpy()
prediction_scores = sample['prediction_scores'].numpy()
prediction_label = sample['prediction_label'].numpy()
prediction_score = sample['prediction_score'].numpy()
if 'prediction_bbox_xyxy' in sample:
prediction_bbox_xyxy = sample['prediction_bbox_xyxy'].numpy()
show_pred_boxes = True
if 'prediction_masks' in sample:
prediction_masks = sample['prediction_masks'].numpy()
if 'prediction_mask' in sample:
prediction_mask = sample['prediction_mask'].numpy()
show_pred_masks = True

n_pred = len(prediction_labels)
n_pred = len(prediction_label)
ncols += 1

# Display image
Expand Down Expand Up @@ -476,11 +476,11 @@ def plot(
axs[0, 1].imshow(image)
axs[0, 1].axis('off')
for i in range(n_pred):
score = prediction_scores[i]
score = prediction_score[i]
if score < 0.5:
continue

class_num = prediction_labels[i]
class_num = prediction_label[i]
color = cm(class_num / len(self.categories))

if show_pred_boxes:
Expand Down Expand Up @@ -512,7 +512,7 @@ def plot(

# Add masks
if show_pred_masks:
mask = prediction_masks[i]
mask = prediction_mask[i]
contours = skimage.measure.find_contours(mask, 0.5)
for verts in contours:
verts = np.fliplr(verts)
Expand Down
8 changes: 1 addition & 7 deletions torchgeo/models/fcsiam.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,7 @@ def __init__(
)
encoder_out_channels = [c * 2 for c in self.encoder.out_channels[1:]]
encoder_out_channels.insert(0, self.encoder.out_channels[0])
try:
# smp 0.3+
UnetDecoder = smp.decoders.unet.decoder.UnetDecoder
except AttributeError:
# smp 0.2
UnetDecoder = smp.unet.decoder.UnetDecoder
self.decoder = UnetDecoder(
self.decoder = smp.decoders.unet.decoder.UnetDecoder(
encoder_channels=encoder_out_channels,
decoder_channels=decoder_channels,
n_blocks=encoder_depth,
Expand Down
2 changes: 2 additions & 0 deletions torchgeo/trainers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from .byol import BYOLTask
from .classification import ClassificationTask, MultiLabelClassificationTask
from .detection import ObjectDetectionTask
from .instance_segmentation import InstanceSegmentationTask
from .iobench import IOBenchTask
from .moco import MoCoTask
from .regression import PixelwiseRegressionTask, RegressionTask
Expand All @@ -18,6 +19,7 @@
'BaseTask',
'ClassificationTask',
'IOBenchTask',
'InstanceSegmentationTask',
'MoCoTask',
'MultiLabelClassificationTask',
'ObjectDetectionTask',
Expand Down
4 changes: 2 additions & 2 deletions torchgeo/trainers/detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,8 @@ def validation_step(
):
datamodule = self.trainer.datamodule
batch['prediction_bbox_xyxy'] = [b['boxes'].cpu() for b in y_hat]
batch['prediction_labels'] = [b['labels'].cpu() for b in y_hat]
batch['prediction_scores'] = [b['scores'].cpu() for b in y_hat]
batch['prediction_label'] = [b['labels'].cpu() for b in y_hat]
batch['prediction_score'] = [b['scores'].cpu() for b in y_hat]
batch['image'] = batch['image'].cpu()
sample = unbind_samples(batch)[0]
# Convert image to uint8 for plotting
Expand Down
Loading