Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Training API (#1307)

Edgar Riba265d19f5e5f8
diff --git a/README.md b/README.md
index 29d89d9b0..51d966a7a 100644
--- a/README.md
+++ b/README.md
@@ -72,6 +72,7 @@ At a granular level, Kornia is a library that consists of the following componen
```bash
pip install kornia
+ pip install kornia[x] # to get the training API !
```
<details>
diff --git a/docs/source/get-started/installation.rst b/docs/source/get-started/installation.rst
index a3d1f2623..c4960dc97 100644
--- a/docs/source/get-started/installation.rst
+++ b/docs/source/get-started/installation.rst
@@ -12,6 +12,7 @@ To install *Kornia*, you can do it in two different ways: using the provided `Py
.. code:: bash
pip install kornia
+ pip install kornia[x] # to get the training API !
2. From source:
diff --git a/docs/source/get-started/training.rst b/docs/source/get-started/training.rst
new file mode 100644
index 000000000..f79df8de8
--- /dev/null
+++ b/docs/source/get-started/training.rst
@@ -0,0 +1,328 @@
+Training API (experimental)
+===========================
+
+Kornia provides a Training API with the specific purpose to train and fine-tune the
+supported deep learning algorithms within the library.
+
+.. important::
+ In order to use our Training API you must: ``pip install kornia[x]``
+
+Why a Training API ?
+--------------------
+
+Kornia includes deep learning models that eventually need to be updated through fine-tuning.
+Our aim is to have an API flexible enough to be used across our vision models and enable us to
+override methods or dynamically pass callbacks to ease the process of debugging and experimentations.
+
+.. admonition:: **Disclaimer**
+ :class: seealso
+
+ We do not pretend to be a general purpose training library but instead we allow Kornia users to
+ experiment with the training of our models.
+
+Design Principles
+-----------------
+
+- `kornia` golden rule is to not have heavy dependencies.
+- Our models are simple enough so that a light training API can fulfill our needs.
+- Flexible and full control to the training/validation loops and customize the pipeline.
+- Decouple the model definition from the training pipeline.
+- Use plane PyTorch abstractions and recipes to write your own routines.
+- Implement `accelerate <https://github.com/huggingface/accelerate/>`_ library to scale the problem.
+
+Trainer Usage
+-------------
+
+The entry point to start traning with Kornia is through the :py:class:`~kornia.x.Trainer` class.
+
+The main API is a self contained module that heavily relies on `accelerate <https://github.com/huggingface/accelerate/>`_
+to easily scale the training over multi-GPUs/TPU/fp16 `(see more) <https://github.com/huggingface/accelerate#supported-integrations/>`_
+by following standard PyTorch recipes. Our API expects to consume standard PyTorch components and you decide if `kornia` makes the magic
+for you.
+
+1. Define your model
+
+.. code:: python
+
+ model = nn.Sequential(
+ kornia.contrib.VisionTransformer(image_size=32, patch_size=16),
+ kornia.contrib.ClassificationHead(num_classes=10),
+ )
+
+2. Create the datasets and dataloaders for training and validation
+
+.. code:: python
+
+ # datasets
+ train_dataset = torchvision.datasets.CIFAR10(
+ root=config.data_path, train=True, download=True, transform=T.ToTensor())
+
+ valid_dataset = torchvision.datasets.CIFAR10(
+ root=config.data_path, train=False, download=True, transform=T.ToTensor())
+
+ # dataloaders
+ train_dataloader = torch.utils.data.DataLoader(
+ train_dataset, batch_size=config.batch_size, shuffle=True)
+
+ valid_daloader = torch.utils.data.DataLoader(
+ valid_dataset, batch_size=config.batch_size, shuffle=True)
+
+3. Create your loss function, optimizer and scheduler
+
+.. code:: python
+
+ # loss function
+ criterion = nn.CrossEntropyLoss()
+
+ # optimizer and scheduler
+ optimizer = torch.optim.AdamW(model.parameters(), lr=config.lr)
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
+ optimizer, config.num_epochs * len(train_dataloader)
+ )
+
+4. Create the Trainer and execute the training pipeline
+
+.. code:: python
+
+ trainer = kornia.train.Trainer(
+ model, train_dataloader, valid_daloader, criterion, optimizer, scheduler, config,
+ )
+ trainer.fit() # execute your training !
+
+
+Customize [callbacks]
+---------------------
+
+At this point you might think - *Is this API generic enough ?*
+
+ Of course not ! What is next ? Let's have fun and **customize**.
+
+The :py:class:`~kornia.x.Trainer` internals are clearly defined such in a way so that e.g you can
+subclass and just override the :py:meth:`~kornia.x.Trainer.evaluate` method and adjust
+according to your needs. We provide predefined classes for generic problems such as
+:py:class:`~kornia.x.ImageClassifierTrainer`.
+
+.. note::
+ More trainers will come as soon as we include more models.
+
+You can easily customize by creating your own class, or even through ``callbacks`` as follows:
+
+.. code:: python
+
+ @torch.no_grad()
+ def my_evaluate(self) -> dict:
+ self.model.eval()
+ for sample_id, sample in enumerate(self.valid_dataloader):
+ source, target = sample # this might change with new pytorch ataset structure
+
+ # perform the preprocess and augmentations in batch
+ img = self.preprocess(source)
+ # Forward
+ out = self.model(img)
+ # Loss computation
+ val_loss = self.criterion(out, target)
+
+ # measure accuracy and record loss
+ acc1, acc5 = accuracy(out.detach(), target, topk=(1, 5))
+
+ # create the trainer and pass the evaluate method as follows
+ trainer = K.train.Trainer(..., callbacks={"evaluate", my_evaluate})
+
+**Still not convinced ?**
+
+ You can even override the whole :py:class:`~kornia.x.ImageClassifierTrainer.fit()`
+ method and implement your custom for loops and the trainer will setup for you using the Accelerator all
+ the data to the device and the rest of the story it is just PyTorch :)
+
+.. code:: python
+
+ def my_fit(self, ): # this is a custom pytorch training loop
+ self.model.train()
+ for epoch in range(self.num_epochs):
+ for source, targets in self.train_dataloader:
+ self.optimizer.zero_grad()
+
+ output = self.model(source)
+ loss = self.criterion(output, targets)
+
+ self.backward(loss)
+ self.optimizer.step()
+
+ stats = self.evaluate() # do whatever you want with validation
+
+ # create the trainer and pass the evaluate method as follows
+ trainer = K.train.Trainer(..., callbacks={"fit", my_fit})
+
+
+Preprocess and augmentations
+----------------------------
+
+Taking a pre-trained model from an external source and assume that by fine-tuning with your
+data by just changing few things in your model is usually a bad assumption in practice.
+
+Fine-tuning a model need a lot tricks which usually means designing a good augmentation
+or preprocess strategy before you execute the training pipeline. For this reason, we enable
+through callbacks to pass pointers to the ``proprocess`` and ``augmentation`` functions to make easy
+the debugging and experimentation experience.
+
+.. code:: python
+
+ def preprocess(x):
+ return x.float() / 255.
+
+ augmentations = nn.Sequential(
+ K.augmentation.RandomHorizontalFlip(p=0.75),
+ K.augmentation.RandomVerticalFlip(p=0.75),
+ K.augmentation.RandomAffine(degrees=10.),
+ K.augmentation.PatchSequential(
+ K.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.8),
+ grid_size=(2, 2), # cifar-10 is 32x32 and vit is patch 16
+ patchwise_apply=False,
+ ),
+ )
+
+ # create the trainer and pass the augmentation or preprocess
+ trainer = K.train.ImageClassifierTrainer(...,
+ callbacks={"preprocess", preprocess, "augmentations": augmentations})
+
+Callbacks utilities
+-------------------
+
+We also provide utilities to save checkpoints of the model or early stop the training. You can use
+as follows passing as ``callbacks`` the classes :py:class:`~kornia.x.ModelCheckpoint` and
+:py:class:`~kornia.x.EarlyStopping`.
+
+.. code:: python
+
+ model_checkpoint = ModelCheckpoint(
+ filepath="./outputs", monitor="top5",
+ )
+
+ early_stop = EarlyStopping(
+ monitor="top5", filepath="early_stop_model.pt"
+ )
+
+ trainer = K.train.ImageClassifierTrainer(...,
+ callbacks={"checkpoint", model_checkpoint, "terminate": early_stop})
+
+Hyperparameter sweeps
+---------------------
+
+One can use `hydra <https://hydra.cc>`_ to implement an easy search strategy for your hyper-parameters and use as follows:
+
+.. note::
+
+ Checkout the toy example in `examples <https://github.com/kornia/kornia/tree/master/examples>`_
+
+.. code:: python
+
+ python ./train/image_classifier/main.py num_epochs=50 batch_size=32
+
+.. code:: python
+
+ python ./train/image_classifier/main.py --multirun lr=1e-3,1e-4
+
+Distributed Training
+--------------------
+
+Kornia :py:class:`~kornia.x.Trainer` heavily relies on `accelerate <https://github.com/huggingface/accelerate/>`_ to
+decouple the process of running your training scripts in a distributed environment.
+
+.. note::
+
+ We haven't tested yet all the possibilities for distributed training.
+ Expect some adventures or `join us <https://join.slack.com/t/kornia/shared_invite/zt-csobk21g-CnydWe5fmvkcktIeRFGCEQ>`_ and help to iterate :)
+
+The below recipes are taken from the `accelerate` library in `here <https://github.com/huggingface/accelerate/tree/main/examples#simple-vision-example>`_:
+
+- single CPU:
+
+ * from a server without GPU
+
+ .. code:: bash
+
+ python ./train/image_classifier/main.py
+
+ * from any server by passing `cpu=True` to the `Accelerator`.
+
+ .. code:: bash
+
+ python ./train/image_classifier/main.py --data_path path_to_data --cpu
+
+ * from any server with Accelerate launcher
+
+ .. code:: bash
+
+ accelerate launch --cpu ./train/image_classifier/main.py --data_path path_to_data
+
+- single GPU:
+
+ .. code:: bash
+
+ python ./train/image_classifier/main.py # from a server with a GPU
+
+- with fp16 (mixed-precision)
+
+ * from any server by passing `fp16=True` to the `Accelerator`.
+
+ .. code:: bash
+
+ python ./train/image_classifier/main.py --data_path path_to_data --fp16
+
+ * from any server with Accelerate launcher
+
+ .. code:: bash
+
+ accelerate launch --fp16 ./train/image_classifier/main.py --data_path path_to_data
+
+- multi GPUs (using PyTorch distributed mode)
+
+ * With Accelerate config and launcher
+
+ .. code:: bash
+
+ accelerate config # This will create a config file on your server
+ accelerate launch ./train/image_classifier/main.py --data_path path_to_data # This will run the script on your server
+
+ * With traditional PyTorch launcher
+
+ .. code:: bash
+
+ python -m torch.distributed.launch --nproc_per_node 2 --use_env ./train/image_classifier/main.py --data_path path_to_data
+
+- multi GPUs, multi node (several machines, using PyTorch distributed mode)
+
+ * With Accelerate config and launcher, on each machine:
+
+ .. code:: bash
+
+ accelerate config # This will create a config file on each server
+ accelerate launch ./train/image_classifier/main.py --data_path path_to_data # This will run the script on each server
+
+ * With PyTorch launcher only
+
+ .. code:: bash
+
+ python -m torch.distributed.launch --nproc_per_node 2 \
+ --use_env \
+ --node_rank 0 \
+ --master_addr master_node_ip_address \
+ ./train/image_classifier/main.py --data_path path_to_data # On the first server
+
+ python -m torch.distributed.launch --nproc_per_node 2 \
+ --use_env \
+ --node_rank 1 \
+ --master_addr master_node_ip_address \
+ ./train/image_classifier/main.py --data_path path_to_data # On the second server
+
+- (multi) TPUs
+
+ * With Accelerate config and launcher
+
+ .. code:: bash
+
+ accelerate config # This will create a config file on your TPU server
+ accelerate launch ./train/image_classifier/main.py --data_path path_to_data # This will run the script on each server
+
+ * In PyTorch:
+ Add an `xmp.spawn` line in your script as you usually do.
diff --git a/docs/source/index.rst b/docs/source/index.rst
index e4d07aacb..ecf6d112d 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -45,6 +45,7 @@ Join the community
get-started/installation
get-started/about
Tutorials <https://kornia-tutorials.readthedocs.io/en/latest/>
+ get-started/training
.. toctree::
:caption: KORNIA APPLICATIONS
@@ -81,6 +82,7 @@ Join the community
losses
morphology
utils
+ x
.. toctree::
:caption: SUPPORT
diff --git a/docs/source/x.rst b/docs/source/x.rst
new file mode 100644
index 000000000..bc1b4ce9c
--- /dev/null
+++ b/docs/source/x.rst
@@ -0,0 +1,21 @@
+kornia.x
+========
+
+.. currentmodule:: kornia.x
+
+Package with the utilities to train kornia models.
+
+.. autoclass:: Trainer
+
+
+Domain trainers
+---------------
+
+.. autoclass:: ImageClassifierTrainer
+
+
+Callbacks
+---------
+
+.. autoclass:: ModelCheckpoint
+.. autoclass:: EarlyStopping
diff --git a/kornia/__init__.py b/kornia/__init__.py
index b56172460..321afb749 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -10,7 +10,7 @@ try:
except ImportError:
pass
-from kornia import augmentation, color, contrib, enhance, feature, filters, geometry, jit, losses, morphology, utils
+from kornia import augmentation, color, contrib, enhance, feature, filters, geometry, jit, losses, morphology, utils, x
from kornia.color import (
bgr_to_grayscale,
bgr_to_rgb,
diff --git a/kornia/x/__init__.py b/kornia/x/__init__.py
new file mode 100644
index 000000000..a876c5b5f
--- /dev/null
+++ b/kornia/x/__init__.py
@@ -0,0 +1,4 @@
+from .callbacks import EarlyStopping, ModelCheckpoint
+from .trainer import Trainer
+from .trainer_classification import ImageClassifierTrainer
+from .utils import Configuration, TrainerState
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.py
new file mode 100644
index 000000000..e5487064e
--- /dev/null
+++ b/kornia/x/callbacks.py
@@ -0,0 +1,103 @@
+from pathlib import Path
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from .utils import TrainerState
+
+
+class EarlyStopping:
+ """Callback that evaluates whether there is improvement in the loss function.
+
+ The module track the losses and in case of finish patience sends a termination signal to the trainer.
+ In case of termination, the module will save the last model.
+
+ Args:
+ monitor: the name of the value to track.
+ min_delta: the minimum difference between losses to increase the patience counter.
+ patience: the number of times to wait until the trainer does not terminate.
+ filepath: a backup filename to save the file in case of termination.
+
+ **Usage example:**
+
+ .. code:: python
+
+ early_stop = EarlyStopping(
+ monitor="top5", filepath="early_stop_model.pt"
+ )
+
+ trainer = ImageClassifierTrainer(...,
+ callbacks={"terminate", early_stop}
+ )
+ """
+ def __init__(self, monitor: str, min_delta: float = 0., patience: int = 8) -> None:
+ self.monitor = monitor
+ self.min_delta = min_delta
+ self.patience = patience
+
+ self.counter: int = 0
+ self.best_score: Optional[float] = None
+ self.early_stop: bool = False
+
+ def __call__(self, model: nn.Module, epoch: int, valid_metric) -> TrainerState:
+ score: float = -valid_metric[self.monitor].avg
+
+ # TODO: rethink about this logic - doesn't seem to do the job.
+ if self.best_score is None:
+ self.best_score = score
+ elif score < self.best_score + self.min_delta:
+ self.counter += 1
+ if self.counter >= self.patience:
+ self.early_stop = True
+ else:
+ self.best_score = score
+ self.counter = 0
+
+ if self.early_stop:
+ # TODO: figure out later how and where to save
+ # store old metric and save new model
+ # torch.save(model, self.filepath)
+ print(f"[INFO] Early-Stopping the training process. Epoch: {epoch}.")
+ return TrainerState.TERMINATE
+
+ return TrainerState.TRAINING
+
+
+class ModelCheckpoint:
+ """Callback that save the model at the end of everyepoch.
+
+ Args:
+ filepath: the where to save the mode.
+ monitor: the name of the value to track.
+
+ **Usage example:**
+
+ .. code:: python
+
+ model_checkpoint = ModelCheckpoint(
+ filepath="./outputs", monitor="top5",
+ )
+
+ trainer = ImageClassifierTrainer(...,
+ callbacks={"checkpoint", model_checkpoint}
+ )
+ """
+ def __init__(self, filepath: str, monitor: str) -> None:
+ self.filepath = filepath
+ self.monitor = monitor
+
+ # track best model
+ self.best_metric: float = 0.
+
+ # create directory
+ Path(self.filepath).mkdir(parents=True, exist_ok=True)
+
+ def __call__(self, model: nn.Module, epoch: int, valid_metric) -> None:
+ valid_metric_value: float = valid_metric[self.monitor].avg
+ if valid_metric_value > self.best_metric:
+ self.best_metric = valid_metric_value
+ # store old metric and save new model
+ filename = Path(self.filepath) / f"model_{epoch}.pt"
+ torch.save(model, filename)
+ ...
diff --git a/kornia/x/metrics.py b/kornia/x/metrics.py
new file mode 100644
index 000000000..12802f0e5
--- /dev/null
+++ b/kornia/x/metrics.py
@@ -0,0 +1,29 @@
+# borrowed from timm: https://github.com/rwightman/pytorch-image-models/timm/utils/metrics.py
+
+
+class AverageMeter:
+ """Computes and stores the average and current value."""
+ def __init__(self):
+ self.reset()
+
+ def reset(self):
+ self.val = 0
+ self.avg = 0
+ self.sum = 0
+ self.count = 0
+
+ def update(self, val, n=1):
+ self.val = val
+ self.sum += val * n
+ self.count += n
+ self.avg = self.sum / self.count
+
+
+def accuracy(output, target, topk=(1,)):
+ """Computes the accuracy over the k top predictions for the specified values of k."""
+ maxk = min(max(topk), output.size()[1])
+ batch_size = target.size(0)
+ _, pred = output.topk(maxk, 1, True, True)
+ pred = pred.t()
+ correct = pred.eq(target.reshape(1, -1).expand_as(pred))
+ return [correct[:min(k, maxk)].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
new file mode 100644
index 000000000..fd2ae8dc2
--- /dev/null
+++ b/kornia/x/trainer.py
@@ -0,0 +1,158 @@
+import logging
+from typing import Callable, Dict
+
+import torch
+import torch.nn as nn
+from torch.utils.data import DataLoader
+
+# the accelerator library is a requirement for the Trainer
+# but it is optional for grousnd base user of kornia.
+try:
+ from accelerate import Accelerator
+except ImportError:
+ Accelerator = None
+
+from .metrics import AverageMeter
+from .utils import Configuration, TrainerState
+
+logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
+
+
+callbacks_whitelist = [
+ "preprocess", "augmentations", "evaluate", "fit", "checkpoint", "terminate"
+]
+
+
+class Trainer:
+ """Base class to train the different models in kornia.
+
+ .. warning::
+ The API is experimental and subject to be modified based on the needs of kornia models.
+
+ Args:
+ model: the nn.Module to be optimized.
+ train_dataloader: the data loader used in the training loop.
+ valid_dataloader: the data loader used in the validation loop.
+ criterion: the nn.Module with the function that computes the loss.
+ optimizer: the torch optimizer object to be used during the optimization.
+ scheduler: the torch scheduler object with defiing the scheduling strategy.
+ accelerator: the Accelerator object to distribute the training.
+ config: a TrainerConfiguration structure containing the experiment hyper parameters.
+ callbacks: a dictionary containing the pointers to the functions to overrides. The
+ main supported hooks are ``evaluate``, ``preprocess``, ``augmentations`` and ``fit``.
+
+ .. important::
+ The API heavily relies on `accelerate <https://github.com/huggingface/accelerate/>`_.
+ In order to use it, you must: ``pip install kornia[x]``
+
+ .. seealso::
+ Learn how to use the API in our documentation
+ `here <https://kornia.readthedocs.io/en/latest/get-started/training.html>`_.
+ """
+ def __init__(
+ self,
+ model: nn.Module,
+ train_dataloader: DataLoader,
+ valid_dataloader: DataLoader,
+ criterion: nn.Module,
+ optimizer: torch.optim.Optimizer,
+ scheduler: torch.optim.lr_scheduler.CosineAnnealingLR,
+ config: Configuration,
+ callbacks: Dict[str, Callable] = {},
+ ) -> None:
+ # setup the accelerator
+ if Accelerator is None:
+ raise ModuleNotFoundError(
+ "accelerate library is not installed: pip install kornia[x]")
+ self.accelerator = Accelerator()
+
+ # setup the data related objects
+ self.model = self.accelerator.prepare(model)
+ self.train_dataloader = self.accelerator.prepare(train_dataloader)
+ self.valid_dataloader = self.accelerator.prepare(valid_dataloader)
+ self.criterion = criterion.to(self.device)
+ self.optimizer = self.accelerator.prepare(optimizer)
+ self.scheduler = scheduler
+ self.config = config
+
+ # configure callbacks
+ for fn_name, fn in callbacks.items():
+ if fn_name not in callbacks_whitelist:
+ raise ValueError(f"Not supported: {fn_name}.")
+ setattr(self, fn_name, fn)
+
+ # hyper-params
+ self.num_epochs = config.num_epochs
+
+ self._logger = logging.getLogger('train')
+
+ @property
+ def device(self) -> torch.device:
+ return self.accelerator.device
+
+ def backward(self, loss: torch.Tensor) -> None:
+ self.accelerator.backward(loss)
+
+ def fit_epoch(self, epoch: int) -> None:
+ # train loop
+ self.model.train()
+ losses = AverageMeter()
+ for sample_id, sample in enumerate(self.train_dataloader):
+ source, target = sample # this might change with new pytorch dataset structure
+ self.optimizer.zero_grad()
+
+ # perform the preprocess and augmentations in batch
+ img = self.preprocess(source)
+ img = self.augmentations(img)
+ # make the actual inference
+ output = self.model(img)
+ loss = self.criterion(output, target)
+ self.backward(loss)
+ self.optimizer.step()
+
+ losses.update(loss.item(), img.shape[0])
+
+ if sample_id % 50 == 0:
+ self._logger.info(
+ f"Train: {epoch + 1}/{self.num_epochs} "
+ f"Sample: {sample_id + 1}/{len(self.train_dataloader)} "
+ f"Loss: {losses.val:.3f} {losses.avg:.3f}"
+ )
+
+ def fit(self,) -> None:
+ # execute the main loop
+ # NOTE: Do not change and keep this structure clear for readability.
+ for epoch in range(self.num_epochs):
+ # call internally the training loop
+ # NOTE: override to customize your evaluation routine
+ self.fit_epoch(epoch)
+
+ # call internally the evaluation loop
+ # NOTE: override to customize your evaluation routine
+ valid_stats = self.evaluate()
+
+ self.checkpoint(self.model, epoch, valid_stats)
+
+ state = self.terminate(self.model, epoch, valid_stats)
+ if state == TrainerState.TERMINATE:
+ break
+
+ # END OF THE EPOCH
+ self.scheduler.step()
+
+ ...
+
+ def evaluate(self):
+ ...
+
+ def preprocess(self, x):
+ return x
+
+ def augmentations(self, x):
+ return x
+
+ def checkpoint(self, *args, **kwargs):
+ ...
+
+ def terminate(self, *args, **kwargs):
+ ...
diff --git a/kornia/x/trainer_classification.py b/kornia/x/trainer_classification.py
new file mode 100644
index 000000000..53a9b7c48
--- /dev/null
+++ b/kornia/x/trainer_classification.py
@@ -0,0 +1,45 @@
+import torch
+
+from .metrics import accuracy, AverageMeter
+from .trainer import Trainer
+
+
+class ImageClassifierTrainer(Trainer):
+ """Module to be used for Image Classification purposes.
+
+ The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
+ :py:meth:`~kornia.x.Trainer.evaluate` function implementing a standard accuracy topk@[1, 5].
+
+ .. seealso::
+ Learn how to use this class in the following
+ `example <https://github.com/kornia/kornia/master/examples/train/train_classifier.py>`_.
+ """
+ @torch.no_grad()
+ def evaluate(self) -> dict:
+ self.model.eval()
+ stats = {'losses': AverageMeter(), 'top1': AverageMeter(), 'top5': AverageMeter()}
+ for sample_id, sample in enumerate(self.valid_dataloader):
+ source, target = sample # this might change with new pytorch ataset structure
+
+ # perform the preprocess and augmentations in batch
+ img = self.preprocess(source)
+ # Forward
+ out = self.model(img)
+ # Loss computation
+ val_loss = self.criterion(out, target)
+
+ # measure accuracy and record loss
+ acc1, acc5 = accuracy(out.detach(), target, topk=(1, 5))
+ stats['losses'].update(val_loss.item(), img.shape[0])
+ stats['top1'].update(acc1.item(), img.shape[0])
+ stats['top5'].update(acc5.item(), img.shape[0])
+
+ if sample_id % 10 == 0:
+ self._logger.info(
+ f"Test: {sample_id}/{len(self.valid_dataloader)} "
+ f"Loss: {stats['losses'].val:.2f} {stats['losses'].avg:.2f} "
+ f"Acc@1: {stats['top1'].val:.2f} {stats['top1'].val:.2f} "
+ f"Acc@5: {stats['top5'].val:.2f} {stats['top5'].val:.2f} "
+ )
+
+ return stats
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
new file mode 100644
index 000000000..e0a33c5af
--- /dev/null
+++ b/kornia/x/utils.py
@@ -0,0 +1,32 @@
+from dataclasses import dataclass, field
+from enum import Enum
+from pathlib import Path
+
+import yaml # type: ignore
+
+
+class TrainerState(Enum):
+ TRAINING = 0
+ TERMINATE = 1
+
+
+# NOTE: this class needs to be redefined according to the needed parameters.
+@dataclass
+class Configuration:
+ data_path: str = field(default="./", metadata={"help": "The input data directory."})
+ batch_size: int = field(default=1, metadata={"help": "The number of batches for the training dataloader."})
+ num_epochs: int = field(default=1, metadata={"help": "The number of epochs to run the training."})
+ lr: float = field(default=1e-3, metadata={"help": "The learning rate to be used for the optimize."})
+ output_path: str = field(default="./output", metadata={"help": "The output data directory."})
+
+ # TODO: possibly remove because hydra already do this
+ def __init__(self, **entries):
+ for k, v in entries.items():
+ self.__dict__[k] = Configuration(**v) if isinstance(v, dict) else v
+
+ @classmethod
+ def from_yaml(cls, config_file: str):
+ """Create an instance of the configuration from a yaml file."""
+ with open(config_file) as f:
+ data = yaml.safe_load(f)
+ return cls(**data)
diff --git a/requirements-dev.txt b/requirements-dev.txt
index da1f9a889..1f8fae060 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -11,3 +11,5 @@ yapf
isort
numpy
scipy
+# x
+accelerate==0.4.0
diff --git a/setup.py b/setup.py
index 8f2e09bcd..297187762 100644
--- a/setup.py
+++ b/setup.py
@@ -118,6 +118,10 @@ requirements = [
'packaging' # REMOVE once we deprecate pytorch > 1.7.1. See: issue #1264
]
+requirements_extras = {
+ "x": ["accelerate==0.4.0"],
+}
+
if __name__ == '__main__':
write_version_file()
@@ -139,7 +143,8 @@ if __name__ == '__main__':
packages=find_packages(exclude=('docs', 'test', 'examples')),
package_data={"kornia": ["py.typed"]},
zip_safe=True,
- install_requires=requirements,
+ install_require=requirements,
+ extras_require=requirements_extras,
keywords=['computer vision', 'deep learning', 'pytorch'],
project_urls={
"Bug Tracker": "https://github.com/kornia/kornia/issues",
diff --git a/test/test_x.py b/test/test_x.py
new file mode 100644
index 000000000..d32481857
--- /dev/null
+++ b/test/test_x.py
@@ -0,0 +1,109 @@
+from dataclasses import dataclass
+
+import pytest
+import torch
+import torch.nn as nn
+from torch.utils.data import Dataset
+
+from kornia.contrib import ClassificationHead, VisionTransformer
+from kornia.x import Configuration, EarlyStopping, ImageClassifierTrainer, ModelCheckpoint
+from kornia.x.metrics import AverageMeter
+from kornia.x.utils import TrainerState
+
+
+class DummyDataset(Dataset):
+ def __len__(self):
+ return 10
+
+ def __getitem__(self, index):
+ return torch.ones(3, 32, 32), torch.tensor(1)
+
+
+def model():
+ return nn.Sequential(
+ VisionTransformer(image_size=32),
+ ClassificationHead(num_classes=10),
+ )
+
+
+def dataset():
+ return DummyDataset()
+
+
+def dataloader(dataset):
+ return torch.utils.data.DataLoader(dataset, batch_size=1)
+
+
+def criterion():
+ return nn.CrossEntropyLoss()
+
+
+def optimizer(model):
+ return torch.optim.AdamW(model.parameters())
+
+
+def scheduler(optimizer, dataloader):
+ return torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(dataloader))
+
+
+def configuration():
+ config = Configuration()
+ config.num_epochs = 1
+ return config
+
+
+class TestImageClassifierTrainer:
+ def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):
+ trainer = ImageClassifierTrainer(
+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,
+ )
+ trainer.fit()
+
+ def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
+ with pytest.raises(ValueError):
+ ImageClassifierTrainer(
+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,
+ callbacks={'frodo': None},
+ )
+
+
+def test_callback_modelcheckpoint(tmp_path, model):
+ cb = ModelCheckpoint(tmp_path, 'test_monitor')
+ assert cb is not None
+
+ metric = {'test_monitor': AverageMeter()}
+ metric['test_monitor'].avg = 1.
+
+ cb(model, epoch=0, valid_metric=metric)
+ assert cb.best_metric == 1.0
+ assert (tmp_path / "model_0.pt").is_file()
+
+
+def test_callback_earlystopping(model):
+ cb = EarlyStopping('test_monitor', patience=2)
+ assert cb is not None
+ assert cb.counter == 0
+
+ metric = {'test_monitor': AverageMeter()}
+ metric['test_monitor'].avg = 1
+
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -1
+ assert cb.counter == 0
+
+ metric['test_monitor'].avg = 2
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TRAINING
+ assert cb.best_score == -1
+ assert cb.counter == 1
+
+ state = cb(model, epoch=0, valid_metric=metric)
+ assert state == TrainerState.TERMINATE