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

New datamodules design #572

Merged
merged 84 commits into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
84 commits
Select commit Hold shift + click to select a range
ee1cfce
move sample generation to datamodule instead of dataset
djdameln Sep 9, 2022
ec5199e
move sample generation from init to setup
djdameln Sep 12, 2022
9f0a35e
remove inference stage and add base classes
djdameln Sep 13, 2022
dea176f
replace dataset classes with AnomalibDataset
djdameln Sep 13, 2022
62a04f8
move setup to base class, create samples as class method
djdameln Sep 13, 2022
e91afad
update docstrings
djdameln Sep 13, 2022
df4a805
refactor btech to new format
djdameln Sep 14, 2022
c225a83
allow training with no anomalous data
djdameln Sep 14, 2022
ac0dc8a
remove MVTec name from comment
djdameln Sep 15, 2022
5d90209
raise NotImplementedError in base class
djdameln Sep 15, 2022
c1e6724
allow both png and bmp images for btech
djdameln Sep 15, 2022
2d70d89
use label_index to check if dataset contains anomalous images
djdameln Sep 16, 2022
f5f17db
refactor getitem in dataset class
djdameln Sep 16, 2022
f02065f
use iloc for indexing
djdameln Sep 16, 2022
9cba9da
move dataloader getters to base class
djdameln Sep 16, 2022
5b3e841
refactor to add validate stage in setup
djdameln Sep 16, 2022
f652227
implement alternative datamodules solution
djdameln Sep 21, 2022
0e565a4
small improvements
djdameln Sep 21, 2022
297195a
improve design
djdameln Oct 7, 2022
94cabb7
remove unused constructor arguments
djdameln Oct 7, 2022
1ee8a96
adapt btech to new design
djdameln Oct 7, 2022
7fc5483
add prepare_data method for mvtec
djdameln Oct 7, 2022
8a9a30c
solve merge conflicts
djdameln Oct 7, 2022
1ac7c65
implement more generic random splitting function
djdameln Oct 10, 2022
965ea94
update docstrings for folder module
djdameln Oct 10, 2022
2a9f6f8
ensure type consistency when performing operations on dataset
djdameln Oct 10, 2022
84997b9
change imports
djdameln Oct 10, 2022
f21c652
change variable names
djdameln Oct 10, 2022
ab7d0ff
replace pass with NotImplementedError
djdameln Oct 10, 2022
d7e47a9
allow training on folder without test images
djdameln Oct 11, 2022
da851c6
use relative path for normal_test_dir
djdameln Oct 11, 2022
f3e38ba
fix dataset tests
djdameln Oct 11, 2022
f4719f2
update validation set parameter in configs
djdameln Oct 11, 2022
e25a587
change default argument
djdameln Oct 11, 2022
1170ca3
Merge branch 'main' into da/datamodules-alternative
djdameln Oct 11, 2022
fb84cd1
use setter for samples
djdameln Oct 12, 2022
cfa4f52
hint options for val_split_mode
djdameln Oct 12, 2022
624e522
update assert message and docstring
djdameln Oct 12, 2022
0bd77f9
revert name change dataset vs datamodule
djdameln Oct 12, 2022
6bed98f
typing and docstrings
djdameln Oct 12, 2022
fc34f8e
remove samples argument from dataset constructor
djdameln Oct 12, 2022
1482c13
val/test -> eval
djdameln Oct 12, 2022
e168163
remove Split.Full from enum
djdameln Oct 13, 2022
5071dcf
sort samples when setting
djdameln Oct 13, 2022
e175d7d
update warn message
djdameln Oct 13, 2022
03773b0
formatting
djdameln Oct 13, 2022
3910c32
use setter when creating samples in dataset classes
djdameln Oct 13, 2022
894ef12
add tests for new dataset class
djdameln Oct 13, 2022
44009e2
add test case for label aware random split
djdameln Oct 13, 2022
012ed47
update parameter name in inferencers
djdameln Oct 14, 2022
62b176e
move _setup implementation to base class
djdameln Oct 14, 2022
7e957b6
address codacy issues
djdameln Oct 14, 2022
25f503d
fix pylint issues
djdameln Oct 14, 2022
1245928
codacy
djdameln Oct 14, 2022
d9bd6e0
Merge branch 'main' into da/datamodules-alternative
djdameln Oct 14, 2022
0459a0d
update example dataset config in docs
djdameln Oct 14, 2022
30dc45a
fix test
djdameln Oct 14, 2022
85c475a
move base classes to separate files (avoid circular import)
djdameln Oct 14, 2022
cc32896
add base classes
djdameln Oct 14, 2022
23d4766
update docstring
djdameln Oct 14, 2022
e8d7998
fix imports
djdameln Oct 14, 2022
9c4e7bf
validation_split_mode -> val_split_mode
djdameln Oct 18, 2022
067d601
update docs
djdameln Oct 19, 2022
c84c99c
Update anomalib/data/base/dataset.py
djdameln Oct 21, 2022
b680d44
get length from self.samples
djdameln Oct 21, 2022
95c37b0
assert unique indices
djdameln Oct 21, 2022
3e77014
check is_setup for individual datasets
djdameln Oct 21, 2022
ede213a
remove assert in __getitem_\
djdameln Oct 21, 2022
f5e2d24
Update anomalib/data/btech.py
djdameln Oct 21, 2022
d9e1369
clearer assert message
djdameln Oct 21, 2022
2e6bc60
clarify list inversion in comment
djdameln Oct 21, 2022
af0cd99
comments and typing
djdameln Oct 21, 2022
d508786
Merge branch 'da/datamodules-alternative' of https://github.com/openv…
djdameln Oct 21, 2022
c85713c
Merge branch 'main' into da/datamodules-alternative
djdameln Oct 21, 2022
5ee8480
validate contents of samples dataframe before setting
djdameln Oct 21, 2022
a5e876a
add file paths check
djdameln Oct 21, 2022
c490e30
add seed to random_split function
djdameln Oct 21, 2022
4808287
fix expected columns
djdameln Oct 24, 2022
10bbf9c
fix typo
djdameln Oct 24, 2022
81d3ca3
add seed parameter to datamodules
djdameln Oct 28, 2022
b372dd1
set global seed in test entrypoint
djdameln Oct 28, 2022
e07a12c
add NONE option to valsplitmode
djdameln Oct 28, 2022
ffdb47c
clarify setup behaviour in docstring
djdameln Oct 28, 2022
dedfd4b
fix typo
djdameln Oct 31, 2022
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
33 changes: 26 additions & 7 deletions anomalib/data/base/datamodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,23 @@ class AnomalibDataModule(LightningDataModule, ABC):
train_batch_size (int): Batch size used by the train dataloader.
test_batch_size (int): Batch size used by the val and test dataloaders.
num_workers (int): Number of workers used by the train, val and test dataloaders.
seed (Optional[int], optional): Seed used during random subset splitting.
"""

def __init__(self, train_batch_size: int, eval_batch_size: int, num_workers: int, val_split_mode: ValSplitMode):
def __init__(
self,
train_batch_size: int,
eval_batch_size: int,
num_workers: int,
val_split_mode: ValSplitMode,
seed: Optional[int] = None,
):
super().__init__()
self.train_batch_size = train_batch_size
self.eval_batch_size = eval_batch_size
self.num_workers = num_workers
self.val_split_mode = val_split_mode
self.seed = seed

self.train_data: Optional[AnomalibDataset] = None
self.val_data: Optional[AnomalibDataset] = None
Expand All @@ -55,26 +64,36 @@ def setup(self, stage: Optional[str] = None):
def _setup(self, _stage: Optional[str] = None) -> None:
"""Set up the datasets and perform dynamic subset splitting.

