Skip to content
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

Trainers: add Instance Segmentation Task #2513

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 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
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
230 changes: 230 additions & 0 deletions tests/trainers/test_instance_segmentation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import os
from pathlib import Path
from typing import Any, cast

import pytest
import segmentation_models_pytorch as smp

Check failure on line 9 in tests/trainers/test_instance_segmentation.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

tests/trainers/test_instance_segmentation.py:9:39: F401 `segmentation_models_pytorch` imported but unused
import timm
import torch
import torch.nn as nn
from lightning.pytorch import Trainer
from pytest import MonkeyPatch
from torch.nn.modules import Module
from torchvision.models._api import WeightsEnum

from torchgeo.datamodules import MisconfigurationException, SEN12MSDataModule
from torchgeo.datasets import LandCoverAI, RGBBandsMissingError

Check failure on line 19 in tests/trainers/test_instance_segmentation.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

tests/trainers/test_instance_segmentation.py:19:31: F401 `torchgeo.datasets.LandCoverAI` imported but unused
from torchgeo.main import main
from torchgeo.models import ResNet18_Weights
from torchgeo.trainers import InstanceSegmentationTask


class SegmentationTestModel(Module):
def __init__(self, in_channels: int = 3, classes: int = 3, **kwargs: Any) -> None:
super().__init__()
self.conv1 = nn.Conv2d(
in_channels=in_channels, out_channels=classes, kernel_size=1, padding=0
)

def forward(self, x: torch.Tensor) -> torch.Tensor:
return cast(torch.Tensor, self.conv1(x))


def create_model(**kwargs: Any) -> Module:
return SegmentationTestModel(**kwargs)


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


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


class TestSemanticSegmentationTask:
@pytest.mark.parametrize(
'name',
[
'agrifieldnet',
'cabuar',
'chabud',
'chesapeake_cvpr_5',
'chesapeake_cvpr_7',
'deepglobelandcover',
'etci2021',
'ftw',
'geonrw',
'gid15',
'inria',
'l7irish',
'l8biome',
'landcoverai',
'landcoverai100',
'loveda',
'naipchesapeake',
'potsdam2d',
'sen12ms_all',
'sen12ms_s1',
'sen12ms_s2_all',
'sen12ms_s2_reduced',
'sentinel2_cdl',
'sentinel2_eurocrops',
'sentinel2_nccm',
'sentinel2_south_america_soybean',
'southafricacroptype',
'spacenet1',
'spacenet6',
'ssl4eo_l_benchmark_cdl',
'ssl4eo_l_benchmark_nlcd',
'vaihingen2d',
],
)
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

@pytest.fixture
def weights(self) -> WeightsEnum:
return ResNet18_Weights.SENTINEL2_ALL_MOCO

@pytest.fixture
def mocked_weights(
self,
tmp_path: Path,
monkeypatch: MonkeyPatch,
weights: WeightsEnum,
load_state_dict_from_url: None,
) -> WeightsEnum:
path = tmp_path / f'{weights}.pth'
model = timm.create_model(
weights.meta['model'], in_chans=weights.meta['in_chans']
)
torch.save(model.state_dict(), path)
try:
monkeypatch.setattr(weights.value, 'url', str(path))
except AttributeError:
monkeypatch.setattr(weights, 'url', str(path))
return weights

def test_weight_file(self, checkpoint: str) -> None:
InstanceSegmentationTask(backbone='resnet18', weights=checkpoint, num_classes=6)

def test_weight_enum(self, mocked_weights: WeightsEnum) -> None:
InstanceSegmentationTask(
backbone=mocked_weights.meta['model'],
weights=mocked_weights,
in_channels=mocked_weights.meta['in_chans'],
)

def test_weight_str(self, mocked_weights: WeightsEnum) -> None:
InstanceSegmentationTask(
backbone=mocked_weights.meta['model'],
weights=str(mocked_weights),
in_channels=mocked_weights.meta['in_chans'],
)

