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 63 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
21 changes: 21 additions & 0 deletions anomalib/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,27 @@ def get_configurable_parameters(
if "format" not in config.dataset.keys():
config.dataset.format = "mvtec"

if "create_validation_set" in config.dataset.keys():
warn(
"The 'create_validation_set' parameter is deprecated and will be removed in v0.4.0. Please use "
"'validation_split_mode' instead."
)
config.dataset.validation_split_mode = "from_test" if config.dataset.create_validation_set else "same_as_test"

if "test_batch_size" in config.dataset.keys():
warn(
"The 'test_batch_size' parameter is deprecated and will be removed in v0.4.0. Please use "
"'eval_batch_size' instead."
)
config.dataset.eval_batch_size = config.dataset.test_batch_size

if "transform_config" in config.dataset.keys() and "val" in config.dataset.transform_config.keys():
warn(
"The 'transform_config.val' parameter is deprecated and will be removed in v0.4.0. Please use "
"'transform_config.eval' instead."
)
config.dataset.transform_config.eval = config.dataset.transform_config.val

config = update_input_size_config(config)

# Project Configs
Expand Down
31 changes: 14 additions & 17 deletions anomalib/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from typing import Union

from omegaconf import DictConfig, ListConfig
from pytorch_lightning import LightningDataModule

from .base import AnomalibDataModule, AnomalibDataset
from .btech import BTech
from .folder import Folder
from .inference import InferenceDataset
Expand All @@ -17,7 +17,7 @@
logger = logging.getLogger(__name__)


def get_datamodule(config: Union[DictConfig, ListConfig]) -> LightningDataModule:
def get_datamodule(config: Union[DictConfig, ListConfig]) -> AnomalibDataModule:
"""Get Anomaly Datamodule.

Args:
Expand All @@ -28,37 +28,33 @@ def get_datamodule(config: Union[DictConfig, ListConfig]) -> LightningDataModule
"""
logger.info("Loading the datamodule")

datamodule: LightningDataModule
datamodule: AnomalibDataModule

if config.dataset.format.lower() == "mvtec":
datamodule = MVTec(
# TODO: Remove config values. IAAALD-211
root=config.dataset.path,
category=config.dataset.category,
image_size=(config.dataset.image_size[0], config.dataset.image_size[1]),
train_batch_size=config.dataset.train_batch_size,
test_batch_size=config.dataset.test_batch_size,
eval_batch_size=config.dataset.eval_batch_size,
num_workers=config.dataset.num_workers,
seed=config.project.seed,
task=config.dataset.task,
transform_config_train=config.dataset.transform_config.train,
transform_config_val=config.dataset.transform_config.val,
create_validation_set=config.dataset.create_validation_set,
transform_config_eval=config.dataset.transform_config.eval,
val_split_mode=config.dataset.val_split_mode,
)
elif config.dataset.format.lower() == "btech":
datamodule = BTech(
# TODO: Remove config values. IAAALD-211
root=config.dataset.path,
category=config.dataset.category,
image_size=(config.dataset.image_size[0], config.dataset.image_size[1]),
train_batch_size=config.dataset.train_batch_size,
test_batch_size=config.dataset.test_batch_size,
eval_batch_size=config.dataset.eval_batch_size,
num_workers=config.dataset.num_workers,
seed=config.project.seed,
task=config.dataset.task,
transform_config_train=config.dataset.transform_config.train,
transform_config_val=config.dataset.transform_config.val,
create_validation_set=config.dataset.create_validation_set,
transform_config_eval=config.dataset.transform_config.eval,
val_split_mode=config.dataset.val_split_mode,
)
elif config.dataset.format.lower() == "folder":
datamodule = Folder(
Expand All @@ -70,14 +66,13 @@ def get_datamodule(config: Union[DictConfig, ListConfig]) -> LightningDataModule
mask_dir=config.dataset.mask,
extensions=config.dataset.extensions,
split_ratio=config.dataset.split_ratio,
seed=config.project.seed,
image_size=(config.dataset.image_size[0], config.dataset.image_size[1]),
train_batch_size=config.dataset.train_batch_size,
test_batch_size=config.dataset.test_batch_size,
eval_batch_size=config.dataset.eval_batch_size,
num_workers=config.dataset.num_workers,
transform_config_train=config.dataset.transform_config.train,
transform_config_val=config.dataset.transform_config.val,
create_validation_set=config.dataset.create_validation_set,
transform_config_eval=config.dataset.transform_config.eval,
val_split_mode=config.dataset.val_split_mode,
)
else:
raise ValueError(
Expand All @@ -90,6 +85,8 @@ def get_datamodule(config: Union[DictConfig, ListConfig]) -> LightningDataModule


__all__ = [
"AnomalibDataset",
"AnomalibDataModule",
"get_datamodule",
"BTech",
"Folder",
Expand Down
10 changes: 10 additions & 0 deletions anomalib/data/base/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Base classes for custom dataset and datamodules."""

# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0


from .datamodule import AnomalibDataModule
from .dataset import AnomalibDataset

__all__ = ["AnomalibDataset", "AnomalibDataModule"]
89 changes: 89 additions & 0 deletions anomalib/data/base/datamodule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Anomalib datamodule base class."""

# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations

import logging
from abc import ABC
from typing import Optional

from pandas import DataFrame
from pytorch_lightning import LightningDataModule
from pytorch_lightning.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS
from torch.utils.data import DataLoader

from anomalib.data.base.dataset import AnomalibDataset
from anomalib.data.utils import ValSplitMode, random_split

logger = logging.getLogger(__name__)


class AnomalibDataModule(LightningDataModule, ABC):
"""Base Anomalib data module.

Args:
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.
"""

def __init__(self, train_batch_size: int, eval_batch_size: int, num_workers: int, val_split_mode: ValSplitMode):
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.train_data: Optional[AnomalibDataset] = None
self.val_data: Optional[AnomalibDataset] = None
self.test_data: Optional[AnomalibDataset] = None

self._samples: Optional[DataFrame] = None

def setup(self, stage: Optional[str] = None):
"""Setup train, validation and test data.

Args:
stage: Optional[str]: Train/Val/Test stages. (Default value = None)
"""
if not self.is_setup:
self._setup(stage)
assert self.is_setup

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.
"""
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)
elif self.val_split_mode == ValSplitMode.SAME_AS_TEST:
self.val_data = self.test_data
else:
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

def train_dataloader(self) -> TRAIN_DATALOADERS:
"""Get train dataloader."""
return DataLoader(self.train_data, shuffle=True, batch_size=self.train_batch_size, num_workers=self.num_workers)

def val_dataloader(self) -> EVAL_DATALOADERS:
"""Get validation dataloader."""
return DataLoader(self.val_data, shuffle=False, batch_size=self.eval_batch_size, num_workers=self.num_workers)

def test_dataloader(self) -> EVAL_DATALOADERS:
"""Get test dataloader."""
return DataLoader(self.test_data, shuffle=False, batch_size=self.eval_batch_size, num_workers=self.num_workers)
155 changes: 155 additions & 0 deletions anomalib/data/base/dataset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""Anomalib dataset base class."""

# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations

import copy
import logging
from abc import ABC, abstractmethod
from typing import Dict, Sequence, Union

import cv2
import numpy as np
import pandas as pd
from pandas import DataFrame
from torch import Tensor
from torch.utils.data import Dataset

from anomalib.data.utils import read_image
from anomalib.pre_processing import PreProcessor

logger = logging.getLogger(__name__)


class AnomalibDataset(Dataset, ABC):
"""Anomalib dataset."""

def __init__(self, task: str, pre_process: PreProcessor):
super().__init__()
self.task = task
self.pre_process = pre_process
self._samples = None
djdameln marked this conversation as resolved.
Show resolved Hide resolved

def __len__(self) -> int:
"""Get length of the dataset."""
assert isinstance(self._samples, DataFrame)
return len(self._samples)
djdameln marked this conversation as resolved.
Show resolved Hide resolved

def subsample(self, indices: Sequence[int], inplace=False) -> AnomalibDataset:
"""Subsamples the dataset at the provided indices.

Args:
indices (Sequence[int]): Indices at which the dataset is to be subsampled.
inplace (bool): When true, the subsampling will be performed on the instance itself.
"""
dataset = self if inplace else copy.deepcopy(self)
dataset.samples = self.samples.iloc[indices].reset_index(drop=True)
djdameln marked this conversation as resolved.
Show resolved Hide resolved
return dataset

@property
def is_setup(self) -> bool:
"""Checks if setup() been called."""
return isinstance(self._samples, DataFrame)

@property
def samples(self) -> DataFrame:
"""Get the samples dataframe."""
if not self.is_setup:
raise RuntimeError("Dataset is not setup yet. Call setup() first.")
return self._samples

@samples.setter
def samples(self, samples: DataFrame):
"""Overwrite the samples with a new dataframe.

Args:
samples (DataFrame): DataFrame with new samples.
"""
self._samples = samples.sort_values(by="image_path", ignore_index=True)
djdameln marked this conversation as resolved.
Show resolved Hide resolved

@property
def has_normal(self) -> bool:
"""Check if the dataset contains any normal samples."""
return 0 in list(self.samples.label_index)

@property
def has_anomalous(self) -> bool:
"""Check if the dataset contains any anomalous samples."""
return 1 in list(self.samples.label_index)

def __getitem__(self, index: int) -> Dict[str, Union[str, Tensor]]:
"""Get dataset item for the index ``index``.

Args:
index (int): Index to get the item.

Returns:
Union[Dict[str, Tensor], Dict[str, Union[str, Tensor]]]: Dict of image tensor during training.
Otherwise, Dict containing image path, target path, image tensor, label and transformed bounding box.
"""
assert isinstance(self._samples, DataFrame)
djdameln marked this conversation as resolved.
Show resolved Hide resolved

image_path = self._samples.iloc[index].image_path
image = read_image(image_path)
label_index = self._samples.iloc[index].label_index

item = dict(image_path=image_path, label=label_index)

if self.task == "classification":
pre_processed = self.pre_process(image=image)
elif self.task == "segmentation":
mask_path = self._samples.iloc[index].mask_path

# Only Anomalous (1) images have masks in anomaly datasets
# Therefore, create empty mask for Normal (0) images.
if label_index == 0:
mask = np.zeros(shape=image.shape[:2])
else:
mask = cv2.imread(mask_path, flags=0) / 255.0

pre_processed = self.pre_process(image=image, mask=mask)

item["mask_path"] = mask_path
item["mask"] = pre_processed["mask"]
else:
raise ValueError(f"Unknown task type: {self.task}")
item["image"] = pre_processed["image"]

return item

def __add__(self, other_dataset: AnomalibDataset) -> AnomalibDataset:
"""Concatenate this dataset with another dataset."""
assert isinstance(other_dataset, self.__class__), "Cannot concatenate datasets that are not of the same type."
djdameln marked this conversation as resolved.
Show resolved Hide resolved
assert self.is_setup and other_dataset.is_setup, "Cannot concatenate uninitialized datasets. Call setup first."
djdameln marked this conversation as resolved.
Show resolved Hide resolved
dataset = copy.deepcopy(self)
dataset.samples = pd.concat([self.samples, other_dataset.samples], ignore_index=True)
return dataset

def setup(self) -> None:
"""Load data/metadata into memory."""
if not self.is_setup:
self._setup()
assert self.is_setup, "setup() should set self._samples"

@abstractmethod
def _setup(self) -> DataFrame:
"""Set up the data module.

This method should return a dataframe that contains the information needed by the dataloader to load each of
the dataset items into memory.
The dataframe must at least contain the following columns:
split: the subset to which the dataset item is assigned.
image_path: path to file system location where the image is stored.
label_index: index of the anomaly label, typically 0 for "normal" and 1 for "anomalous".
mask_path (if task == "segmentation"): path to the ground truth masks (for the anomalous images only).

Example:
|---|-------------------|-----------|-------------|------------------|-------|
| | image_path | label | label_index | mask_path | split |
|---|-------------------|-----------|-------------|------------------|-------|
| 0 | path/to/image.png | anomalous | 1 | path/to/mask.png | train |
|---|-------------------|-----------|-------------|------------------|-------|
"""
raise NotImplementedError
Loading