May be overridden in subclass for custom splitting behaviour.
This method yay be overridden in subclass for custom splitting behaviour.
djdameln marked this conversation as resolved.
Show resolved Hide resolved

Note: The stage argument is not used here. This is because, for a given instance of an AnomalibDataModule
subclass, all three subsets are created at the first call of setup(). This is to accommodate the subset
splitting behaviour of anomaly tasks, where the validation set is usually extracted from the test set, and
the test set must therefore be created as early as the `fit` stage.
"""
assert self.train_data is not None
assert self.test_data is not None

self.train_data.setup()
self.test_data.setup()
if self.val_split_mode == ValSplitMode.FROM_TEST:
self.val_data, self.test_data = random_split(self.test_data, [0.5, 0.5], label_aware=True)
self.val_data, self.test_data = random_split(self.test_data, [0.5, 0.5], label_aware=True, seed=self.seed)
elif self.val_split_mode == ValSplitMode.SAME_AS_TEST:
self.val_data = self.test_data
else:
elif self.val_split_mode != ValSplitMode.NONE:
raise ValueError(f"Unknown validation split mode: {self.val_split_mode}")

@property
def is_setup(self):
"""Checks if setup() has been called."""
if self.train_data is None or self.val_data is None or self.test_data is None:
return False
return self.train_data.is_setup and self.val_data.is_setup and self.test_data.is_setup
# at least one of [train_data, val_data, test_data] should be setup
if self.train_data is not None and self.train_data.is_setup:
return True
if self.val_data is not None and self.val_data.is_setup:
return True
if self.test_data is not None and self.test_data.is_setup:
return True
return False

def train_dataloader(self) -> TRAIN_DATALOADERS:
"""Get train dataloader."""
Expand Down
6 changes: 3 additions & 3 deletions anomalib/data/btech.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ def __init__(
pre_process: List of pre_processing object containing albumentation compose.
split: 'train', 'val' or 'test'
task: ``classification`` or ``segmentation``
seed: seed used for the random subset splitting
create_validation_set: Create a validation subset in addition to the train and test subsets

Examples:
Expand Down Expand Up @@ -182,6 +181,7 @@ def __init__(
transform_config_train: Optional[Union[str, A.Compose]] = None,
transform_config_eval: Optional[Union[str, A.Compose]] = None,
val_split_mode: ValSplitMode = ValSplitMode.SAME_AS_TEST,
seed: Optional[int] = None,
) -> None:
"""Instantiate BTech Lightning Data Module.