@pytest.mark.slow
def test_weight_enum_download(self, weights: WeightsEnum) -> None:
InstanceSegmentationTask(
backbone=weights.meta['model'],
weights=weights,
in_channels=weights.meta['in_chans'],
)

@pytest.mark.slow
def test_weight_str_download(self, weights: WeightsEnum) -> None:
InstanceSegmentationTask(
backbone=weights.meta['model'],
weights=str(weights),
in_channels=weights.meta['in_chans'],
)

def test_invalid_model(self) -> None:
match = "Model type 'invalid_model' is not valid."
with pytest.raises(ValueError, match=match):
InstanceSegmentationTask(model='invalid_model')

def test_invalid_loss(self) -> None:
match = "Loss type 'invalid_loss' is not valid."
with pytest.raises(ValueError, match=match):
InstanceSegmentationTask(loss='invalid_loss')

def test_no_plot_method(self, monkeypatch: MonkeyPatch, fast_dev_run: bool) -> None:
monkeypatch.setattr(SEN12MSDataModule, 'plot', plot)
datamodule = SEN12MSDataModule(
root='tests/data/sen12ms', batch_size=1, num_workers=0
)
model = InstanceSegmentationTask(
backbone='resnet18', in_channels=15, num_classes=6
)
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(SEN12MSDataModule, 'plot', plot_missing_bands)
datamodule = SEN12MSDataModule(
root='tests/data/sen12ms', batch_size=1, num_workers=0
)
model = InstanceSegmentationTask(
backbone='resnet18', in_channels=15, num_classes=6
)
trainer = Trainer(
accelerator='cpu',
fast_dev_run=fast_dev_run,
log_every_n_steps=1,
max_epochs=1,
)
trainer.validate(model=model, datamodule=datamodule)

@pytest.mark.parametrize('model_name', ['unet', 'deeplabv3+'])
@pytest.mark.parametrize(
'backbone', ['resnet18', 'mobilenet_v2', 'efficientnet-b0']
)
def test_freeze_backbone(self, model_name: str, backbone: str) -> None:
model = InstanceSegmentationTask(
model=model_name, backbone=backbone, freeze_backbone=True
)
assert all(
[param.requires_grad is False for param in model.model.encoder.parameters()]
)
assert all([param.requires_grad for param in model.model.decoder.parameters()])
assert all(
[
param.requires_grad
for param in model.model.segmentation_head.parameters()
]
)
2 changes: 2 additions & 0 deletions torchgeo/trainers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@

"""TorchGeo trainers."""

from .base import BaseTask
from .byol import BYOLTask
from .classification import ClassificationTask, MultiLabelClassificationTask
from .detection import ObjectDetectionTask
from .iobench import IOBenchTask

Check failure on line 10 in torchgeo/trainers/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

torchgeo/trainers/__init__.py:10:22: F401 `.iobench.IOBenchTask` imported but unused; consider removing, adding to `__all__`, or using a redundant alias
from .moco import MoCoTask
from .regression import PixelwiseRegressionTask, RegressionTask
from .segmentation import SemanticSegmentationTask
from .simclr import SimCLRTask
from .instance_segmentation import InstanceSegmentationTask

Check failure on line 15 in torchgeo/trainers/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

torchgeo/trainers/__init__.py:6:1: I001 Import block is un-sorted or un-formatted

Check failure on line 15 in torchgeo/trainers/__init__.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

torchgeo/trainers/__init__.py:15:36: F401 `.instance_segmentation.InstanceSegmentationTask` imported but unused; consider removing, adding to `__all__`, or using a redundant alias

__all__ = (
'BYOLTask',
'BaseTask',
'ClassificationTask',
'InstanceSegmentationTask'
'IOBenchTask',
'MoCoTask',
'MultiLabelClassificationTask',
Expand Down
Loading
Loading