Expand All @@ -195,8 +195,8 @@ def __init__(
task: ``classification`` or ``segmentation``
transform_config_train: Config for pre-processing during training.
transform_config_val: Config for pre-processing during validation.
seed: seed used for the random subset splitting
create_validation_set: Create a validation subset in addition to the train and test subsets
seed (Optional[int], optional): Seed used during random subset splitting.

Examples:
>>> from anomalib.data import BTech
Expand Down Expand Up @@ -224,7 +224,7 @@ def __init__(
>>> data["image"].shape, data["mask"].shape
(torch.Size([32, 3, 256, 256]), torch.Size([32, 256, 256]))
"""
super().__init__(train_batch_size, eval_batch_size, num_workers, val_split_mode)
super().__init__(train_batch_size, eval_batch_size, num_workers, val_split_mode, seed)

self.root = Path(root)
self.category = Path(category)
Expand Down
5 changes: 4 additions & 1 deletion anomalib/data/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ class Folder(AnomalibDataModule):
during validation.
Defaults to None.
val_split_mode (ValSplitMode): Setting that determines how the validation subset is obtained.
seed (Optional[int], optional): Seed used during random subset splitting.
"""

def __init__(
Expand All @@ -251,12 +252,14 @@ def __init__(
transform_config_train: Optional[Union[str, A.Compose]] = None,
transform_config_eval: Optional[Union[str, A.Compose]] = None,
val_split_mode: ValSplitMode = ValSplitMode.FROM_TEST,
seed: Optional[int] = None,
):
super().__init__(
train_batch_size=train_batch_size,
eval_batch_size=eval_batch_size,
num_workers=num_workers,
val_split_mode=val_split_mode,
seed=seed,
)

self.split_ratio = split_ratio
Expand Down Expand Up @@ -298,7 +301,7 @@ def _setup(self, _stage: Optional[str] = None):

# add some normal images to the test set
if not self.test_data.has_normal:
self.train_data, normal_test_data = random_split(self.train_data, self.split_ratio)
self.train_data, normal_test_data = random_split(self.train_data, self.split_ratio, seed=self.seed)
self.test_data += normal_test_data

super()._setup()
2 changes: 2 additions & 0 deletions anomalib/data/mvtec.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,14 @@ def __init__(
transform_config_train: Optional[Union[str, A.Compose]] = None,
transform_config_eval: Optional[Union[str, A.Compose]] = None,
val_split_mode: ValSplitMode = ValSplitMode.SAME_AS_TEST,
seed: Optional[int] = None,
):
super().__init__(
train_batch_size=train_batch_size,
eval_batch_size=eval_batch_size,
num_workers=num_workers,
val_split_mode=val_split_mode,
seed=seed,
)

self.root = Path(root)
Expand Down
1 change: 1 addition & 0 deletions anomalib/data/utils/split.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class Split(str, Enum):
class ValSplitMode(str, Enum):
"""Splitting mode used to obtain validation subset."""

NONE = "none"
SAME_AS_TEST = "same_as_test"
FROM_TEST = "from_test"

Expand Down
5 changes: 4 additions & 1 deletion tools/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from argparse import ArgumentParser, Namespace

from pytorch_lightning import Trainer
from pytorch_lightning import Trainer, seed_everything

from anomalib.config import get_configurable_parameters
from anomalib.data import get_datamodule
Expand Down Expand Up @@ -40,6 +40,9 @@ def test():
weight_file=args.weight_file,
)

if config.project.seed:
seed_everything(config.project.seed)

datamodule = get_datamodule(config)
model = get_model(config)

Expand Down