Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

remove grad_estimator, nerf and x modules (#3401)

Edgar Riba4d6ca7b61c6a
diff --git a/README.md b/README.md
index a13ec2c18..be7912e2a 100644
--- a/README.md
+++ b/README.md
@@ -64,7 +64,7 @@ Leverage pre-trained AI models optimized for a variety of vision tasks, all with
| **Image Registration** | - Affine and homography-based registration<br>- Image alignment using feature matching |
| **Pose Estimation** | - Essential and Fundamental matrix estimation<br>- PnP problem solvers<br>- Pose refinement |
| **Optical Flow** | - Farneback optical flow<br>- Dense optical flow<br>- Sparse optical flow |
-| **3D Vision** | - Depth estimation<br>- Point cloud operations<br>- Nerf<br> |
+| **3D Vision** | - Depth estimation<br>- Point cloud operations<br> |
| **Image Denoising** | - Gaussian noise removal<br>- Poisson noise removal |
| **Edge Detection** | - Sobel operator<br>- Canny edge detection | |
| **Transformations** | - Rotation<br>- Translation<br>- Scaling<br>- Shearing |
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 09b500b80..ed33d96a0 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -96,11 +96,9 @@ def draw_bbox_kpts(imgs, bboxes, keypoints):
def main():
# Download the tutorial examples for the main docs
- URLS_TUTORIALS_EXAMPLES = {
- "image_classifier.py": "scripts/training/image_classifier/main.py",
- "object_detection.py": "scripts/training/object_detection/main.py",
- "semantic_segmentation.py": "scripts/training/semantic_segmentation/main.py",
- }
+ # Note: Training API examples (image_classifier, object_detection, semantic_segmentation) removed
+ # as they depend on kornia.x which has been removed
+ URLS_TUTORIALS_EXAMPLES = {}
OUTPUT_PATH_SCRIPTS = Path(__file__).absolute().parent / "source/_static/scripts/"
diff --git a/docs/source/applications/image_classification.rst b/docs/source/applications/image_classification.rst
deleted file mode 100644
index be8b6c72f..000000000
--- a/docs/source/applications/image_classification.rst
+++ /dev/null
@@ -1,75 +0,0 @@
-Image Classification
-====================
-
-.. image:: https://production-media.paperswithcode.com/thumbnails/task/task-0000000951-52325f45_O0tAMly.jpg
- :align: right
- :width: 20%
-
-Image Classification is a fundamental task that attempts to comprehend an entire image as a whole.
-The goal is to classify the image by assigning it to a specific label. Typically, Image Classification refers to images
-in which only one object appears and is analyzed. In contrast, object detection involves both classification and
-localization tasks, and is used to analyze more realistic cases in which multiple objects may exist in an image.
-
-Learn more: `https://paperswithcode.com/task/image-classification <https://paperswithcode.com/task/image-classification>`_
-
-Inference
----------
-
-Kornia provides a couple of backbones based on `transformers <https://paperswithcode.com/methods/category/vision-transformer>`_
-to perform image classification. Checkout the following apis :py:class:`~kornia.contrib.VisionTransformer`,
-:py:class:`~kornia.contrib.ClassificationHead` and combine as follows to customize your own classifier:
-
-.. code:: python
-
- import torch.nn as nn
- import kornia.contrib as K
-
- classifier = nn.Sequential(
- K.VisionTransformer(image_size=224, patch_size=16),
- K.ClassificationHead(num_classes=1000)
- )
-
- img = torch.rand(1, 3, 224, 224)
- out = classifier(img) # BxN
- scores = out.argmax(-1) # B
-
-.. tip::
- Read more about our :ref:`kornia_vit`
-
-Finetuning
-----------
-
-In order to customize your model with your own data you can use our :ref:`training_api` to perform the
-`fine-tuning <https://paperswithcode.com/methods/category/fine-tuning>`_ of your model.
-
-We provide :py:class:`~kornia.x.ImageClassifierTrainer` with a default training structure to train basic
-image classification problems. However, one can leverage this is API using the models provided by Kornia or
-use existing libraries from the PyTorch ecosystem such as `torchvision <https://pytorch.org/vision/stable/models.html>`_
-or `timm <https://rwightman.github.io/pytorch-image-models/>`_.
-
-Create the dataloaders:
-
-.. literalinclude:: ../_static/scripts/image_classifier.py
- :language: python
- :lines: 20-36
-
-Define your model, losses, optimizers and schedulers:
-
-.. literalinclude:: ../_static/scripts/image_classifier.py
- :language: python
- :lines: 37-48
-
-Define your augmentations:
-
-.. literalinclude:: ../_static/scripts/image_classifier.py
- :language: python
- :lines: 50-65
-
-Finally, instantiate the :py:class:`~kornia.x.ImageClassifierTrainer` and execute your training pipeline.
-
-.. literalinclude:: ../_static/scripts/image_classifier.py
- :language: python
- :lines: 66-78
-
-.. seealso::
- Play with the full example `here <https://github.com/kornia/tutorials/tree/master/scripts/training/image_classifier>`_
diff --git a/docs/source/applications/object_detection.rst b/docs/source/applications/object_detection.rst
index ea3fa81b4..ad1ca1494 100644
--- a/docs/source/applications/object_detection.rst
+++ b/docs/source/applications/object_detection.rst
@@ -17,38 +17,7 @@ Learn more: `https://paperswithcode.com/task/object-detection <https://paperswit
Finetuning
----------
-In order to customize your model with your own data you can use our :ref:`training_api` to perform the
-`fine-tuning <https://paperswithcode.com/methods/category/fine-tuning>`_ of your model.
-
-We provide :py:class:`~kornia.x.ObjectDetectionTrainer`
-with a default training structure to train object detection problems. However, one can leverage this is
-API using the models provided by Kornia or use existing libraries from the PyTorch ecosystem such
+In order to customize your model with your own data, you can use the models provided by Kornia or use existing libraries from the PyTorch ecosystem such
as `torchvision <https://pytorch.org/vision/stable/models.html>`_.
-Create the dataloaders and transforms:
-
-.. literalinclude:: ../_static/scripts/object_detection.py
- :language: python
- :lines: 17-39
-
-Define your model, losses, optimizers and schedulers:
-
-.. literalinclude:: ../_static/scripts/object_detection.py
- :language: python
- :lines: 40-50
-
-Create your preprocessing and augmentations pipeline:
-
-.. literalinclude:: ../_static/scripts/object_detection.py
- :language: python
- :lines: 50-90
-
-Finally, instantiate the :py:class:`~kornia.x.ObjectDetectionTrainer`
-and execute your training pipeline.
-
-.. literalinclude:: ../_static/scripts/object_detection.py
- :language: python
- :lines: 90-111
-
-.. seealso::
- Play with the full example `here <https://github.com/kornia/tutorials/tree/master/scripts/training/object_detection>`_
+You can use standard PyTorch training loops with Kornia models and augmentations.
diff --git a/docs/source/applications/semantic_segmentation.rst b/docs/source/applications/semantic_segmentation.rst
deleted file mode 100644
index 014619669..000000000
--- a/docs/source/applications/semantic_segmentation.rst
+++ /dev/null
@@ -1,50 +0,0 @@
-Semantic segmentation
-=====================
-
-.. image:: https://production-media.paperswithcode.com/thumbnails/task/task-0000000885-bec5f079_K84qLCL.jpg
- :align: right
- :width: 40%
-
-Semantic segmentation, or image segmentation, is the task of clustering parts of an image together which belong to the
-same object class. It is a form of pixel-level prediction because each pixel in an image is classified according to a
-category. Some example benchmarks for this task are Cityscapes, PASCAL VOC and ADE20K. Models are usually evaluated with
-the Mean Intersection-Over-Union (Mean IoU) and Pixel Accuracy metrics.
-
-Learn more: `https://paperswithcode.com/task/semantic-segmentation <https://paperswithcode.com/task/semantic-segmentation>`_
-
-Finetuning
-----------
-
-In order to customize your model with your own data you can use our :ref:`training_api` to perform the
-`fine-tuning <https://paperswithcode.com/methods/category/fine-tuning>`_ of your model.
-
-We provide :py:class:`~kornia.x.SemanticSegmentationTrainer` with a default training structure to train semantic
-segmentation problems. However, one can leverage this is API using the models provided by Kornia or
-use existing libraries from the PyTorch ecosystem such as `torchvision <https://pytorch.org/vision/stable/models.html>`_.
-
-Create the dataloaders and transforms:
-
-.. literalinclude:: ../_static/scripts/semantic_segmentation.py
- :language: python
- :lines: 17-50
-
-Define your model, losses, optimizers and schedulers:
-
-.. literalinclude:: ../_static/scripts/semantic_segmentation.py
- :language: python
- :lines: 52-60
-
-Create your preprocessing and augmentations pipeline:
-
-.. literalinclude:: ../_static/scripts/semantic_segmentation.py
- :language: python
- :lines: 62-81
-
-Finally, instantiate the :py:class:`~kornia.x.SemanticSegmentationTrainer` and execute your training pipeline.
-
-.. literalinclude:: ../_static/scripts/semantic_segmentation.py
- :language: python
- :lines: 83-91
-
-.. seealso::
- Play with the full example `here <https://github.com/kornia/tutorials/tree/master/scripts/training/semantic_segmentation>`_
diff --git a/docs/source/get-started/installation.rst b/docs/source/get-started/installation.rst
index c4960dc97..c6f70889a 100644
--- a/docs/source/get-started/installation.rst
+++ b/docs/source/get-started/installation.rst
@@ -11,8 +11,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 !
+ pip install kornia
2. From source:
diff --git a/docs/source/get-started/training.rst b/docs/source/get-started/training.rst
deleted file mode 100644
index 47e97fdb4..000000000
--- a/docs/source/get-started/training.rst
+++ /dev/null
@@ -1,375 +0,0 @@
-.. _training_api:
-
-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.
-
-.. sidebar:: **Deep Alchemy**
-
- .. image:: https://github.com/kornia/data/raw/main/pixie_alchemist.png
- :width: 100%
- :align: center
-
- A seemingly magical process of transformation, creation, or combination of data to usable deep learning models.
-
-
-.. 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 training 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:func:`~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`, :py:class:`~kornia.x.SemanticSegmentationTrainer`.
-
-.. 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:func:`~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 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})
-
-.. note::
- The following hooks are available to override: ``preprocess``, ``augmentations``, ``evaluate``, ``fit``,
- ``on_checkpoint``, ``on_epoch_end``, ``on_before_model``
-
-
-Preprocess and augmentations
-----------------------------
-
-Taking a pre-trained model from an external source and assume that 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.ColorJiggle(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
-
- def my_evaluate(self):
- # stats = StatsTracker()
- # loss = nn.CrossEntropyLoss()
- # rest of your evaluation loop
- prediction = self.on_model(self.model, sample)
- val_loss = self.compute_loss(out, sample["mask"])
- stats.update("loss", val_loss.item(), batch_size)
- return stats.as_dict()
-
- model_checkpoint = ModelCheckpoint(
- filepath="./outputs", monitor="loss",
- )
-
- early_stop = EarlyStopping(
- monitor="loss", patience=2
- )
-
- trainer = SemanticSegmentationTrainer(...,
- callbacks={"on_epoch_end": early_stop, "on_checkpoint", model_checkpoint}
- )
-.. note::
- It'll look something like this considering code above
- | best_loss = inf
-
- | epoch 1:
- | avg_loss = 1.0
- | checkpoint = ./output/model_epoch=1_metricValue=1.0.pt
-
- | epoch 2:
- | avg_loss = 0.9
- | best_loss = 0.9
- | checkpoint = ./output/model_epoch=1_metricValue=0.9.pt
-
- | epoch 3
- | avg_loss = 1.1
- | early_stop.counter += 1
-
- | epoch 4
- | avg_loss = 1.2
- | early_stop.counter += 1
- | early_stop.patience == early_stop.counter
- | training ends here
-
-Hyperparameter sweeps
----------------------
-
-Use `hydra <https://hydra.cc>`_ to implement an easy search strategy for your hyper-parameters as follows:
-
-.. note::
-
- Checkout the toy example in `here <https://github.com/kornia/tutorials/tree/master/scripts/training/image_classifier>`__
-
-.. 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-2AQRi~X9Uu6PLMuUZdvfjA>`_ 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 b226bcf1d..e02670546 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -96,7 +96,6 @@ Join the community
get-started/about
Tutorials <https://kornia.github.io/tutorials/>
get-started/multi-framework-support
- get-started/training
OpenCV AI Kit <https://docs.luxonis.com/en/latest/pages/tutorials/creating-custom-nn-models/#kornia>
get-started/governance
@@ -120,12 +119,10 @@ Join the community
models
metrics
morphology
- nerf
onnx
tracking
testing
utils
- x
.. toctree::
:caption: KORNIA APPLICATIONS
@@ -135,13 +132,10 @@ Join the community
applications/visual_prompting
applications/face_detection
applications/image_augmentations
- applications/image_classification
applications/image_matching
applications/image_stitching
applications/image_registration
applications/image_denoising
- applications/semantic_segmentation
- applications/object_detection
.. toctree::
:caption: KORNIA MODELS
diff --git a/docs/source/nerf.rst b/docs/source/nerf.rst
deleted file mode 100644
index 3c1b311fb..000000000
--- a/docs/source/nerf.rst
+++ /dev/null
@@ -1,49 +0,0 @@
-kornia.nerf
-===========
-
-.. meta::
- :name: description
- :content: "The Kornia.nerf module provides tools for working with Neural Radiance Fields (NeRF), including models, solvers, renderers, and samplers. Key components include NerfModel, NerfSolver, and VolumeRenderer for high-quality 3D scene rendering."
-
-The functions in this sections perform Neural Radiance Fields (NeRF) related
-
-.. currentmodule:: kornia.nerf
-
-Models
-------
-
-.. autoclass:: kornia.nerf.nerf_model.NerfModel
- :members:
-.. autoclass:: kornia.nerf.nerf_model.NerfModelRenderer
- :members:
-.. autoclass:: kornia.nerf.nerf_model.MLP
- :members:
-
-Solvers
--------
-
-.. autoclass:: kornia.nerf.nerf_solver.NerfSolver
- :members:
- :exclude-members: init_training
-
-Renderers
----------
-
-.. autoclass:: kornia.nerf.volume_renderer.VolumeRenderer
- :members:
-.. autoclass:: kornia.nerf.volume_renderer.IrregularRenderer
- :members:
-.. autoclass:: kornia.nerf.volume_renderer.RegularRenderer
- :members:
-
-Samplers
---------
-
-.. autoclass:: kornia.nerf.samplers.RaySampler
- :members:
-.. autoclass:: kornia.nerf.samplers.RandomRaySampler
- :members:
-.. autoclass:: kornia.nerf.samplers.RandomGridRaySampler
- :members:
-.. autoclass:: kornia.nerf.samplers.UniformRaySampler
- :members:
diff --git a/docs/source/x.rst b/docs/source/x.rst
deleted file mode 100644
index c190e1bdb..000000000
--- a/docs/source/x.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-kornia.x
-========
-
-.. meta::
- :name: description
- :content: "The Kornia.x module provides utilities for training Kornia models, including domain-specific trainers for image classification, semantic segmentation, and object detection. It also offers training callbacks like ModelCheckpoint and EarlyStopping."
-
-.. currentmodule:: kornia.x
-
-Package with the utilities to train kornia models.
-
-.. autoclass:: Trainer
-
-
-Domain trainers
----------------
-
-.. autoclass:: ImageClassifierTrainer
-.. autoclass:: SemanticSegmentationTrainer
-.. autoclass:: ObjectDetectionTrainer
-
-
-Callbacks
----------
-
-.. autoclass:: ModelCheckpoint
-.. autoclass:: EarlyStopping
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 2db06c407..da5c6974c 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -25,7 +25,6 @@ convenience imports at the top level.
# and by changing the import order you might get into a circular dependencies issue.
from . import filters
from . import geometry
-from . import grad_estimator
# import the other modules for convenience
from . import (
@@ -44,7 +43,6 @@ from . import (
onnx,
tracking,
utils,
- x,
)
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index edcfb4f6f..3dbed537f 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -15,11 +15,10 @@
# limitations under the License.
#
-from typing import Callable, Dict, List, Optional, Tuple, Type, TypeVar
+from typing import Callable, Dict, List, Optional, Tuple, TypeVar
import torch
from torch import nn
-from torch.autograd import Function
from torch.distributions import Bernoulli, RelaxedBernoulli
from typing_extensions import Self
@@ -51,7 +50,6 @@ class OperationBase(Module):
temperature: float = 0.1,
is_batch_operation: bool = False,
magnitude_fn: Optional[Callable[[Tensor], Tensor]] = None,
- gradient_estimator: Optional[Type[Function]] = None,
symmetric_megnitude: bool = False,
) -> None:
super().__init__()
@@ -76,7 +74,6 @@ class OperationBase(Module):
self.symmetric_megnitude = symmetric_megnitude
self._magnitude_fn = self._init_magnitude_fn(magnitude_fn)
- self._gradient_estimator = gradient_estimator
def _init_magnitude_fn(self, magnitude_fn: Optional[Callable[[Tensor], Tensor]]) -> Callable[[Tensor], Tensor]:
def _identity(x: Tensor) -> Tensor:
@@ -163,16 +160,6 @@ class OperationBase(Module):
batch_prob = params["batch_prob"][(...,) + ((None,) * (len(input.shape) - 1))].to(device=input.device)
- if self._gradient_estimator is not None:
- # skip the gradient computation if gradient estimator is provided.
- with torch.no_grad():
- output = self.op(input, params=params)
- output = batch_prob * output + (1 - batch_prob) * input
- if self.magnitude is None:
- # If magnitude is None, make the grad w.r.t the input
- return self._gradient_estimator.apply(input, output)
- # If magnitude is not None, make the grad w.r.t the magnitude
- return self._gradient_estimator.apply(self.magnitude, output)
return batch_prob * self.op(input, params=params) + (1 - batch_prob) * input
@property
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index 19a2ddbad..db26a2d57 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -20,7 +20,6 @@ from typing import Optional, Tuple
import kornia.augmentation as K
from kornia.augmentation.auto.operations.base import OperationBase
from kornia.core import Tensor
-from kornia.grad_estimator import STEFunction
__all__ = [
"AutoContrast",
@@ -195,9 +194,6 @@ class Equalize(OperationBase):
Note:
Equalize cannot update probabilities yet.
- Note:
- STE gradient estimator applied for back propagation.
-
"""
def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
@@ -206,7 +202,6 @@ class Equalize(OperationBase):
initial_magnitude=None,
temperature=temperature,
symmetric_megnitude=False,
- gradient_estimator=STEFunction,
)
@@ -259,9 +254,6 @@ class Posterize(OperationBase):
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
- Note:
- STE gradient estimator applied for back propagation.
-
"""
@staticmethod
@@ -282,7 +274,6 @@ class Posterize(OperationBase):
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
magnitude_fn=Posterize._process_magnitude,
- gradient_estimator=STEFunction,
)
@@ -297,9 +288,6 @@ class Solarize(OperationBase):
symmetric_megnitude: if to randomly assign the magnitude as negative or not.magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
- Note:
- STE gradient estimator applied for back propagation.
-
"""
def __init__(
@@ -315,7 +303,6 @@ class Solarize(OperationBase):
initial_magnitude=[("thresholds", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
- gradient_estimator=STEFunction,
)
@@ -330,9 +317,6 @@ class SolarizeAdd(OperationBase):
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
- Note:
- STE gradient estimator applied for back propagation.
-
"""
def __init__(
@@ -348,7 +332,6 @@ class SolarizeAdd(OperationBase):
initial_magnitude=[("additions", initial_magnitude)],
temperature=temperature,
symmetric_megnitude=symmetric_megnitude,
- gradient_estimator=STEFunction,
)
diff --git a/kornia/grad_estimator/__init__.py b/kornia/grad_estimator/__init__.py
deleted file mode 100644
index 9ad884015..000000000
--- a/kornia/grad_estimator/__init__.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Kornia Grad Estimator β€” Gradient estimation utilities for Kornia.
-
-This subpackage provides straight-through estimators and related functions.
-"""
-
-from .ste import STEFunction, StraightThroughEstimator
diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.py
deleted file mode 100644
index 63b6eafdf..000000000
--- a/kornia/grad_estimator/ste.py
+++ /dev/null
@@ -1,139 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from typing import Any, Callable, Optional, Tuple
-
-from torch import Tensor, nn
-from torch.autograd import Function
-
-__all__ = ["STEFunction", "StraightThroughEstimator"]
-
-
-class STEFunction(Function):
- """Straight-Through Estimation (STE) function.
-
- STE bridges the gradients between the input tensor and output tensor as if the function
- was an identity function. Meanwhile, advanced gradient functions are also supported. e.g.
- the output gradients can be mapped into [-1, 1] with ``F.hardtanh`` function.
-
- Args:
- grad_fn: function to restrain the gradient received. If None, no mapping will performed.
-
- Example:
- Let the gradients of ``torch.sign`` estimated from STE.
- >>> input = torch.randn(4, requires_grad = True)
- >>> output = torch.sign(input)
- >>> loss = output.mean()
- >>> loss.backward()
- >>> input.grad
- tensor([0., 0., 0., 0.])
-
- >>> with torch.no_grad():
- ... output = torch.sign(input)
- >>> out_est = STEFunction.apply(input, output)
- >>> loss = out_est.mean()
- >>> loss.backward()
- >>> input.grad
- tensor([0.2500, 0.2500, 0.2500, 0.2500])
-
- """
-
- @staticmethod
- def forward(ctx: Any, input: Tensor, output: Tensor, grad_fn: Optional[Callable[..., Any]] = None) -> Tensor:
- ctx.in_shape = input.shape
- ctx.out_shape = output.shape
- ctx.grad_fn = grad_fn
- return output
-
- @staticmethod
- def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, Tensor, None]:
- if ctx.grad_fn is None:
- return grad_output.sum_to_size(ctx.in_shape), grad_output.sum_to_size(ctx.out_shape), None
- return (
- ctx.grad_fn(grad_output.sum_to_size(ctx.in_shape)),
- ctx.grad_fn(grad_output.sum_to_size(ctx.out_shape)),
- None,
- )
-
- # https://pytorch.org/docs/1.10.0/onnx.html#torch-autograd-functions
- # @staticmethod
- # def symbolic(g: torch._C.graph, input: torch._C.Value) -> torch._C.Value:
- # raise NotImplementedError(
- # "ONNX support is not implemented at the moment."
- # "Feel free to contribute to https://github.com/kornia/kornia.")
-
-
-class StraightThroughEstimator(nn.Module):
- """Straight-Through Estimation (STE) module.
-
- STE wraps the ``STEFunction`` to aid the back propagation of non-differentiable modules.
- It may also use to avoid gradient computation for differentiable operations. By default,
- STE bridges the gradients between the input tensor and output tensor as if the function
- was an identity function. Meanwhile, advanced gradient functions are also supported. e.g.
- the output gradients can be mapped into [-1, 1] with ``F.hardtanh`` function.
-
- Args:
- target_fn: the target function to wrap with.
- grad_fn: function to restrain the gradient received. If None, no mapping will performed.
-
- Example:
- ``RandomPosterize`` is a non-differentiable operation. Let STE estimate the gradients.
- >>> import kornia.augmentation as K
- >>> import torch.nn.functional as F
- >>> input = torch.randn(1, 1, 4, 4, requires_grad = True)
- >>> estimator = StraightThroughEstimator(K.RandomPosterize(3, p=1.), grad_fn=F.hardtanh)
- >>> out = estimator(input)
- >>> out.mean().backward()
- >>> input.grad
- tensor([[[[0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625]]]])
-
- This can be used to chain up the gradients within a ``Sequential`` block.
- >>> import kornia.augmentation as K
- >>> input = torch.randn(1, 1, 4, 4, requires_grad = True)
- >>> aug = K.ImageSequential(
- ... K.RandomAffine((77, 77)),
- ... StraightThroughEstimator(K.RandomPosterize(3, p=1.), grad_fn=None),
- ... K.RandomRotation((15, 15)),
- ... )
- >>> aug(input).mean().backward()
- >>> input.grad
- tensor([[[[0.0422, 0.0626, 0.0566, 0.0422],
- [0.0566, 0.0626, 0.0626, 0.0626],
- [0.0626, 0.0626, 0.0626, 0.0566],
- [0.0422, 0.0566, 0.0626, 0.0422]]]])
-
- """
-
- def __init__(self, target_fn: nn.Module, grad_fn: Optional[Callable[..., Any]] = None) -> None:
- super().__init__()
- self.target_fn = target_fn
- self.grad_fn = grad_fn
-
- def __repr__(self) -> str:
- return f"{self.__class__.__name__}(target_fn={self.target_fn}, grad_fn={self.grad_fn})"
-
- def forward(self, input: Tensor) -> Tensor:
- out = self.target_fn(input)
- if not isinstance(out, Tensor):
- raise NotImplementedError(
- "Only Tensor is supported at the moment. Feel free to contribute to https://github.com/kornia/kornia."
- )
- output = STEFunction.apply(input, out, self.grad_fn)
- return output
diff --git a/kornia/nerf/__init__.py b/kornia/nerf/__init__.py
deleted file mode 100644
index b38a157df..000000000
--- a/kornia/nerf/__init__.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Neural Radiance Fields (NeRF) submodule for Kornia.
-
-This package provides utilities and models for NeRF-based 3D scene representation and rendering.
-"""
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
deleted file mode 100755
index 306f4a41d..000000000
--- a/kornia/nerf/camera_utils.py
+++ /dev/null
@@ -1,171 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import math
-from typing import List, Tuple, Union
-
-import torch
-
-from kornia.core import Device, Tensor, cos, sin, stack
-from kornia.geometry.camera import PinholeCamera
-from kornia.geometry.conversions import quaternion_to_rotation_matrix
-
-
-def parse_colmap_output(
- cameras_path: str, images_path: str, device: Device, dtype: torch.dtype
-) -> Tuple[List[str], PinholeCamera]:
- r"""Parse colmap output to create an PinholeCamera for aligned scene cameras.
-
- Args:
- cameras_path: Path to camera.txt Colmap file with camera intrinsics: str
- images_path: Path to images.txt Colmap file with camera extrinsics for each image: str
- device: device for created camera object: Union[str, torch.device]
- dtype: Intrinsics and extrinsics dtype.
-
- Returns:
- image names: List[str]
- scene camera object: PinholeCamera
-
- """
- # Parse camera intrinsics
- with open(cameras_path) as f:
- lines = [line.strip() for line in f if not line.startswith("#")]
-
- class CameraParams:
- def __init__(self, line: str) -> None:
- split_line = line.split(" ")
- if len(split_line) < 7:
- raise ValueError(f"Invalid camera line: {line}")
- model = split_line[1]
- if model == "SIMPLE_PINHOLE":
- self.width = int(split_line[2])
- self.height = int(split_line[3])
- self.fx = float(split_line[4])
- self.fy = self.fx
- self.cx = float(split_line[5])
- self.cy = float(split_line[6])
- elif model == "PINHOLE":
- if len(split_line) < 8:
- raise ValueError(f"Invalid PINHOLE camera line: {line}")
- self.width = int(split_line[2])
- self.height = int(split_line[3])
- self.fx = float(split_line[4])
- self.fy = float(split_line[5])
- self.cx = float(split_line[6])
- self.cy = float(split_line[7])
- else:
- raise ValueError(f"Unsupported camera model: {model}")
-
- cameras_params: List[CameraParams] = [CameraParams(line) for line in lines]
- with open(images_path) as f:
- lines = [
- stripped
- for stripped in (line.strip() for line in f if not line.startswith("#"))
- if stripped.endswith(("jpg", "png"))
- ]
- num_images = len(lines)
- if num_images == 0:
- raise ValueError("No valid images found in images.txt")
- img_names: List[str] = []
- camera_inds: List[int] = []
- quats_list: List[List[float]] = []
- ts_list: List[List[float]] = []
- for line in lines:
- split_line = line.split(" ")
- if len(split_line) < 10:
- raise ValueError(f"Invalid image line: {line}")
- qw, qx, qy, qz = map(float, split_line[1:5])
- tx, ty, tz = map(float, split_line[5:8])
- camera_ind = int(split_line[8]) - 1
- img_name = split_line[9]
- if camera_ind >= len(cameras_params):
- raise ValueError(f"Invalid camera index {camera_ind + 1} for image {img_name}")
- img_names.append(img_name)
- camera_inds.append(camera_ind)
- quats_list.append([qw, qx, qy, qz])
- ts_list.append([tx, ty, tz])
- quats = torch.tensor(quats_list, device=device, dtype=dtype)
- ts = torch.tensor(ts_list, device=device, dtype=dtype)
- Rs = quaternion_to_rotation_matrix(quats)
- extrinsics = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).repeat(num_images, 1, 1)
- extrinsics[:, :3, :3] = Rs
- extrinsics[:, :3, 3] = ts
- fxs = torch.tensor([cameras_params[i].fx for i in camera_inds], device=device, dtype=dtype)
- fys = torch.tensor([cameras_params[i].fy for i in camera_inds], device=device, dtype=dtype)
- cxs = torch.tensor([cameras_params[i].cx for i in camera_inds], device=device, dtype=dtype)
- cys = torch.tensor([cameras_params[i].cy for i in camera_inds], device=device, dtype=dtype)
- intrinsics = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).repeat(num_images, 1, 1)
- intrinsics[:, 0, 0] = fxs
- intrinsics[:, 1, 1] = fys
- intrinsics[:, 0, 2] = cxs
- intrinsics[:, 1, 2] = cys
- heights = torch.tensor([cameras_params[i].height for i in camera_inds], device=device)
- widths = torch.tensor([cameras_params[i].width for i in camera_inds], device=device)
- cameras = PinholeCamera(
- intrinsics,
- extrinsics,
- heights,
- widths,
- )
- return img_names, cameras
-
-
-def cameras_for_ids(cameras: PinholeCamera, camera_ids: Union[List[int], Tensor]) -> PinholeCamera:
- r"""Take a PinholeCamera camera and camera indices to create a new PinholeCamera for requested cameras.
-
- Args:
- cameras: Scene camera object: PinholeCamera
- camera_ids: List of camera indices to copy: List[int]
-
- Return:
- A new PinholeCamera object with a sub-set of cameras: PinholeCamera
-
- """
- intrinsics = cameras.intrinsics[camera_ids]
- extrinsics = cameras.extrinsics[camera_ids]
- height = cameras.height[camera_ids]
- width = cameras.width[camera_ids]
- return PinholeCamera(intrinsics, extrinsics, height, width)
-
-
-def create_spiral_path(cameras: PinholeCamera, rad: float, num_views: int, num_circles: int) -> PinholeCamera:
- r"""Create a PinholeCamera object with cameras that follow a spiral path.
-
- Used for novel view synthesis for face facing models.
-
- Args:
- cameras: Scene cameras used to train the NeRF model: PinholeCamera
- rad: Spiral radius: float
- num_views: Number of created cameras: int
- num_circles: Number of spiral circles: int
-
- """
- # Average locations over all cameras
- mean_center = cameras.translation_vector.mean(0, False).squeeze(-1)
- device = cameras.intrinsics.device
- t = torch.linspace(0, 2 * math.pi * num_circles, num_views, device=device)
- cos_t = cos(t) * rad
- sin_t = -sin(t) * rad
- sin_05t = -sin(0.5 * t) * rad
- translation_vector = torch.unsqueeze(mean_center, dim=0) + stack((cos_t, sin_t, sin_05t)).permute((1, 0))
- mean_intrinsics = cameras.intrinsics.mean(0, True).repeat(num_views, 1, 1)
- mean_extrinsics = cameras.extrinsics.mean(0, True).repeat(num_views, 1, 1)
- extrinsics = mean_extrinsics
- extrinsics[:, :3, 3] = translation_vector
- height = torch.tensor([cameras.height[0]] * num_views, device=device)
- width = torch.tensor([cameras.width[0]] * num_views, device=device)
- return PinholeCamera(mean_intrinsics, extrinsics, height, width)
diff --git a/kornia/nerf/core.py b/kornia/nerf/core.py
deleted file mode 100755
index 7036eb235..000000000
--- a/kornia/nerf/core.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from typing import List, Union
-
-from kornia.core import Tensor
-
-ImagePaths = List[str]
-ImageTensors = List[Tensor]
-Images = Union[ImagePaths, ImageTensors]
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
deleted file mode 100755
index f63ea7579..000000000
--- a/kornia/nerf/data_utils.py
+++ /dev/null
@@ -1,202 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from typing import TYPE_CHECKING, List, Optional, Sequence, Tuple, Union
-
-import torch
-from torch.utils.data import BatchSampler, DataLoader, Dataset, RandomSampler, SequentialSampler
-from typing_extensions import TypeGuard
-
-from kornia.core import Device, Tensor, stack
-from kornia.geometry.camera import PinholeCamera
-from kornia.io import ImageLoadType, load_image
-from kornia.nerf.core import Images, ImageTensors
-from kornia.nerf.samplers import RandomRaySampler, RaySampler, UniformRaySampler
-
-RayGroup = Tuple[Tensor, Tensor, Optional[Tensor]]
-
-
-def _is_list_of_str(lst: Sequence[object]) -> TypeGuard[List[str]]:
- return isinstance(lst, list) and all(isinstance(x, str) for x in lst)
-
-
-def _is_list_of_tensors(lst: Sequence[object]) -> TypeGuard[List[Tensor]]:
- return isinstance(lst, list) and all(isinstance(x, Tensor) for x in lst)
-
-
-class RayDataset(Dataset[RayGroup]):
- r"""Class to represent a dataset of rays.
-
- Args:
- cameras: scene cameras: PinholeCamera
- min_depth: sampled rays minimal depth from cameras: float
- max_depth: sampled rays maximal depth from cameras: float
- ndc: convert ray parameters to normalized device coordinates: bool
- device: device for ray tensors: Union[str, torch.device]
- dtype: type of ray tensors: torch.dtype
-
- """
-
- def __init__(
- self, cameras: PinholeCamera, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype
- ) -> None:
- super().__init__()
- self._ray_sampler: Optional[RaySampler] = None
- self._imgs: Optional[List[Tensor]] = None
- self._cameras = cameras
- self._min_depth = min_depth
- self._max_depth = max_depth
- self._ndc = ndc
- self._device = device
- self._dtype = dtype
-
- def init_ray_dataset(self, num_img_rays: Optional[Tensor] = None) -> None:
- r"""Initialize a ray dataset.
-
- Args:
- num_img_rays: If not None, number of rays to randomly cast from each camera: math: `(B)`.
-
- """
- if num_img_rays is None:
- self._init_uniform_ray_dataset()
- else:
- self._init_random_ray_dataset(num_img_rays)
-
- def init_images_for_training(self, imgs: Images) -> None:
- r"""Initialize images for training.
-
- Images can be either a list of tensors, or a list of paths to image disk locations.
-
- Args:
- imgs: List of image tensors or image paths: Images
-
- """
- self._check_image_type_consistency(imgs)
-
- if _is_list_of_str(imgs): # Load images from disk
- images = self._load_images(imgs)
- elif _is_list_of_tensors(imgs):
- images = imgs # Take images provided on input
- else:
- raise TypeError(f"Expected a list of image tensors or image paths. Gotcha {type(imgs)}.")
-
- self._check_dimensions(images)
-
- # Move images to defined device
- self._imgs = [img.to(self._device) for img in images]
-
- def _init_random_ray_dataset(self, num_img_rays: Tensor) -> None:
- r"""Initialize a random ray sampler and calculates dataset ray parameters.
-
- Args:
- num_img_rays: If not None, number of rays to randomly cast from each camers: math: `(B)`.
-
- """
- self._ray_sampler = RandomRaySampler(
- self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
- )
- self._ray_sampler.calc_ray_params(self._cameras, num_img_rays)
-
- def _init_uniform_ray_dataset(self) -> None:
- r"""Initialize a uniform ray sampler and calculates dataset ray parameters."""
- self._ray_sampler = UniformRaySampler(
- self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
- )
- self._ray_sampler.calc_ray_params(self._cameras)
-
- def _check_image_type_consistency(self, imgs: Images) -> None:
- if not all(isinstance(img, str) for img in imgs) and not all(isinstance(img, Tensor) for img in imgs):
- raise ValueError("The list of input images can only be all paths or tensors")
-
- def _check_dimensions(self, imgs: ImageTensors) -> None:
- if len(imgs) != self._cameras.batch_size:
- raise ValueError(
- f"Number of images {len(imgs)} does not match number of cameras {self._cameras.batch_size}"
- )
- if not all(img.shape[0] == 3 for img in imgs):
- raise ValueError("Not all input images have 3 channels")
- for i, (img, height, width) in enumerate(zip(imgs, self._cameras.height, self._cameras.width)):
- if img.shape[1:] != (height, width):
- raise ValueError(
- f"Image index {i} dimensions {(img.shape[1], img.shape[2])} are inconsistent with equivalent "
- f"camera dimensions {(height.item(), width.item())}"
- )
-
- @staticmethod
- def _load_images(img_paths: List[str]) -> List[Tensor]:
- imgs: List[Tensor] = []
- for img_path in img_paths:
- imgs.append(load_image(img_path, ImageLoadType.UNCHANGED))
- return imgs
-
- def __len__(self) -> int:
- if isinstance(self._ray_sampler, RaySampler):
- return len(self._ray_sampler)
- return 0
-
- def __getitem__(self, idxs: Union[int, List[int]]) -> RayGroup:
- r"""Get a dataset item.
-
- Args:
- idxs: An index or group of indices of ray parameter object: Union[int, List[int]]
-
- Return:
- A ray parameter object that includes ray origins, directions, and rgb values at the ray 2d pixel
- coordinates: RayGroup
-
- """
- if not isinstance(self._ray_sampler, RaySampler):
- raise TypeError("Ray sampler is not initiate yet, please run self.init_ray_dataset() before use it.")
-
- origins = self._ray_sampler.origins[idxs]
- directions = self._ray_sampler.directions[idxs]
- if self._imgs is None:
- return origins, directions, None
-
- camerd_ids = self._ray_sampler.camera_ids[idxs]
- points_2d = self._ray_sampler.points_2d[idxs]
- rgbs = None
- imgs_for_ids = [self._imgs[i] for i in camerd_ids]
- rgbs = stack([img[:, point2d[1].item(), point2d[0].item()] for img, point2d in zip(imgs_for_ids, points_2d)])
- rgbs = rgbs.to(dtype=self._dtype) / 255.0
- return origins, directions, rgbs
-
-
-def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> DataLoader[RayGroup]:
- r"""Initialize a dataloader to manage a ray dataset.
-
- Args:
- dataset: A ray dataset: RayDataset
- batch_size: Number of rays to sample in a batch: int
- shuffle: Whether to shuffle rays or sample then sequentially: bool
-
- """
-
- def collate_rays(items: List[RayGroup]) -> RayGroup:
- return items[0]
-
- if TYPE_CHECKING:
- # TODO: remove the type ignore when kornia relies on kornia 1.10
- return DataLoader(dataset)
- else:
- return DataLoader(
- dataset,
- sampler=BatchSampler(
- RandomSampler(dataset) if shuffle else SequentialSampler(dataset), batch_size, drop_last=False
- ),
- collate_fn=collate_rays,
- )
diff --git a/kornia/nerf/nerf_model.py b/kornia/nerf/nerf_model.py
deleted file mode 100755
index 011cd84c4..000000000
--- a/kornia/nerf/nerf_model.py
+++ /dev/null
@@ -1,247 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-import torch
-from torch import nn
-from torch.nn import functional as F
-
-from kornia.core import Module, Tensor
-from kornia.geometry.camera import PinholeCamera
-from kornia.geometry.ray import Ray
-from kornia.nerf.positional_encoder import PositionalEncoder
-from kornia.nerf.samplers import sample_lengths, sample_ray_points
-from kornia.nerf.volume_renderer import IrregularRenderer, RegularRenderer
-from kornia.utils._compat import torch_inference_mode
-from kornia.utils.grid import create_meshgrid
-
-
-class MLP(Module):
- r"""Class to represent a multi-layer perceptron.
-
- The MLP represents a deep NN of fully connected layers.
- The network is build of user defined sub-units, each with a user defined number of layers.
-
- Skip connections span between the sub-units.
- The model follows: Ben Mildenhall et el. (2020) at https://arxiv.org/abs/2003.08934.
- """
-
- def __init__(self, num_dims: int, num_units: int = 2, num_unit_layers: int = 4, num_hidden: int = 128) -> None:
- """Construct MLP.
-
- Args:
- num_dims: Number of input dimensions (channels).
- num_units: Number of sub-units.
- num_unit_layers: Number of fully connected layers in each sub-unit.
- num_hidden: Layer hidden dimensions.
-
- """
- super().__init__()
- self._num_unit_layers = num_unit_layers
- layers = []
- for i in range(num_units):
- num_unit_inp_dims = num_dims if i == 0 else num_hidden + num_dims
- for j in range(num_unit_layers):
- num_layer_inp_dims = num_unit_inp_dims if j == 0 else num_hidden
- layer = nn.Linear(num_layer_inp_dims, num_hidden)
- layers.append(nn.Sequential(layer, nn.ReLU()))
- self._mlp = nn.ModuleList(layers)
-
- def forward(self, x: Tensor) -> Tensor:
- out = x
- x_skip = x
- for i, layer in enumerate(self._mlp):
- if i > 0 and i % self._num_unit_layers == 0:
- out = torch.cat((out, x_skip), dim=-1)
- out = layer(out)
- return out
-
-
-class NerfModel(Module):
- r"""Class to represent NeRF model.
-
- Args:
- num_ray_points: Number of points to sample along rays.
- irregular_ray_sampling: Whether to sample ray points irregularly.
- num_pos_freqs: Number of frequencies for positional encoding.
- num_dir_freqs: Number of frequencies for directional encoding.
- num_units: Number of sub-units.
- num_unit_layers: Number of fully connected layers in each sub-unit.
- num_hidden: Layer hidden dimensions.
- log_space_encoding: Whether to apply log spacing for encoding.
-
- """
-
- def __init__(
- self,
- num_ray_points: int,
- irregular_ray_sampling: bool = True,
- num_pos_freqs: int = 10,
- num_dir_freqs: int = 4,
- num_units: int = 2,
- num_unit_layers: int = 4,
- num_hidden: int = 128, # FIXME: add as call argument
- log_space_encoding: bool = True,
- ) -> None:
- super().__init__()
- self._num_ray_points = num_ray_points
- self._irregular_ray_sampling = irregular_ray_sampling
- self._renderer = IrregularRenderer() if self._irregular_ray_sampling else RegularRenderer()
-
- self._pos_encoder = PositionalEncoder(3, num_pos_freqs, log_space=log_space_encoding)
- self._dir_encoder = PositionalEncoder(3, num_dir_freqs, log_space=log_space_encoding)
- self._mlp = MLP(self._pos_encoder.num_encoded_dims, num_units, num_unit_layers, num_hidden)
- self._fc1 = nn.Linear(num_hidden, num_hidden)
- self._fc2 = nn.Sequential(
- nn.Linear(num_hidden + self._dir_encoder.num_encoded_dims, num_hidden // 2), nn.ReLU()
- )
-
- self._sigma = nn.Linear(num_hidden, 1, bias=True)
- torch.nn.init.xavier_uniform_(self._sigma.weight.data)
- self._sigma.bias.data = torch.tensor([0.1]).float()
-
- self._rgb = nn.Sequential(nn.Linear(num_hidden // 2, 3), nn.Sigmoid())
- self._rgb[0].bias.data = torch.tensor([0.02, 0.02, 0.02]).float()
-
- def forward(self, origins: Tensor, directions: Tensor) -> Tensor:
- """Forward method.
-
- Args:
- origins: Ray origins with shape :math:`(B, 3)`.
- directions: Ray directions with shape :math:`(B, 3)`.
-
- Returns:
- Rendered image pixels :math:`(B, 3)`.
-
- """
- # Sample xyz for ray parameters
- batch_size = origins.shape[0]
- lengths = sample_lengths(
- batch_size,
- self._num_ray_points,
- device=origins.device,
- dtype=origins.dtype,
- irregular=self._irregular_ray_sampling,
- ) # FIXME: handle the case of hierarchical sampling
- points_3d = sample_ray_points(origins, directions, lengths)
-
- # Encode positions & directions
- points_3d_encoded = self._pos_encoder(points_3d)
- directions_encoded = self._dir_encoder(F.normalize(directions, dim=-1))
-
- # Map positional encodings to latent features (MLP with skip connections)
- y = self._mlp(points_3d_encoded)
- y = self._fc1(y)
-
- # Calculate ray point density values
- densities_ray_points = self._sigma(y)
- densities_ray_points = densities_ray_points + torch.randn_like(densities_ray_points) * 0.1
- densities_ray_points = torch.relu(densities_ray_points) # FIXME: Revise this
-
- # Calculate ray point rgb values
- y = torch.cat((y, directions_encoded[..., None, :].expand(-1, self._num_ray_points, -1)), dim=-1)
- y = self._fc2(y)
- rgbs_ray_points = self._rgb(y)
-
- # Rendering rgbs and densities along rays
- rgbs = self._renderer(rgbs_ray_points, densities_ray_points, points_3d)
-
- # Return pixel point rendered rgb
- return rgbs
-
-
-class NerfModelRenderer:
- """Renders a novel synthesis view of a trained NeRF model for given camera."""
-
- def __init__(
- self, nerf_model: NerfModel, image_size: tuple[int, int], device: torch.device | None, dtype: torch.dtype | None
- ) -> None:
- """Construct NerfModelRenderer.
-
- Args:
- nerf_model: NeRF model.
- image_size: image size.
- device: device to run the model on.
- dtype: dtype to run the model on.
-
- """
- self._nerf_model = nerf_model
- self._image_size = image_size
- self._device = device
- self._dtype = dtype
-
- self._pixels_grid, self._ones = self._create_pixels_grid() # 1xHxWx2 and (H*W)x1
-
- def _create_pixels_grid(self) -> tuple[Tensor, Tensor]:
- """Create the pixels grid to unproject to plane z=1.
-
- Args:
- image_size: image size: tuple[int, int]
-
- Returns:
- - Pixels grid: Tensor (1, H, W, 2)
- - Ones: Tensor (H*W, 1)
-
- """
- height, width = self._image_size
- pixels_grid: Tensor = create_meshgrid(
- height, width, normalized_coordinates=False, device=self._device, dtype=self._dtype
- ) # 1xHxWx2
- pixels_grid = pixels_grid.reshape(-1, 2) # (H*W)x2
-
- ones = torch.ones(pixels_grid.shape[0], 1, device=pixels_grid.device, dtype=pixels_grid.dtype) # (H*W)x1
-
- return pixels_grid, ones
-
- def render_view(self, camera: PinholeCamera) -> Tensor:
- """Render a novel synthesis view of a trained NeRF model for given camera.
-
- Args:
- camera: camera for image rendering: PinholeCamera.
-
- Returns:
- Rendered image with shape :math:`(H, W, 3)`.
-
- """
- # create ray for this camera
- rays: Ray = self._create_rays(camera)
-
- # render the image
- with torch_inference_mode():
- rgb_model = self._nerf_model(rays.origin, rays.direction)
-
- rgb_image = rgb_model.view(self._image_size[0], self._image_size[1], 3)
-
- return rgb_image
-
- def _create_rays(self, camera: PinholeCamera) -> Ray:
- """Create rays for a given camera.
-
- Args:
- camera: camera for image rendering: PinholeCamera.
-
- """
- height, width = self._image_size
-
- # convert to rays
- origin = camera.extrinsics[..., :3, -1] # 1x3
- origin = origin.repeat(height * width, 1) # (H*W)x3
-
- destination = camera.unproject(self._pixels_grid, self._ones) # (H*W)x3
-
- return Ray.through(origin, destination)
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
deleted file mode 100755
index 0f1aee618..000000000
--- a/kornia/nerf/nerf_solver.py
+++ /dev/null
@@ -1,257 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-import logging
-from datetime import datetime
-from typing import cast
-
-import torch
-import torch.nn.functional as F
-from torch import optim
-
-from kornia.core import Module, Tensor, tensor
-from kornia.core.check import KORNIA_CHECK
-from kornia.geometry.camera import PinholeCamera
-from kornia.metrics import psnr
-from kornia.nerf.core import Images
-from kornia.nerf.data_utils import RayDataset, instantiate_ray_dataloader
-from kornia.nerf.nerf_model import NerfModel
-from kornia.utils import deprecated
-
-logger = logging.getLogger(__name__)
-
-
-class NerfSolver:
- r"""NeRF solver class.
-
- Args:
- device: device for class tensors: Union[str, Device]
- dtype: type for all floating point calculations: torch.dtype
-
- """
-
- def __init__(self, device: torch.device, dtype: torch.dtype) -> None:
- # TODO: add support for the new CameraModel class
- # cameras used for training
- self._cameras: PinholeCamera | None = None
-
- # rays depth range
- self._min_depth: float = 0.0
- self._max_depth: float = 0.0
-
- # whether to convert ray parameters to normalized device coordinates
- self._ndc: bool = True
-
- # images used for training
- self._imgs: Images | None = None
-
- # number of rays to randomly cast from each camera
- self._num_img_rays: Tensor | int | None = None
-
- # number of rays to sample in a batch
- self._batch_size: int = 0
-
- # number of points to sample along rays
- self._num_ray_points: int = 0
-
- # the model and optimizer
- self._nerf_model: Module | None = None
- self._nerf_optimizer: optim.Optimizer | None = None
-
- self._device = device
- self._dtype = dtype
-
- def setup_solver(
- self,
- cameras: PinholeCamera,
- min_depth: float,
- max_depth: float,
- ndc: bool,
- imgs: Images,
- num_img_rays: Tensor | int,
- batch_size: int,
- num_ray_points: int,
- irregular_ray_sampling: bool = True,
- log_space_encoding: bool = True,
- lr: float = 1.0e-3,
- ) -> None:
- """Initialize training settings and model.
-
- Args:
- cameras: Scene cameras in the order of input images.
- min_depth: sampled rays minimal depth from cameras.
- max_depth: sampled rays maximal depth from cameras.
- ndc: convert ray parameters to normalized device coordinates.
- imgs: Scene 2D images (one for each camera).
- num_img_rays: Number of rays to randomly cast from each camera: math: `(B)`.
- batch_size: Number of rays to sample in a batch.
- num_ray_points: Number of points to sample along rays.
- irregular_ray_sampling: Whether to sample ray points irregularly.
- log_space_encoding: Whether frequency sampling should be log spaced.
- lr: Learning rate.
-
- """
- self._cameras = cameras
- self._min_depth = min_depth
- self._max_depth = max_depth
- self._ndc = ndc
-
- self._imgs = imgs
-
- KORNIA_CHECK(
- isinstance(batch_size, int) and batch_size > 0,
- "batch_size must be a positive integer",
- )
-
- KORNIA_CHECK(
- isinstance(num_ray_points, int) and num_ray_points > 0,
- "num_ray_points must be a positive integer",
- )
-
- KORNIA_CHECK(num_img_rays is not None, "num_img_rays must be specified")
-
- if isinstance(num_img_rays, int):
- self._num_img_rays = tensor([num_img_rays] * cameras.batch_size)
- elif torch.is_tensor(num_img_rays):
- self._num_img_rays = num_img_rays
- else:
- raise TypeError("num_img_rays can be either an int or a Tensor")
-
- self._batch_size = batch_size
-
- self._nerf_model = NerfModel(
- num_ray_points, irregular_ray_sampling=irregular_ray_sampling, log_space_encoding=log_space_encoding
- )
- self._nerf_model.to(device=self._device, dtype=self._dtype)
-
- self._nerf_optimizer = optim.Adam(self._nerf_model.parameters(), lr=lr)
-
- @deprecated(replace_with="setup_solver", version="0.7.0")
- def init_training(
- self,
- cameras: PinholeCamera,
- min_depth: float,
- max_depth: float,
- ndc: bool,
- imgs: Images,
- num_img_rays: Tensor | int,
- batch_size: int,
- num_ray_points: int,
- irregular_ray_sampling: bool = True,
- log_space_encoding: bool = True,
- lr: float = 1.0e-3,
- ) -> None:
- self.setup_solver(
- cameras,
- min_depth,
- max_depth,
- ndc,
- imgs,
- num_img_rays,
- batch_size,
- num_ray_points,
- irregular_ray_sampling,
- log_space_encoding,
- lr,
- )
-
- @property
- def nerf_model(self) -> Module | None:
- """Returns the NeRF model."""
- return self._nerf_model
-
- def _train_one_epoch(self) -> float:
- r"""Trains the NeRF model one epoch.
-
- 1) A dataset of rays is initialized, and sent over to a data loader.
- 2) The data loader sample a batch of rays randomly, and runs them through the NeRF model,
- to predict ray associated rgb model values.
- 3) The model rgb is compared with the image pixel rgb, and the loss between the two is back
- propagated to update the model weights.
-
- Implemented steps:
- - Create an object of class RayDataset
- - Initialize ray dataset with group of images on disk, and number of rays to randomly sample
- - Initialize a data loader with batch size info
- - Iterate over data loader
- -- Reset optimizer
- -- Run ray batch through Nerf model
- -- Find loss
- -- Back propagate loss
- -- Optimizer step
-
- Returns:
- Average psnr over all epoch rays.
-
- """
- KORNIA_CHECK(self._nerf_model is not None, "The model should be a NeRF model.")
- KORNIA_CHECK(self._nerf_optimizer is not None, "The optimizer should be an Adam optimizer.")
- KORNIA_CHECK(self._cameras is not None, "The camera should be a PinholeCamera.")
- KORNIA_CHECK(self._imgs is not None, "The images should be a list of tensors.")
- KORNIA_CHECK(self._num_img_rays is not None, "The number of images of Ray should be a tensor.")
-
- # TODO: refactor and so that the constructor receives the correct types
- cameras: PinholeCamera = cast(PinholeCamera, self._cameras)
- num_img_rays: Tensor = cast(Tensor, self._num_img_rays)
- images = cast(Images, self._imgs)
- nerf_model: NerfModel = cast(NerfModel, self._nerf_model)
- nerf_optimizer: optim.Optimizer = cast(optim.Optimizer, self._nerf_optimizer)
-
- # create the dataset and data loader
- ray_dataset = RayDataset(
- cameras, self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
- )
- ray_dataset.init_ray_dataset(num_img_rays)
- ray_dataset.init_images_for_training(images) # FIXME: Do we need to load the same images on each Epoch?
-
- # data loader
- ray_data_loader = instantiate_ray_dataloader(ray_dataset, self._batch_size, shuffle=True)
-
- total_psnr: Tensor = torch.tensor(0.0, device=self._device, dtype=self._dtype)
-
- i_batch: float = 0
-
- for origins, directions, rgbs in ray_data_loader:
- rgbs_model = nerf_model(origins, directions)
- loss = F.mse_loss(rgbs_model, rgbs)
-
- total_psnr += psnr(rgbs_model, rgbs, 1.0)
-
- nerf_optimizer.zero_grad()
- loss.backward()
- nerf_optimizer.step()
-
- i_batch += 1
-
- return float(total_psnr / (i_batch + 1))
-
- def run(self, num_epochs: int = 1) -> None:
- r"""Run training epochs.
-
- Args:
- num_epochs: number of epochs to run. Default: 1.
-
- """
- for i_epoch in range(num_epochs):
- # train one epoch
- epoch_psnr: float = self._train_one_epoch()
-
- if i_epoch % 10 == 0:
- current_time = datetime.now().strftime("%H:%M:%S") # noqa: DTZ005
- logger.info("Epoch: %d: epoch_psnr = %f; time: %s", i_epoch, epoch_psnr, current_time)
diff --git a/kornia/nerf/positional_encoder.py b/kornia/nerf/positional_encoder.py
deleted file mode 100755
index 2e38e0ff0..000000000
--- a/kornia/nerf/positional_encoder.py
+++ /dev/null
@@ -1,86 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from functools import partial
-
-import torch
-from torch import nn
-
-from kornia.core import Tensor
-
-
-def _torch_sin(x: Tensor, freq: Tensor) -> Tensor:
- return (x * freq).sin() # FIXME: PI?
-
-
-def _torch_cos(x: Tensor, freq: Tensor) -> Tensor:
- return (x * freq).cos()
-
-
-class PositionalEncoder(nn.Module):
- """Sine-cosine positional encoder for input points."""
-
- def __init__(self, num_dims: int, num_freqs: int, log_space: bool = False) -> None:
- """Initialize positional encoder.
-
- Args:
- num_dims: Number of input dimensions (channels): int
- num_freqs: Number of frequency bands for encoding span: int
- log_space: Whether frequency sampling should be log spaced: bool
-
- """
- super().__init__()
- self._num_dims = num_dims
- self._embed_fns = [lambda x: x]
-
- # Define frequencies in either linear or log scale
- freq_bands: Tensor
- if log_space:
- freq_bands = 2.0 ** torch.linspace(0.0, num_freqs - 1, num_freqs)
- else:
- freq_bands = torch.linspace(2.0**0.0, 2.0 ** (num_freqs - 1), num_freqs)
-
- # Alternate sin and cos
- for freq in freq_bands:
- self._embed_fns.append(partial(_torch_sin, freq=freq))
- self._embed_fns.append(partial(_torch_cos, freq=freq))
-
- self._num_encoded_dims = self._num_dims * len(self._embed_fns)
-
- @property
- def num_encoded_dims(self) -> int:
- """Number of encoded dimensions."""
- return self._num_encoded_dims
-
- def forward(self, x: Tensor) -> Tensor:
- """Apply positional encoding to input.
-
- Args:
- x: Positionsl (or directional) tensor to encode: Tensor
-
- Returns:
- Tensor with encoded position/direction: Tensor
-
- """
- if x.ndim < 1:
- raise ValueError("Input tensor represents a scalar")
- if x.shape[-1] != self._num_dims:
- raise ValueError(
- f"Input tensor number of dimensions {x.shape[-1]} does not match instantiated dimensionality "
- f"{self._num_dims}"
- )
- return torch.cat([fn(x) for fn in self._embed_fns], dim=-1)
diff --git a/kornia/nerf/samplers.py b/kornia/nerf/samplers.py
deleted file mode 100755
index 091f9d6c5..000000000
--- a/kornia/nerf/samplers.py
+++ /dev/null
@@ -1,466 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import math
-from typing import Dict, List, Tuple
-
-import torch
-
-from kornia.core import Device, Tensor, tensor
-from kornia.geometry.camera import PinholeCamera
-from kornia.nerf.camera_utils import cameras_for_ids
-from kornia.utils._compat import torch_meshgrid
-from kornia.utils.helpers import _torch_inverse_cast
-
-
-class RaySampler:
- r"""Class to manage spatial ray sampling.
-
- Args:
- min_depth: sampled rays minimal depth from cameras: float
- max_depth: sampled rays maximal depth from cameras: float
- ndc: convert ray parameters to normalized device coordinates: bool
- device: device for ray tensors: Union[str, torch.device]
-
- """
-
- _origins: Tensor # Ray origins in world coordinates (*, 3)
- _directions: Tensor # Ray directions in world coordinates (*, 3)
- _directions_cam: Tensor # Ray directions in camera coordinates (*, 3)
- _origins_cam: Tensor # Ray origins in camera coordinates (*, 3)
- _camera_ids: Tensor # Ray camera ID
- _points_2d: Tensor # Ray intersection with image plane in camera coordinates
-
- def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
- self._min_depth = min_depth
- self._max_depth = max_depth
- self._ndc = ndc
- self._device = device
- self._dtype = dtype
-
- @property
- def origins(self) -> Tensor:
- return self._origins
-
- @property
- def directions(self) -> Tensor:
- return self._directions
-
- @property
- def camera_ids(self) -> Tensor:
- return self._camera_ids
-
- @property
- def points_2d(self) -> Tensor:
- return self._points_2d
-
- def __len__(self) -> int:
- if self.origins is None:
- return 0
- return self.origins.shape[0]
-
- def _calc_ray_directions_cam(self, cameras: PinholeCamera, points_2d: Tensor) -> Tensor:
- # FIXME: This function should call perspective.unproject_points or, implement in PinholeCamera unproject to
- # camera coordinates that will call perspective.unproject_points
- fx = cameras.fx
- fy = cameras.fy
- cx = cameras.cx
- cy = cameras.cy
- directions_x = (points_2d[..., 0] - cx[..., None]) / fx[..., None]
- directions_y = (points_2d[..., 1] - cy[..., None]) / fy[..., None]
- directions_z = torch.ones_like(directions_x)
- directions_cam = torch.stack([directions_x, directions_y, directions_z], dim=-1)
- return directions_cam.reshape(-1, 3)
-
- class Points2D:
- r"""A class to hold ray 2d pixel coordinates and a camera id for each.
-
- Args:
- points_2d: tensor with ray pixel coordinates (the coordinates in the image plane that correspond to the
- ray):math:`(B, 2)`
- camera_ids: list of camera ids for each pixel coordinates: List[int]
-
- """
-
- def __init__(self, points_2d: Tensor, camera_ids: List[int]) -> None:
- self._points_2d = points_2d # (*, N, 2)
- self._camera_ids = camera_ids
-
- @property
- def points_2d(self) -> Tensor:
- return self._points_2d
-
- @property
- def camera_ids(self) -> List[int]:
- return self._camera_ids
-
- def _calc_ray_params(self, cameras: PinholeCamera, points_2d_camera: Dict[int, Points2D]) -> None:
- r"""Calculate ray parameters: origins, directions.
-
- Also stored are camera ids for each ray, and its pixel coordinates.
-
- Args:
- cameras: scene cameras: PinholeCamera
- points_2d_camera: a dictionary that groups Point2D objects by total number of casted rays
-
- """
- # Unproject 2d points in image plane to 3d world for two depths
- origins = []
- directions = []
- directions_cam = []
- origins_cam = []
- camera_ids = []
- points_2d = []
- for obj in points_2d_camera.values():
- # FIXME: Below both world and camera ray directions are calculated. It could be that world ray directions
- # will not be necessary and can be removed here
- num_cams_group, num_points_per_cam_group = obj._points_2d.shape[:2]
- depths = (
- torch.ones(num_cams_group, 2 * num_points_per_cam_group, 3, device=self._device, dtype=self._dtype)
- * self._min_depth
- )
- depths[:, num_points_per_cam_group:] = self._max_depth
- cams = cameras_for_ids(cameras, obj.camera_ids)
- points_3d = cams.unproject(obj._points_2d.repeat(1, 2, 1), depths)
- origins.append(points_3d[..., :num_points_per_cam_group, :].reshape(-1, 3))
- directions.append(
- (points_3d[..., num_points_per_cam_group:, :] - points_3d[..., :num_points_per_cam_group, :]).reshape(
- -1, 3
- )
- )
- directions_cam.append(self._calc_ray_directions_cam(cams, obj._points_2d))
- origins_cam.append(directions_cam[-1] * self._min_depth)
- camera_ids.append(
- tensor(obj.camera_ids).repeat(num_points_per_cam_group, 1).permute(1, 0).reshape(1, -1).squeeze(0)
- )
- points_2d.append(obj._points_2d.reshape(-1, 2).int())
- self._origins = torch.cat(origins)
- self._directions = torch.cat(directions)
- self._directions_cam = torch.cat(directions_cam)
- self._origins_cam = torch.cat(origins_cam)
- self._camera_ids = torch.cat(camera_ids)
- if self._ndc: # Transform ray parameters to NDC, if defined
- self._origins, self._directions = self.transform_ray_params_world_to_ndc(cameras)
- self._points_2d = torch.cat(points_2d)
-
- def transform_ray_params_world_to_ndc(self, cameras: PinholeCamera) -> Tuple[Tensor, Tensor]:
- r"""Transform ray parameters to normalized coordinate device (camera) system (NDC).
-
- Args:
- cameras: scene cameras: PinholeCamera
-
- """
- cams = cameras_for_ids(cameras, self._camera_ids)
- fx = cams.fx
- fy = cams.fy
- widths = cams.width
- heights = cams.height
- fx_widths = 2.0 * fx / (widths - 1.0)
- fy_heights = 2.0 * fy / (heights - 1.0)
-
- # oxoz = self._origins_cam[..., 0] / self._origins_cam[..., 2]
- # oyoz = self._origins_cam[..., 1] / self._origins_cam[..., 2]
-
- oxoz = self._origins[..., 0] / self._origins[..., 2]
- oyoz = self._origins[..., 1] / self._origins[..., 2]
-
- origins_ndc_x = fx_widths * oxoz
- origins_ndc_y = fy_heights * oyoz
-
- # origins_ndc_z = 1 - 2 * self._min_depth / self._origins_cam[..., 2]
-
- origins_ndc_z = 1 - 2 * self._min_depth / self._origins[..., 2]
-
- origins_ndc = torch.stack([origins_ndc_x, origins_ndc_y, origins_ndc_z], dim=-1)
-
- # dxdz = self._directions_cam[..., 0] / self._directions_cam[..., 2]
- # dydz = self._directions_cam[..., 1] / self._directions_cam[..., 2]
-
- Rt_inv = _torch_inverse_cast(cams.rotation_matrix)
- directions_rotated_world = (Rt_inv @ self._directions_cam[..., None]).squeeze(dim=-1)
-
- dxdz = directions_rotated_world[..., 0] / directions_rotated_world[..., 2]
- dydz = directions_rotated_world[..., 1] / directions_rotated_world[..., 2]
-
- directions_ndc_x = fx_widths * dxdz - origins_ndc_x
- directions_ndc_y = fy_heights * dydz - origins_ndc_y
- directions_ndc_z = 1 - origins_ndc_z
- directions_ndc = torch.stack([directions_ndc_x, directions_ndc_y, directions_ndc_z], dim=-1)
-
- # Rt_inv = _torch_inverse_cast(cams.rotation_matrix)
- # origins_ndc_world = (Rt_inv @ origins_ndc[..., None]).squeeze(dim=-1)
- # directions_ndc_world = (Rt_inv @ directions_ndc[..., None]).squeeze(dim=-1)
-
- origins_ndc_world = origins_ndc
- directions_ndc_world = directions_ndc
-
- return origins_ndc_world, directions_ndc_world
-
- class Points2D_FlatTensors:
- r"""Class to hold x/y pixel coordinates for each ray, and its scene camera id."""
-
- def __init__(self) -> None:
- self._x: Tensor
- self._y: Tensor
- self._camera_ids: List[int] = []
-
- @staticmethod
- def _add_points2d_as_flat_tensors_to_num_ray_dict(
- n: int, x: Tensor, y: Tensor, camera_id: int, points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors]
- ) -> None:
- r"""Add x/y pixel coordinates for all rays casted by a scene camera to dictionary of pixel coordinates
- grouped by total number of rays.
- """ # noqa: D205
- if n not in points2d_as_flat_tensors:
- points2d_as_flat_tensors[n] = RaySampler.Points2D_FlatTensors()
- points2d_as_flat_tensors[n]._x = x.flatten()
- points2d_as_flat_tensors[n]._y = y.flatten()
- else:
- points2d_as_flat_tensors[n]._x = torch.cat((points2d_as_flat_tensors[n]._x, x.flatten()))
- points2d_as_flat_tensors[n]._y = torch.cat((points2d_as_flat_tensors[n]._y, y.flatten()))
- points2d_as_flat_tensors[n]._camera_ids.append(camera_id)
-
- @staticmethod
- def _build_num_ray_dict_of_points2d(
- points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors],
- ) -> Dict[int, Points2D]:
- r"""Build a dictionary of ray pixel points, by total number of rays as key.
-
- The dictionary groups rays by the total amount of rays, which allows the case of casting different number
- of rays from each scene camera.
-
- Args:
- points2d_as_flat_tensors: dictionary of pixel coordinates grouped by total number of rays:
- Dict[int, Points2D_FlatTensors]
-
- Returns:
- dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
- id it was casted by: Dict[int, Points2D]
-
- """
- num_ray_dict_of_points2d: Dict[int, RaySampler.Points2D] = {}
- for n, points2d_as_flat_tensor in points2d_as_flat_tensors.items():
- num_cams = len(points2d_as_flat_tensor._camera_ids)
- points_2d = (
- torch.stack((points2d_as_flat_tensor._x, points2d_as_flat_tensor._y))
- .permute(1, 0)
- .reshape(num_cams, -1, 2)
- )
- num_ray_dict_of_points2d[n] = RaySampler.Points2D(points_2d, points2d_as_flat_tensor._camera_ids)
- return num_ray_dict_of_points2d
-
-
-class RandomRaySampler(RaySampler):
- r"""Class to manage random ray spatial sampling.
-
- Args:
- min_depth: sampled rays minimal depth from cameras: float
- max_depth: sampled rays maximal depth from cameras: float
- ndc: convert to normalized device coordinates: bool
- device: device for ray tensors: Union[str, torch.device]
-
- """
-
- def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
- super().__init__(min_depth, max_depth, ndc, device, dtype)
-
- def sample_points_2d(self, heights: Tensor, widths: Tensor, num_img_rays: Tensor) -> Dict[int, RaySampler.Points2D]:
- r"""Randomly sample pixel points in 2d.
-
- Args:
- heights: tensor that holds scene camera image heights (can vary between cameras): math: `(B)`.
- widths: tensor that holds scene camera image widths (can vary between cameras): math: `(B)`.
- num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera: math: `(B)`.
-
- Returns:
- dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
- id it was casted by: Dict[int, Points2D]
-
- """
- num_img_rays = num_img_rays.int()
- points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
- for camera_id, (height, width, n) in enumerate(zip(heights.tolist(), widths.tolist(), num_img_rays.tolist())):
- y_rand = torch.trunc(torch.rand(n, device=self._device, dtype=self._dtype) * height)
- x_rand = torch.trunc(torch.rand(n, device=self._device, dtype=self._dtype) * width)
- RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
- n, x_rand, y_rand, camera_id, points2d_as_flat_tensors
- )
- return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
-
- def calc_ray_params(self, cameras: PinholeCamera, num_img_rays: Tensor) -> None:
- r"""Calculate ray parameters: origins, directions.
-
- Also stored are camera ids for each ray, and its pixel coordinates.
-
- Args:
- cameras: scene cameras: PinholeCamera
- num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera: int math: `(B)`.
-
- """
- num_cams = cameras.batch_size
- if num_cams != num_img_rays.shape[0]:
- raise ValueError(
- f"Number of cameras {num_cams} does not match size of tensor to define number of rays to march from "
- f"each camera {num_img_rays.shape[0]}"
- )
- points_2d_camera = self.sample_points_2d(cameras.height, cameras.width, num_img_rays)
- self._calc_ray_params(cameras, points_2d_camera)
-
-
-class RandomGridRaySampler(RandomRaySampler):
- r"""Class to manage random ray spatial sampling.
-
- Sampling is done on a regular grid of pixels by randomizing
- column and row values, and casting rays for all pixels along the selected ones.
-
- Args:
- min_depth: sampled rays minimal depth from cameras: float
- max_depth: sampled rays maximal depth from cameras: float
- ndc: convert to normalized device coordinates: bool
- device: device for ray tensors: Union[str, torch.device]
-
- """
-
- def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
- super().__init__(min_depth, max_depth, ndc, device, dtype)
-
- def sample_points_2d(self, heights: Tensor, widths: Tensor, num_img_rays: Tensor) -> Dict[int, RaySampler.Points2D]:
- r"""Randomly sample pixel points in 2d over a regular row-column grid.
-
- Args:
- heights: tensor that holds scene camera image heights (can vary between cameras): math: `(B)`.
- widths: tensor that holds scene camera image widths (can vary between cameras): math: `(B)`.
- num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera. Number of rows
- and columns is the square root of this value: int math: `(B)`.
-
- Returns:
- dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
- id it was casted by: Dict[int, Points2D]
-
- """
- num_img_rays = num_img_rays.int()
- points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
- for camera_id, (height, width, n) in enumerate(zip(heights.tolist(), widths.tolist(), num_img_rays.tolist())):
- n_sqrt = int(math.sqrt(n))
- y_rand = torch.randperm(int(height), device=self._device, dtype=self._dtype)[: min(int(height), n_sqrt)]
- x_rand = torch.randperm(int(width), device=self._device, dtype=self._dtype)[: min(int(width), n_sqrt)]
- y_grid, x_grid = torch_meshgrid([y_rand, x_rand], indexing="ij")
- RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
- n_sqrt * n_sqrt, x_grid, y_grid, camera_id, points2d_as_flat_tensors
- )
- return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
-
-
-class UniformRaySampler(RaySampler):
- r"""Class to manage uniform ray spatial sampling for all camera scene pixels.
-
- Args:
- min_depth: sampled rays minimal depth from cameras: float
- max_depth: sampled rays maximal depth from cameras: float
- ndc: convert to normalized device coordinates: bool
- device: device for ray tensors: Union[str, torch.device]
-
- """
-
- def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
- super().__init__(min_depth, max_depth, ndc, device, dtype)
-
- def sample_points_2d(
- self, heights: Tensor, widths: Tensor, sampling_step: int = 1
- ) -> Dict[int, RaySampler.Points2D]:
- r"""Uniformly sample pixel points in 2d for all scene camera pixels.
-
- Args:
- heights: tensor that holds scene camera image heights (can vary between cameras): math: `(B)`.
- widths: tensor that holds scene camera image widths (can vary between cameras): math: `(B)`.
- sampling_step: defines uniform strides between rows and columns: int.
-
- Returns:
- dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
- id it was casted by: Dict[int, Points2D]
-
- """
- heights = heights.int()
- widths = widths.int()
- points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
- for camera_id, (height, width) in enumerate(zip(heights.tolist(), widths.tolist())):
- n = height * width
- y_grid, x_grid = torch_meshgrid(
- [
- torch.arange(0, height, sampling_step, device=self._device, dtype=self._dtype),
- torch.arange(0, width, sampling_step, device=self._device, dtype=self._dtype),
- ],
- indexing="ij",
- )
- RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
- n, x_grid, y_grid, camera_id, points2d_as_flat_tensors
- )
- return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
-
- def calc_ray_params(self, cameras: PinholeCamera) -> None:
- points_2d_camera = self.sample_points_2d(cameras.height, cameras.width)
- self._calc_ray_params(cameras, points_2d_camera)
-
-
-def sample_lengths(
- num_rays: int, num_ray_points: int, device: Device, dtype: torch.dtype, irregular: bool = False
-) -> Tensor:
- """Sample points along the length of rays."""
- if num_ray_points <= 1:
- raise ValueError("Number of ray points must be greater than 1")
- if not irregular:
- zero_to_one = torch.linspace(0.0, 1.0, num_ray_points, device=device, dtype=dtype)
- lengths = zero_to_one.repeat(num_rays, 1) # FIXME: Expand instead of repeat maybe?
- else:
- zero_to_one = torch.linspace(0.0, 1.0, num_ray_points + 1, device=device, dtype=dtype)
- lengths = torch.rand(num_rays, num_ray_points, device=device) / num_ray_points + zero_to_one[:-1]
- return lengths
-
-
-# TODO: Implement hierarchical ray sampling as described in Mildenhall (2020) Sec. 5.2
-
-
-def sample_ray_points(
- origins: Tensor, directions: Tensor, lengths: Tensor
-) -> Tensor: # FIXME: Test by projecting to points_2d and compare with sampler 2d points
- r"""Sample points along ray.
-
- Args:
- origins: tensor containing ray origins in 3d world coordinates. Tensor shape :math:`(*, 3)`.
- directions: tensor containing ray directions in 3d world coordinates. Tensor shape :math:`(*, 3)`.
- lengths: tensor containing sampled distances along each ray. Tensor shape :math:`(*, num_ray_points)`.
-
- Returns:
- points_3d: Points along rays :math:`(*, num_ray_points, 3)`
-
- """
- points_3d = origins[..., None, :] + lengths[..., None] * directions[..., None, :]
- return points_3d
-
-
-def calc_ray_t_vals(points_3d: Tensor) -> Tensor:
- r"""Calculate t values along rays.
-
- Args:
- points_3d: Points along rays :math:`(*, num_ray_points, 3)`
-
- Returns:
- t values along rays :math:`(*, num_ray_points)`
-
- """
- t_vals = torch.linalg.norm(points_3d - points_3d[..., 0, :].unsqueeze(-2), dim=-1)
- return t_vals
diff --git a/kornia/nerf/volume_renderer.py b/kornia/nerf/volume_renderer.py
deleted file mode 100755
index 39be5fbfb..000000000
--- a/kornia/nerf/volume_renderer.py
+++ /dev/null
@@ -1,112 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import torch
-
-from kornia.core import Tensor
-from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.nerf.samplers import calc_ray_t_vals
-
-
-class VolumeRenderer(torch.nn.Module):
- r"""Base class for volume rendering.
-
- Implementation follows Ben Mildenhall et el. (2020) at https://arxiv.org/abs/2003.08934.
- """
-
- _huge = 1.0e10
- _eps = 1.0e-10
-
- def __init__(self, shift: int = 1) -> None:
- """Initialize the renderer.
-
- Args:
- shift: Size of far-field layer: int
-
- """
- super().__init__()
- self._shift = shift
-
- def _render(self, alpha: Tensor, rgbs: Tensor) -> Tensor:
- trans = torch.cumprod(1 - alpha + self._eps, dim=-2) # (*, N, 1)
- trans = torch.roll(trans, shifts=self._shift, dims=-2) # (*, N, 1)
- trans[..., : self._shift, :] = 1 # (*, N, 1)
-
- weights = trans * alpha # (*, N, 1)
-
- rgbs_rendered = torch.sum(weights * rgbs, dim=-2) # (*, 3)
-
- return rgbs_rendered
-
- def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
- raise NotImplementedError
-
-
-class IrregularRenderer(VolumeRenderer):
- """Renders 3D irregularly sampled points along rays."""
-
- def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
- r"""Render 3D irregularly sampled points along rays.
-
- Args:
- rgbs: RGB values of points along rays :math:`(*, N, 3)`
- densities: Volume densities of points along rays :math:`(*, N)`
- points_3d: 3D points along rays :math:`(*, N, 3)`
-
- Returns:
- Rendered RGB values for each ray :math:`(*, 3)`
-
- """
- t_vals = calc_ray_t_vals(points_3d)
- deltas = t_vals[..., 1:] - t_vals[..., :-1] # (*, N - 1)
- far = torch.empty(size=t_vals.shape[:-1], dtype=t_vals.dtype, device=t_vals.device).fill_(self._huge)
- deltas = torch.cat([deltas, far[..., None]], dim=-1) # (*, N)
-
- alpha = 1 - torch.exp(-1.0 * densities * deltas[..., None]) # (*, N)
-
- return self._render(alpha, rgbs)
-
-
-class RegularRenderer(VolumeRenderer):
- """Renders 3D regularly sampled points along rays."""
-
- def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
- r"""Render 3D regularly sampled points along rays.
-
- Args:
- rgbs: RGB values of points along rays :math:`(*, N, 3)`
- densities: Volume densities of points along rays :math:`(*, N)`
- points_3d: 3D points along rays :math:`(*, N, 3)`
-
- Returns:
- Rendered RGB values for each ray :math:`(*, 3)`
-
- """
- KORNIA_CHECK_SHAPE(rgbs, ["*", "N", "3"])
- KORNIA_CHECK_SHAPE(densities, ["*", "N"])
- KORNIA_CHECK_SHAPE(points_3d, ["*", "N", "3"])
-
- num_ray_points: int = points_3d.shape[-2]
-
- points_3d = points_3d.reshape(-1, num_ray_points, 3) # (*, N, 3)
-
- delta_3d = points_3d[0, 1, :] - points_3d[0, 0, :] # (*, 3)
- delta = torch.linalg.norm(delta_3d, dim=-1)
-
- alpha = 1 - torch.exp(-1.0 * densities * delta) # (*, N)
-
- return self._render(alpha, rgbs)
diff --git a/kornia/x/__init__.py b/kornia/x/__init__.py
deleted file mode 100644
index 1a4787ea3..000000000
--- a/kornia/x/__init__.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Experimental submodule (x) for Kornia.
-
-This package provides experimental features, trainers, callbacks, and utilities for advanced workflows.
-"""
-
-from .callbacks import EarlyStopping, ModelCheckpoint
-from .trainer import Trainer
-from .trainers import ImageClassifierTrainer, ObjectDetectionTrainer, SemanticSegmentationTrainer
-from .utils import Configuration, Lambda, TrainerState
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.py
deleted file mode 100644
index b38b70f07..000000000
--- a/kornia/x/callbacks.py
+++ /dev/null
@@ -1,158 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from math import inf
-from pathlib import Path
-from typing import Callable, Dict, Optional, Union
-
-import torch
-
-from kornia.core import Module
-from kornia.metrics import AverageMeter
-
-from .utils import TrainerState
-
-
-def default_filename_fcn(epoch: Union[str, int], metric: Union[str, float]) -> str:
- """Generate the filename in the model checkpoint."""
- return f"model_epoch={epoch}_metricValue={metric}.pt"
-
-
-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.
-
- 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.
- max_mode: if true metric will be multiply by -1,
- turn this flag when increasing metric value is expected for example Accuracy
-
- **Usage example:**
-
- .. code:: python
-
- early_stop = EarlyStopping(
- monitor="loss", patience=10
- )
-
- trainer = ImageClassifierTrainer(
- callbacks={"on_epoch_end", early_stop}
- )
-
- """
-
- def __init__(
- self,
- monitor: str,
- min_delta: float = 0.0,
- patience: int = 8,
- max_mode: bool = False,
- ) -> None:
- self.monitor = monitor
- self.min_delta = min_delta
- self.patience = patience
- # flag to reverse metric, for example in case of accuracy metric where bigger value is better
- # In classical loss functions smaller value = better,
- # in case of max_mode training end with metric stable/decreasing
- self.max_mode = max_mode
-
- self.counter: int = 0
- self.best_score: float = -inf if max_mode else inf
- self.early_stop: bool = False
-
- def __call__(self, model: Module, epoch: int, valid_metric: Dict[str, AverageMeter]) -> TrainerState:
- score: float = valid_metric[self.monitor].avg
- is_best: bool = score > self.best_score if self.max_mode else score < self.best_score
- if is_best:
- self.best_score = score
- self.counter = 0
- else:
- # Example score = 1.9 best_score = 2.0 min_delta = 0.15
- # with max_mode (1.9 > (2.0 - 0.15)) == True
- # with min_mode (1.9 < (2.0 + 0.15)) == True
- is_within_delta: bool = (
- score > (self.best_score - self.min_delta)
- if self.max_mode
- else score < (self.best_score + self.min_delta)
- )
- if not is_within_delta:
- self.counter += 1
- if self.counter >= self.patience:
- self.early_stop = True
-
- if self.early_stop:
- 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 every epoch.
-
- Args:
- filepath: the where to save the mode.
- monitor: the name of the value to track.
- max_mode: if true metric will be multiply by -1
- turn this flag when increasing metric value is expected for example Accuracy
- **Usage example:**
-
- .. code:: python
-
- model_checkpoint = ModelCheckpoint(
- filepath="./outputs", monitor="loss",
- )
-
- trainer = ImageClassifierTrainer(...,
- callbacks={"on_checkpoint", model_checkpoint}
- )
-
- """
-
- def __init__(
- self,
- filepath: str,
- monitor: str,
- filename_fcn: Optional[Callable[..., str]] = None,
- max_mode: bool = False,
- ) -> None:
- self.filepath = filepath
- self.monitor = monitor
- self._filename_fcn = filename_fcn or default_filename_fcn
- # track best model
- self.best_metric: float = -inf if max_mode else inf
- # flag to reverse metric, for example in case of accuracy metric where bigger value is better
- # In classical loss functions smaller value = better,
- # In case of max_mode checkpoints are saved if new metric value > old metric value
- self.max_mode = max_mode
-
- # create directory
- Path(self.filepath).mkdir(parents=True, exist_ok=True)
-
- def __call__(self, model: Module, epoch: int, valid_metric: Dict[str, AverageMeter]) -> None:
- valid_metric_value: float = valid_metric[self.monitor].avg
- is_best: bool = (
- valid_metric_value > self.best_metric if self.max_mode else valid_metric_value < self.best_metric
- )
- if is_best:
- self.best_metric = valid_metric_value
- # store old metric and save new model
- filename = Path(self.filepath) / self._filename_fcn(epoch, valid_metric_value)
- torch.save(model, filename)
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
deleted file mode 100644
index 5a3397852..000000000
--- a/kornia/x/trainer.py
+++ /dev/null
@@ -1,235 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import logging
-from typing import Any, Callable, Dict, Optional
-
-# the accelerator library is a requirement for the Trainer
-# but it is optional for grousnd base user of kornia.
-import torch
-from torch.optim import Optimizer, lr_scheduler
-from torch.utils.data import DataLoader
-
-try:
- from accelerate import Accelerator
-except ImportError:
- Accelerator = None
-
-from kornia.core import Module, Tensor
-from kornia.metrics import AverageMeter
-
-from .utils import Configuration, StatsTracker, TrainerState
-
-callbacks_whitelist = [
- # high level functions
- "preprocess",
- "augmentations",
- "evaluate",
- "fit",
- "fit_epoch",
- # events (by calling order)
- "on_epoch_start",
- "on_before_model",
- "on_after_model",
- "on_checkpoint",
- "on_epoch_end",
-]
-
-
-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: Module,
- train_dataloader: DataLoader[Any],
- valid_dataloader: DataLoader[Any],
- criterion: Optional[Module],
- optimizer: Optimizer,
- scheduler: lr_scheduler._LRScheduler,
- config: Configuration,
- callbacks: Optional[Dict[str, Callable[..., None]]] = None,
- ) -> 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 = None if criterion is None else criterion.to(self.device)
- self.optimizer = self.accelerator.prepare(optimizer)
- self.scheduler = scheduler
- self.config = config
-
- # configure callbacks
- if callbacks is None:
- callbacks = {}
- for fn_name, fn in callbacks.items():
- if fn_name not in callbacks_whitelist:
- raise ValueError(f"Not supported: {fn_name}.")
- setattr(Trainer, fn_name, fn)
-
- # hyper-params
- self.num_epochs = config.num_epochs
-
- self.state = TrainerState.STARTING
-
- self._logger = logging.getLogger("train")
-
- @property
- def device(self) -> torch.device:
- return self.accelerator.device
-
- def backward(self, loss: 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):
- sample = {"input": sample[0], "target": sample[1]} # new dataset api will come like this
- self.optimizer.zero_grad()
- # perform the preprocess and augmentations in batch
- sample = self.preprocess(sample)
- sample = self.augmentations(sample)
- sample = self.on_before_model(sample)
- # make the actual inference
- output = self.on_model(self.model, sample)
- self.on_after_model(output, sample) # for debugging purposes
- loss = self.compute_loss(output, sample["target"])
- self.backward(loss)
- self.optimizer.step()
-
- losses.update(loss.item(), len(sample["input"]))
-
- 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.state = TrainerState.TRAINING
- self.fit_epoch(epoch)
-
- # call internally the evaluation loop
- # NOTE: override to customize your evaluation routine
- self.state = TrainerState.VALIDATE
- valid_stats = self.evaluate()
-
- self.on_checkpoint(self.model, epoch, valid_stats)
-
- self.on_epoch_end()
- if self.state == TrainerState.TERMINATE:
- break
-
- # END OF THE EPOCH
- self.scheduler.step()
-
- ...
-
- # events stubs
-
- @torch.no_grad()
- def evaluate(self) -> Dict[str, AverageMeter]:
- self.model.eval()
- stats = StatsTracker()
- for sample_id, sample in enumerate(self.valid_dataloader):
- sample = {"input": sample[0], "target": sample[1]} # new dataset api will come like this
- # perform the preprocess and augmentations in batch
- sample = self.preprocess(sample)
- sample = self.on_before_model(sample)
- # Forward
- out = self.on_model(self.model, sample)
- self.on_after_model(out, sample)
-
- batch_size: int = len(sample["input"])
- # measure accuracy and record loss
- # Loss computation
- if self.criterion is not None:
- val_loss = self.compute_loss(out, sample["target"])
- stats.update("losses", val_loss.item(), batch_size)
- stats.update_from_dict(self.compute_metrics(out, sample["target"]), batch_size)
-
- if sample_id % 10 == 0:
- self._logger.info(f"Test: {sample_id}/{len(self.valid_dataloader)} {stats}")
-
- return stats.as_dict()
-
- def on_epoch_start(self, *args: Any, **kwargs: Any) -> None: ...
-
- def preprocess(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
- return x
-
- def augmentations(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
- return x
-
- def compute_metrics(self, *args: Any) -> Dict[str, float]:
- """Compute metrics during the evaluation."""
- return {}
-
- def compute_loss(self, *args: Tensor) -> Tensor:
- if self.criterion is None:
- raise RuntimeError("`criterion` should not be None.")
- return self.criterion(*args)
-
- def on_before_model(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
- return x
-
- def on_model(self, model: Module, sample: Dict[str, Tensor]) -> Tensor:
- return model(sample["input"])
-
- def on_after_model(self, output: Tensor, sample: Dict[str, Tensor]) -> None: ...
-
- def on_checkpoint(self, *args: Any, **kwargs: Dict[str, Any]) -> None: ...
-
- def on_epoch_end(self, *args: Any, **kwargs: Dict[str, Any]) -> None: ...
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
deleted file mode 100644
index 9a8fd69dc..000000000
--- a/kornia/x/trainers.py
+++ /dev/null
@@ -1,135 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from typing import Any, Callable, Dict, Optional, Tuple
-
-from torch.optim import Optimizer, lr_scheduler
-from torch.utils.data import DataLoader
-
-from kornia.core import Module, Tensor, stack
-from kornia.metrics import accuracy, mean_average_precision, mean_iou
-
-from .trainer import Trainer
-from .utils import Configuration
-
-
-class ImageClassifierTrainer(Trainer):
- """Module to be used for image classification purposes.
-
- The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
- :py:func:`~kornia.x.Trainer.evaluate` function implementing a standard
- :py:func:`~kornia.metrics.accuracy` topk@[1, 5].
-
- .. seealso::
- Learn how to use this class in the following
- `example <https://github.com/kornia/tutorials/tree/master/scripts/training/image_classifier/>`__.
- """
-
- def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
- if len(args) != 2:
- raise AssertionError
- out, target = args
- acc1, acc5 = accuracy(out, target, topk=(1, 5))
- return {"top1": acc1.item(), "top5": acc5.item()}
-
-
-class SemanticSegmentationTrainer(Trainer):
- """Module to be used for semantic segmentation purposes.
-
- The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
- :py:func:`~kornia.x.Trainer.evaluate` function implementing IoU :py:func:`~kornia.metrics.mean_iou`.
-
- .. seealso::
- Learn how to use this class in the following
- `example <https://github.com/kornia/tutorials/tree/master/scripts/training/semantic_segmentation/>`__.
- """
-
- def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
- if len(args) != 2:
- raise AssertionError
- out, target = args
- iou = mean_iou(out.argmax(1), target, out.shape[1]).mean()
- return {"iou": iou.item()}
-
-
-class ObjectDetectionTrainer(Trainer):
- """Module to be used for object detection purposes.
-
- The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
- :py:func:`~kornia.x.Trainer.evaluate` function implementing IoU :py:func:`~kornia.metrics.mean_iou`.
-
- .. seealso::
- Learn how to use this class in the following
- `example <https://github.com/kornia/tutorials/tree/master/scripts/training/object_detection/>`__.
- """
-
- def __init__(
- self,
- model: Module,
- train_dataloader: DataLoader[Any],
- valid_dataloader: DataLoader[Any],
- criterion: Optional[Module],
- optimizer: Optimizer,
- scheduler: lr_scheduler._LRScheduler,
- config: Configuration,
- num_classes: int,
- callbacks: Optional[Dict[str, Callable[..., None]]] = None,
- loss_computed_by_model: Optional[bool] = None,
- ) -> None:
- if callbacks is None:
- callbacks = {}
- super().__init__(model, train_dataloader, valid_dataloader, criterion, optimizer, scheduler, config, callbacks)
- # TODO: auto-detect if the model is from TorchVision
- self.loss_computed_by_model = loss_computed_by_model
- self.num_classes = num_classes
-
- def on_model(self, model: Module, sample: Dict[str, Tensor]) -> Tensor:
- if self.loss_computed_by_model and model.training:
- return model(sample["input"], sample["target"])
- return model(sample["input"])
-
- def compute_loss(self, *args: Tensor) -> Tensor:
- if self.loss_computed_by_model:
- # Note: in case of dict losses obtained
- if isinstance(args[0], dict):
- return stack([v for _, v in args[0].items()]).mean()
- return stack(list(args[0])).sum()
- if self.criterion is None:
- raise RuntimeError("`criterion` should not be None if `loss_computed_by_model` is False.")
- return self.criterion(*args)
-
- def compute_metrics(self, *args: Tuple[Dict[str, Tensor]]) -> Dict[str, float]:
- if (
- isinstance(args[0], dict)
- and "boxes" in args[0]
- and "labels" in args[0]
- and "scores" in args[0]
- and isinstance(args[1], dict)
- and "boxes" in args[1]
- and "labels" in args[1]
- ):
- mAP, _ = mean_average_precision(
- [a["boxes"] for a in args[0]],
- [a["labels"] for a in args[0]],
- [a["scores"] for a in args[0]],
- [a["boxes"] for a in args[1]],
- [a["labels"] for a in args[1]],
- n_classes=self.num_classes,
- threshold=0.000001,
- )
- return {"mAP": mAP.item()}
- return super().compute_metrics(*args)
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
deleted file mode 100644
index 783724897..000000000
--- a/kornia/x/utils.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from dataclasses import dataclass, field
-from enum import Enum
-from typing import Any, Callable, Dict, Tuple
-
-from kornia.core import Module, Tensor
-from kornia.metrics.average_meter import AverageMeter
-
-# import yaml
-
-
-class TrainerState(Enum):
- STARTING = 0
- TRAINING = 1
- VALIDATE = 2
- TERMINATE = 3
-
-
-# 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."})
- image_size: Tuple[int, int] = field(default=(224, 224), metadata={"help": "The input image size."})
-
- # 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)
-
-
-class Lambda(Module):
- """Module to create a lambda function as Module.
-
- Args:
- fcn: a pointer to any function.
-
- Example:
- >>> import torch
- >>> import kornia as K
- >>> fcn = Lambda(lambda x: K.geometry.resize(x, (32, 16)))
- >>> fcn(torch.rand(1, 4, 64, 32)).shape
- torch.Size([1, 4, 32, 16])
-
- """
-
- def __init__(self, fcn: Callable[..., Any]) -> None:
- super().__init__()
- self.fcn = fcn
-
- def forward(self, x: Tensor) -> Any:
- return self.fcn(x)
-
-
-class StatsTracker:
- """Stats tracker for computing metrics on the fly."""
-
- def __init__(self) -> None:
- self._stats: Dict[str, AverageMeter] = {}
-
- @property
- def stats(self) -> Dict[str, AverageMeter]:
- return self._stats
-
- def update(self, key: str, val: float, batch_size: int) -> None:
- """Update the stats by the key value pair."""
- if key not in self._stats:
- self._stats[key] = AverageMeter()
- self._stats[key].update(val, batch_size)
-
- def update_from_dict(self, dic: Dict[str, float], batch_size: int) -> None:
- """Update the stats by the dict."""
- for k, v in dic.items():
- self.update(k, v, batch_size)
-
- def __repr__(self) -> str:
- return " ".join([f"{k.upper()}: {v.val:.2f} {v.val:.2f} " for k, v in self._stats.items()])
-
- def as_dict(self) -> Dict[str, AverageMeter]:
- """Return the dict format."""
- return self._stats
diff --git a/pyproject.toml b/pyproject.toml
index 5848e1191..b0c0380db 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -42,7 +42,6 @@ Issues = "https://github.com/kornia/kornia/issues"
[project.optional-dependencies]
dev = [
- "accelerate",
"coverage",
"diffusers",
"ivy>=1.0.0.0",
@@ -79,7 +78,6 @@ docs = [
"sphinxcontrib-gtagjs",
"sphinxcontrib-youtube",
]
-x = ["accelerate", "onnxruntime-gpu>=1.16; sys_platform != 'darwin'"]
[tool.hatch.version]
path = "kornia/__init__.py"
diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.py
index 099a1d91f..22f68c14d 100644
--- a/tests/augmentation/test_auto_operation.py
+++ b/tests/augmentation/test_auto_operation.py
@@ -63,33 +63,6 @@ def _test_sequential(augment_method, device, dtype):
reproducibility_test((inp, mask, bbox, keypoints), aug)
-class TestOperations:
- @pytest.mark.parametrize("op", _find_all_ops())
- def test_step_routine(self, op: OperationBase):
- op = op.eval()
- op = op.train()
- if op.magnitude is not None:
- init_mag = op.magnitude.item()
- init_prob = op.probability.item()
-
- optimizer = torch.optim.SGD(op.parameters(), lr=10, momentum=0.9)
-
- for _ in range(5):
- in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
- optimizer.zero_grad()
- x = op(in_tensor)
- loss = (x - 0).mean()
- loss.backward()
- optimizer.step()
-
- if op.magnitude is not None:
- assert init_mag != op.magnitude.item()
- if isinstance(op, ops.Equalize):
- # NOTE: Equalize is somehow not working yet to update the probabilities.
- return
- assert init_prob != op.probability.item()
-
-
class TestAutoAugment(BaseTester):
@pytest.mark.parametrize("policy", ["imagenet", "cifar10", "svhn", [[("shear_x", 0.9, 4), ("invert", 0.2, None)]]])
def test_smoke(self, policy, device, dtype):
diff --git a/tests/grad_estimator/test_ste.py b/tests/grad_estimator/test_ste.py
deleted file mode 100644
index 134163fb8..000000000
--- a/tests/grad_estimator/test_ste.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import pytest
-import torch
-import torch.nn.functional as F
-from torch.testing import assert_close
-
-import kornia.augmentation as K
-from kornia.grad_estimator import STEFunction, StraightThroughEstimator
-
-
-class TestSTE:
- def test_smoke(self):
- StraightThroughEstimator(K.Normalize(0.5, 0.5))
-
- def test_function(self, device, dtype):
- data = torch.randn(4, requires_grad=True, device=device, dtype=dtype)
- output = torch.sign(data)
- loss = output.mean()
- loss.backward()
- assert_close(data.grad, torch.tensor([0.0, 0.0, 0.0, 0.0], device=device, dtype=dtype))
-
- out_est = STEFunction.apply(data, output, F.hardtanh)
- loss = out_est.mean()
- loss.backward()
- assert_close(data.grad, torch.tensor([0.2500, 0.2500, 0.2500, 0.2500], device=device, dtype=dtype))
-
- out_est = STEFunction.apply(data, output, None)
- loss = out_est.mean()
- loss.backward()
- assert_close(data.grad, torch.tensor([0.5000, 0.5000, 0.5000, 0.5000], device=device, dtype=dtype))
-
- def test_module(self, device, dtype):
- data = torch.randn(1, 1, 4, 4, requires_grad=True, device=device, dtype=dtype)
- estimator = StraightThroughEstimator(K.RandomPosterize(3, p=1.0), grad_fn=F.hardtanh)
- out = estimator(data)
- loss = out.mean()
- loss.backward()
- o = torch.tensor(
- [
- [
- [
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- ]
- ]
- ],
- device=device,
- dtype=dtype,
- )
- assert_close(data.grad, o)
-
- @pytest.mark.skip("Function.apply is not supported in Torchscript rightnow.")
- def test_jit(self, device, dtype):
- inputs = torch.rand(2, 3, 30, 30, dtype=dtype, device=device)
-
- op = StraightThroughEstimator(torch.nn.MaxPool2d(3), grad_fn=None)
- op_script = torch.jit.script(op)
- actual = op_script(inputs)
- expected = op(inputs)
- assert_close(actual, expected)
-
- @pytest.mark.skip("Function is not supported to export to onnx rightnow.")
- def test_onnx(self, device, dtype):
- inputs = torch.rand(2, 3, 30, 30, dtype=dtype, device=device)
- model = StraightThroughEstimator(torch.nn.PixelShuffle(1), grad_fn=None)
-
- input_names = ["input"]
- output_names = ["output1"]
-
- torch.onnx.export(model, inputs, "t.onnx", verbose=True, input_names=input_names, output_names=output_names)
diff --git a/tests/nerf/test_camera_utils.py b/tests/nerf/test_camera_utils.py
deleted file mode 100755
index fd64b24ac..000000000
--- a/tests/nerf/test_camera_utils.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import hashlib
-import urllib.request
-
-import pytest
-import torch
-
-from kornia.geometry.conversions import quaternion_to_rotation_matrix
-from kornia.nerf.camera_utils import create_spiral_path, parse_colmap_output
-
-from testing.base import assert_close
-
-_ref = {
- "cameras": (
- "https://raw.githubusercontent.com/kornia/data/main/nerf/cameras.txt",
- "aee6dbd448be900a0d4de85d08914e47a84f025e16f8498cbf9f7bfc7eff09a6",
- ),
- "images": (
- "https://raw.githubusercontent.com/kornia/data/main/nerf/images.txt",
- "e6b66a9b76d92e498697edece33be76ae69aa28a960bc895a59495763de61286",
- ),
-}
-
-
-def _get_data(url: str, sha256: str) -> str:
- if not url.startswith(("http:", "https:")):
- raise ValueError("URL must start with 'http:' or 'https:'")
-
- req = urllib.request.Request(url) # noqa: S310
- with urllib.request.urlopen(req) as response: # noqa: S310
- data = response.read()
-
- assert hashlib.sha256(data).hexdigest() == sha256
-
- return data.decode("utf-8")
-
-
-def colmap_cameras_path(tmp_path):
- data = _get_data(*_ref["cameras"])
-
- p = tmp_path / "camera.txt"
- p.write_text(data)
-
- return p
-
-
-def colmap_images_path(tmp_path):
- data = _get_data(*_ref["images"])
-
- p = tmp_path / "images.txt"
- p.write_text(data)
-
- return p
-
-
-def test_parse_colmap_output(device, dtype, colmap_cameras_path, colmap_images_path) -> None:
- img_names, cameras = parse_colmap_output(colmap_cameras_path, colmap_images_path, device, dtype)
- assert_close(cameras.fx[0], torch.tensor(845.5654, device=device, dtype=dtype))
- assert_close(cameras.fy[0], torch.tensor(845.5654, device=device, dtype=dtype))
- assert_close(cameras.cx[0], torch.tensor(504, device=device, dtype=dtype))
- assert_close(cameras.cy[0], torch.tensor(378, device=device, dtype=dtype))
-
- qw = 0.99967420027533338
- qx = -0.016637661896892787
- qy = 0.012113517278577941
- qz = 0.015097821353390602
- tx = 3.2407154690493751
- ty = 2.3447342819165637
- tz = -1.0631749488011808
-
- q = torch.tensor([qw, qx, qy, qz], device=device, dtype=dtype)
- R = quaternion_to_rotation_matrix(q)
- t = torch.tensor([tx, ty, tz], device=device, dtype=dtype)
-
- assert_close(R, cameras.rotation_matrix[2])
- assert_close(cameras.translation_vector[2], t.unsqueeze(-1))
-
- assert img_names[2] == "image002.png"
-
-
-def test_create_spiral_path(device, dtype, colmap_cameras_path, colmap_images_path) -> None:
- _, cameras = parse_colmap_output(colmap_cameras_path, colmap_images_path, device, dtype)
- try:
- create_spiral_path(cameras, 1, 30, 3)
- except Exception as err:
- raise AssertionError from err
diff --git a/tests/nerf/test_data_utils.py b/tests/nerf/test_data_utils.py
deleted file mode 100755
index 9ab1c0b94..000000000
--- a/tests/nerf/test_data_utils.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-from kornia.geometry.camera.utils import create_four_cameras, create_random_images_for_cameras
-from kornia.nerf.data_utils import RayDataset, instantiate_ray_dataloader
-
-from testing.base import assert_close
-
-
-class TestDataset:
- def test_uniform_ray_dataset(self, device, dtype):
- cameras = create_four_cameras(device, dtype)
- imgs = create_random_images_for_cameras(cameras)
- dataset = RayDataset(cameras, 1, 2, False, device=device, dtype=dtype)
- dataset.init_ray_dataset()
- dataset.init_images_for_training(imgs)
-
- batch_size = 32
- data_loader = instantiate_ray_dataloader(dataset, batch_size=batch_size, shuffle=False)
- d = next(iter(data_loader)) # First batch of 32 labeled rays
-
- # Check dimensions
- assert d[0].shape == (batch_size, 3) # Ray origins
- assert d[1].shape == (batch_size, 3) # Ray directions
- assert d[2].shape == (batch_size, 3) # Ray rgbs
-
- # Comparing RGB values between sampled rays and original images
- assert_close(d[2][0].cpu().to(dtype), (imgs[0][:, 0, 0] / 255.0).to(dtype))
- assert_close(
- d[2][1].cpu().to(dtype), (imgs[0][:, 0, 1] / 255.0).to(dtype)
- ) # First row, second column in the image (1 sample point index)
- assert_close(
- d[2][9].cpu().to(dtype), (imgs[0][:, 1, 0] / 255.0).to(dtype)
- ) # Second row, first column in the image (9 sample point index)
diff --git a/tests/nerf/test_nerf_model.py b/tests/nerf/test_nerf_model.py
deleted file mode 100755
index aaa910a2f..000000000
--- a/tests/nerf/test_nerf_model.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import pytest
-import torch
-
-from kornia.geometry.camera import PinholeCamera
-from kornia.nerf.nerf_model import MLP, NerfModel, NerfModelRenderer
-
-
-def nerf_model():
- return NerfModel(
- num_ray_points=11,
- num_pos_freqs=10,
- num_dir_freqs=4,
- num_units=2,
- num_unit_layers=4,
- num_hidden=256,
- )
-
-
-def create_default_pinhole_camera(height, width, device, dtype):
- intrinsics = torch.eye(4, device=device, dtype=dtype)
- intrinsics[0, -1] = width / 2.0 # cx
- intrinsics[1, -1] = height / 2.0 # cy
- return PinholeCamera(
- intrinsics=intrinsics[None],
- extrinsics=torch.eye(4, device=device, dtype=dtype)[None],
- height=torch.tensor([height], device=device, dtype=dtype),
- width=torch.tensor([width], device=device, dtype=dtype),
- )
-
-
-class TestNerfModel:
- def test_mlp(self, device, dtype):
- d_input = 63 # Input dimension after encoding
- num_hidden = 256
- mlp = MLP(d_input, num_units=2, num_unit_layers=4, num_hidden=num_hidden)
- mlp.to(device=device, dtype=dtype)
-
- num_rays = 15
- num_ray_points = 11
- x = torch.rand(num_rays, num_ray_points, d_input, device=device, dtype=dtype)
- xout = mlp(x)
- assert xout.shape == (num_rays, num_ray_points, num_hidden)
-
- def test_nerf(self, device, dtype, nerf_model):
- nerf_model = nerf_model.to(device=device, dtype=dtype)
- num_rays = 15
- origins = torch.rand(num_rays, 3, device=device, dtype=dtype)
- directions = torch.rand(num_rays, 3, device=device, dtype=dtype)
- rgbs = nerf_model(origins, directions)
- assert rgbs.shape == (num_rays, 3)
-
- def test_render_view(self, device, dtype, nerf_model):
- nerf_model = nerf_model.to(device=device, dtype=dtype)
- height, width = 5, 6
- renderer = NerfModelRenderer(nerf_model, image_size=(height, width), device=device, dtype=dtype)
- camera: PinholeCamera = create_default_pinhole_camera(height, width, device, dtype)
- image = renderer.render_view(camera)
- assert image.shape == (height, width, 3)
diff --git a/tests/nerf/test_nerf_solver.py b/tests/nerf/test_nerf_solver.py
deleted file mode 100755
index 366a52670..000000000
--- a/tests/nerf/test_nerf_solver.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import pytest
-import torch
-
-from kornia.core import Tensor
-from kornia.geometry.camera import PinholeCamera
-from kornia.geometry.camera.utils import (
- create_four_cameras,
- create_pinhole_camera,
- create_random_images_for_cameras,
- create_red_images_for_cameras,
-)
-from kornia.nerf.nerf_model import NerfModelRenderer
-from kornia.nerf.nerf_solver import NerfSolver
-
-from testing.base import assert_close
-
-
-class TestNerfSolver:
- @pytest.mark.slow
- def test_parameter_change_after_one_epoch(self, device, dtype):
- nerf_obj = NerfSolver(device, dtype)
- cameras: PinholeCamera = create_four_cameras(device, dtype)
- imgs: list[Tensor] = create_random_images_for_cameras(cameras)
- nerf_obj.setup_solver(cameras, 1.0, 3.0, True, imgs, num_img_rays=45, batch_size=1, num_ray_points=10)
-
- params_before_update = [torch.clone(param).detach() for param in nerf_obj.nerf_model.parameters()]
-
- nerf_obj.run(num_epochs=5)
-
- params_after_update = [torch.clone(param).detach() for param in nerf_obj.nerf_model.parameters()]
-
- assert all(
- not torch.equal(param_before_update, param_after_update)
- for param_before_update, param_after_update in zip(params_before_update, params_after_update)
- )
-
- def test_only_red_uniform_sampling(self, device, dtype):
- torch.manual_seed(1) # For reproducibility of random processes
- camera: PinholeCamera = create_pinhole_camera(5, 9, device, dtype)
- img: list[Tensor] = create_red_images_for_cameras(camera, device)
-
- # train the model
- nerf_obj = NerfSolver(device, dtype)
- nerf_obj.setup_solver(camera, 1.0, 3.0, False, img, 15, 2, 10)
- nerf_obj.run(num_epochs=10)
-
- # render the actual image
- renderer = NerfModelRenderer(nerf_obj.nerf_model, (5, 9), device, dtype)
- img_rendered = renderer.render_view(camera).permute(2, 0, 1) # CxHxW
-
- assert_close(img_rendered.to(device, dtype), img[0].to(device, dtype) / 255.0)
-
- def test_single_ray(self, device, dtype):
- camera: PinholeCamera = create_pinhole_camera(5, 9, device, dtype)
- img: list[Tensor] = create_red_images_for_cameras(camera, device)
-
- nerf_obj = NerfSolver(device=device, dtype=dtype)
- nerf_obj.setup_solver(camera, 1.0, 3.0, True, img, 1, 2, 10)
- nerf_obj.run(num_epochs=20)
-
- def test_only_red(self, device, dtype):
- torch.manual_seed(0) # For reproducibility of random processes
-
- camera: PinholeCamera = create_pinhole_camera(5, 9, device, dtype)
- img: list[Tensor] = create_red_images_for_cameras(camera, device)
-
- # train the model
- nerf_obj = NerfSolver(device=device, dtype=dtype)
- nerf_obj.setup_solver(camera, 1.0, 3.0, False, img, num_img_rays=15, batch_size=5, num_ray_points=10, lr=1e-2)
- nerf_obj.run(num_epochs=10)
-
- # render the actual image
- renderer = NerfModelRenderer(nerf_obj.nerf_model, (5, 9), device, dtype)
- img_rendered = renderer.render_view(camera).permute(2, 0, 1) # CxHxW
-
- assert_close(img_rendered.to(device, dtype), img[0].to(device, dtype) / 255.0)
diff --git a/tests/nerf/test_positional_encoder.py b/tests/nerf/test_positional_encoder.py
deleted file mode 100755
index 72b10b183..000000000
--- a/tests/nerf/test_positional_encoder.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import torch
-
-from kornia.nerf.positional_encoder import PositionalEncoder
-
-
-class TestPositionalEncoder:
- def test_dimensions(self, device, dtype):
- num_rays = 15
- num_ray_points = 11
- num_dims = 3
- x = torch.rand(num_rays, num_ray_points, num_dims, device=device, dtype=dtype)
- num_freqs = 10
- pos_encoder = PositionalEncoder(num_dims, num_freqs)
- x_encoded = pos_encoder(x)
- assert x_encoded.shape == (num_rays, num_ray_points, pos_encoder.num_encoded_dims)
diff --git a/tests/nerf/test_rays.py b/tests/nerf/test_rays.py
deleted file mode 100755
index b2a0ff2b8..000000000
--- a/tests/nerf/test_rays.py
+++ /dev/null
@@ -1,115 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-from kornia.geometry.camera.utils import create_camera_dimensions, create_four_cameras
-from kornia.nerf.samplers import (
- RandomGridRaySampler,
- RandomRaySampler,
- UniformRaySampler,
- calc_ray_t_vals,
- cameras_for_ids,
- sample_lengths,
- sample_ray_points,
-)
-
-from testing.base import assert_close
-
-
-class TestRaySampler_2DPoints:
- def test_dimensions_random_sampler(self, device, dtype):
- heights, widths, num_img_rays = create_camera_dimensions(device, dtype)
- sampler = RandomRaySampler(1, 1, ndc=False, device=device, dtype=dtype)
- points_2d_camera = sampler.sample_points_2d(heights, widths, num_img_rays)
- assert len(points_2d_camera) == 2
- assert points_2d_camera[10].points_2d.shape == (3, 10, 2)
- assert points_2d_camera[15].points_2d.shape == (2, 15, 2)
-
- def test_dimensions_uniform_sampler(self, device, dtype):
- heights, widths, _ = create_camera_dimensions(device, dtype)
- sampler = UniformRaySampler(1, 1, ndc=False, device=device, dtype=dtype)
- points_2d_camera = sampler.sample_points_2d(heights, widths)
- assert len(points_2d_camera) == 2
- assert points_2d_camera[60000].points_2d.shape == (3, 60000, 2)
- assert points_2d_camera[40000].points_2d.shape == (2, 40000, 2)
-
- def test_dimensions_radom_grid_sampler(self, device, dtype):
- heights, widths, num_img_rays = create_camera_dimensions(device, dtype)
- sampler = RandomGridRaySampler(1, 1, True, device=device, dtype=dtype)
- points_2d_camera = sampler.sample_points_2d(heights, widths, num_img_rays)
- assert len(points_2d_camera) == 1
- assert points_2d_camera[9].points_2d.shape == (5, 9, 2)
-
-
-class TestRaySampler_3DPoints:
- def test_dimensions_uniform_sampler(self, device, dtype):
- cameras = create_four_cameras(device, dtype)
- uniform_sampler_four_cameras = UniformRaySampler(1, 1, False, device=device, dtype=dtype)
- points_2d_four_cameras = uniform_sampler_four_cameras.sample_points_2d(cameras.height, cameras.width)
- cameras_28 = cameras_for_ids(cameras, points_2d_four_cameras[28].camera_ids)
- points_3d_28 = cameras_28.unproject(points_2d_four_cameras[28].points_2d, 1)
- cameras_40 = cameras_for_ids(cameras, points_2d_four_cameras[45].camera_ids)
- points_3d_40 = cameras_40.unproject(points_2d_four_cameras[45].points_2d, 1)
- assert points_3d_28.shape == (3, 28, 3)
- assert points_3d_40.shape == (1, 45, 3)
-
- def test_dimensions_ray_params(self, device, dtype):
- cameras = create_four_cameras(device, dtype)
- uniform_sampler_four_cameras = UniformRaySampler(1, 2, False, device=device, dtype=dtype)
- uniform_sampler_four_cameras.calc_ray_params(cameras)
- lengths = sample_lengths(
- uniform_sampler_four_cameras.origins.shape[0], 10, device=device, dtype=dtype, irregular=True
- )
- assert uniform_sampler_four_cameras.origins.shape == (3 * 28 + 45, 3)
- assert uniform_sampler_four_cameras.directions.shape == (3 * 28 + 45, 3)
- assert uniform_sampler_four_cameras.camera_ids.shape == (3 * 28 + 45,)
- assert uniform_sampler_four_cameras.points_2d.shape == (3 * 28 + 45, 2)
- assert lengths.shape == (3 * 28 + 45, 10)
-
- def test_dimensions_sample_ray_points(self, device, dtype):
- cameras = create_four_cameras(device, dtype)
- uniform_sampler_four_cameras = UniformRaySampler(1, 2, False, device, dtype=dtype)
- uniform_sampler_four_cameras.calc_ray_params(cameras)
- lengths = sample_lengths(
- uniform_sampler_four_cameras.origins.shape[0], 10, device=device, dtype=dtype, irregular=True
- )
- points_3d = sample_ray_points(
- uniform_sampler_four_cameras.origins, uniform_sampler_four_cameras.directions, lengths
- )
- assert points_3d.shape == (3 * 28 + 45, 10, 3)
-
- def test_t_vals(self, device, dtype):
- cameras = create_four_cameras(device, dtype)
- uniform_sampler_four_cameras = UniformRaySampler(2, 3.0, False, device=device, dtype=dtype)
- uniform_sampler_four_cameras.calc_ray_params(cameras)
- lengths = sample_lengths(
- uniform_sampler_four_cameras.origins.shape[0], 10, device=device, dtype=dtype, irregular=False
- )
- points_3d = sample_ray_points(
- uniform_sampler_four_cameras.origins, uniform_sampler_four_cameras.directions, lengths
- )
- t_vals = calc_ray_t_vals(points_3d)
- assert t_vals.shape == (3 * 28 + 45, 10)
- assert_close(t_vals[22, -1].item(), 1.0) # Testing middle ray
-
- def test_dimensions_ray_params_in_ndc(self, device, dtype):
- cameras = create_four_cameras(device, dtype)
- uniform_sampler_four_cameras = UniformRaySampler(2, 3.5, False, device=device, dtype=dtype)
- uniform_sampler_four_cameras.calc_ray_params(cameras)
- origins_ndc, directions_ndc = uniform_sampler_four_cameras.transform_ray_params_world_to_ndc(cameras)
- assert origins_ndc.shape == (3 * 28 + 45, 3)
- assert directions_ndc.shape == (3 * 28 + 45, 3)
diff --git a/tests/nerf/test_renderer.py b/tests/nerf/test_renderer.py
deleted file mode 100755
index 31d256704..000000000
--- a/tests/nerf/test_renderer.py
+++ /dev/null
@@ -1,106 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import math
-
-import torch
-
-from kornia.core import Device, Tensor
-from kornia.nerf.volume_renderer import IrregularRenderer, RegularRenderer
-from kornia.utils._compat import torch_meshgrid
-
-from testing.base import assert_close
-
-
-def _create_regular_point_cloud(
- height: int, width: int, num_ray_points: int, device: Device, dtype: torch.dtype
-) -> Tensor:
- x = torch.linspace(0, width, steps=width, device=device, dtype=dtype)
- y = torch.linspace(0, height, steps=height, device=device, dtype=dtype)
- xy = torch_meshgrid([y, x], indexing="ij")
- z = torch.linspace(1, 11, steps=num_ray_points, device=device, dtype=dtype)
- points3d = torch.zeros(height, width, num_ray_points, 3, device=device, dtype=dtype)
- points3d[..., 0] = xy[0].unsqueeze(-1)
- points3d[..., 1] = xy[1].unsqueeze(-1)
- points3d[..., 2] = z
- return points3d
-
-
-class TestRenderer:
- def test_dimensions(self, device, dtype):
- height = 5
- width = 4
- num_ray_points = 7
- rgbs = torch.rand((height, width, num_ray_points, 3), dtype=dtype, device=device)
- densities = torch.rand((height, width, num_ray_points, 1), dtype=dtype, device=device)
-
- points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
-
- irreg_renderer = IrregularRenderer()
- rgb_rendered = irreg_renderer(rgbs, densities, points3d)
- assert rgb_rendered.shape == (height, width, 3)
-
- def test_only_red(self, device, dtype):
- height = 5
- width = 4
- num_ray_points = 7
- rgbs = torch.zeros((height, width, num_ray_points, 3), dtype=dtype, device=device)
- rgbs[..., 0] = 1
- densities = torch.rand((height, width, num_ray_points, 1), dtype=dtype, device=device)
-
- points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
-
- irreg_renderer = IrregularRenderer()
- rgbs_rendered = irreg_renderer(rgbs, densities, points3d)
- only_reds = torch.zeros_like(rgbs_rendered, dtype=dtype, device=device)
- only_reds[..., 0] = 1.0
- assert_close(rgbs_rendered, only_reds)
-
- def test_shell(self, device, dtype):
- height = 5
- width = 4
- num_ray_points = 11
- rgbs = torch.rand((height, width, num_ray_points, 3), dtype=dtype, device=device)
- densities = torch.zeros((height, width, num_ray_points, 1), dtype=dtype, device=device)
- densities[..., 0, :] = 1
-
- points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
-
- regular_renderer = RegularRenderer()
- rgbs_rendered = regular_renderer(rgbs, densities, points3d)
-
- weight = 1 - math.exp(-1.0)
- assert_close(rgbs_rendered, weight * rgbs[..., 0, :])
-
- def test_regular_vs_irregular(self, device, dtype):
- height = 5
- width = 4
- num_ray_points = 11
- rgbs = torch.rand((height, width, num_ray_points, 3), dtype=dtype, device=device)
- densities = torch.zeros((height, width, num_ray_points, 1), dtype=dtype, device=device)
- densities[..., 0, :] = 10
-
- points3d = _create_regular_point_cloud(height, width, num_ray_points, device=device, dtype=dtype)
-
- irreg_renderer = IrregularRenderer()
- irreg_rgb_rendered = irreg_renderer(rgbs, densities, points3d)
-
- regular_renderer = RegularRenderer()
- regular_rgbs_rendered = regular_renderer(rgbs, densities, points3d)
-
- assert irreg_rgb_rendered.shape == regular_rgbs_rendered.shape
- assert_close(irreg_rgb_rendered, regular_rgbs_rendered)
diff --git a/tests/x/__init__.py b/tests/x/__init__.py
deleted file mode 100644
index 0a4a2653f..000000000
--- a/tests/x/__init__.py
+++ /dev/null
@@ -1,27 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import sys
-
-import pytest
-
-from kornia.utils._compat import torch_version
-
-# NOTE: remove once we deprecate pytorch 1.10.2 for macos
-
-if sys.platform == "darwin" and torch_version() == "1.10.2":
- pytest.skip("Accelerate is broken for macos and pytorch 1.10.2", allow_module_level=True)
diff --git a/tests/x/test_detection.py b/tests/x/test_detection.py
deleted file mode 100644
index 308c86f0b..000000000
--- a/tests/x/test_detection.py
+++ /dev/null
@@ -1,115 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import sys
-
-import pytest
-import torch
-from torch import nn
-from torch.utils.data import Dataset
-
-from kornia.x import Configuration, ObjectDetectionTrainer
-from kornia.x.trainer import Accelerator
-
-
-class DummyDatasetDetection(Dataset):
- def __len__(self):
- return 10
-
- def __getitem__(self, index):
- return torch.ones(3, 32, 32), torch.tensor([10.0, 10.0, 15.0, 15.0])
-
-
-class DummyModel(nn.Module):
- def __init__(self):
- super().__init__()
- self.model = nn.Sequential(nn.Conv2d(3, 1, kernel_size=16, stride=16), nn.Flatten())
-
- def forward(self, x, y=None):
- return self.model(x)
-
-
-def model():
- return DummyModel()
-
-
-def dataloader():
- dataset = DummyDatasetDetection()
- return torch.utils.data.DataLoader(dataset, batch_size=1)
-
-
-def criterion():
- return nn.MSELoss()
-
-
-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 TestObjectDetectionTrainer:
- @pytest.mark.slow
- @pytest.mark.skipif(
- torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
- )
- @pytest.mark.parametrize("loss_computed_by_model", [True, False])
- def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration, loss_computed_by_model):
- trainer = ObjectDetectionTrainer(
- model,
- dataloader,
- dataloader,
- criterion,
- optimizer,
- scheduler,
- configuration,
- num_classes=3,
- loss_computed_by_model=loss_computed_by_model,
- )
- trainer.fit()
-
- @pytest.mark.skipif(
- torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
- )
- @pytest.mark.xfail(sys.platform == "darwin", reason="Sometimes CI can fail with MPS backend out of memory")
- def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
- with pytest.raises(ValueError):
- ObjectDetectionTrainer(
- model,
- dataloader,
- dataloader,
- criterion,
- optimizer,
- scheduler,
- configuration,
- num_classes=3,
- callbacks={"frodo": None},
- )
diff --git a/tests/x/test_image_classification.py b/tests/x/test_image_classification.py
deleted file mode 100644
index 23df21fd5..000000000
--- a/tests/x/test_image_classification.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import sys
-
-import pytest
-import torch
-from torch import nn
-from torch.utils.data import Dataset
-
-from kornia.contrib import ClassificationHead, VisionTransformer
-from kornia.x import Configuration, ImageClassifierTrainer
-from kornia.x.trainer import Accelerator
-
-
-class DummyDatasetClassification(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 dataloader():
- dataset = DummyDatasetClassification()
- 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:
- @pytest.mark.slow
- @pytest.mark.skipif(
- torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
- )
- def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):
- trainer = ImageClassifierTrainer(model, dataloader, dataloader, criterion, optimizer, scheduler, configuration)
- trainer.fit()
-
- @pytest.mark.skipif(
- torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
- )
- @pytest.mark.xfail(sys.platform == "darwin", reason="Sometimes CI can fail with MPS backend out of memory")
- 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}
- )
diff --git a/tests/x/test_segmentation.py b/tests/x/test_segmentation.py
deleted file mode 100644
index 259d83a84..000000000
--- a/tests/x/test_segmentation.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import sys
-
-import pytest
-import torch
-from torch import nn
-from torch.utils.data import Dataset
-
-from kornia.x import Configuration, SemanticSegmentationTrainer
-from kornia.x.trainer import Accelerator
-
-
-class DummyDatasetSegmentation(Dataset):
- def __len__(self):
- return 10
-
- def __getitem__(self, index):
- return torch.ones(3, 32, 32), torch.ones(32, 32).long()
-
-
-def model():
- return nn.Conv2d(3, 10, kernel_size=1)
-
-
-def dataloader():
- dataset = DummyDatasetSegmentation()
- 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 TestsemanticSegmentationTrainer:
- @pytest.mark.slow
- @pytest.mark.skipif(
- torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
- )
- def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):
- trainer = SemanticSegmentationTrainer(
- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration
- )
- trainer.fit()
-
- @pytest.mark.skipif(
- torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
- )
- @pytest.mark.xfail(sys.platform == "darwin", reason="Sometimes CI can fail with MPS backend out of memory")
- def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
- with pytest.raises(ValueError):
- SemanticSegmentationTrainer(
- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={"frodo": None}
- )
diff --git a/tests/x/test_x.py b/tests/x/test_x.py
deleted file mode 100644
index 5e7a73aa8..000000000
--- a/tests/x/test_x.py
+++ /dev/null
@@ -1,192 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import pytest
-from torch import nn
-
-from kornia.metrics import AverageMeter
-from kornia.x import EarlyStopping, ModelCheckpoint
-from kornia.x.utils import TrainerState
-
-
-def model():
- return nn.Conv2d(3, 10, kernel_size=1)
-
-
-class TestModelCheckpoint:
- def test_smoke(self, tmp_path, model):
- cb = ModelCheckpoint(tmp_path, "test_monitor", max_mode=True)
- assert cb is not None
-
- metric = {"test_monitor": AverageMeter()}
- metric["test_monitor"]._avg = 1.0
-
- cb(model, epoch=0, valid_metric=metric)
- assert cb.best_metric == 1.0
- assert (tmp_path / "model_epoch=0_metricValue=1.0.pt").is_file()
-
- def test_custom_filename(self, tmp_path, model):
- cb = ModelCheckpoint(tmp_path, "test_monitor", filename_fcn=lambda x, _: "model.pt", max_mode=True)
- assert cb is not None
-
- metric = {"test_monitor": AverageMeter()}
- metric["test_monitor"]._avg = 1.0
-
- cb(model, epoch=0, valid_metric=metric)
- assert cb.best_metric == 1.0
- assert (tmp_path / "model.pt").is_file()
-
-
-def test_callback_earlystopping_max_mode(model):
- cb = EarlyStopping("test_monitor", patience=2, max_mode=True)
- 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 == 2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = 1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TRAINING
- assert cb.best_score == 2
- assert cb.counter == 1
-
- metric["test_monitor"]._avg = 1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TERMINATE
- assert cb.best_score == 2
- assert cb.counter == 2
-
-
-def test_callback_earlystopping_min_mode(model):
- cb = EarlyStopping("test_monitor", patience=2, max_mode=False)
- 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 == -2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = -1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TRAINING
- assert cb.best_score == -2
- assert cb.counter == 1
-
- metric["test_monitor"]._avg = -1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TERMINATE
- assert cb.best_score == -2
- assert cb.counter == 2
-
-
-def test_callback_earlystopping_max_mode_with_delta(model):
- cb = EarlyStopping("test_monitor", patience=1, max_mode=True, min_delta=0.15)
- 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 == 2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = 1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TRAINING
- assert cb.best_score == 2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = 1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TRAINING
- assert cb.best_score == 2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = 1.7
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TERMINATE
- assert cb.best_score == 2
- assert cb.counter == 1
-
-
-def test_callback_earlystopping_with_delta(model):
- cb = EarlyStopping("test_monitor", patience=1, max_mode=False, min_delta=0.15)
- 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 == -2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = -1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TRAINING
- assert cb.best_score == -2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = -1.9
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TRAINING
- assert cb.best_score == -2
- assert cb.counter == 0
-
- metric["test_monitor"]._avg = -1.7
- state = cb(model, epoch=0, valid_metric=metric)
- assert state == TrainerState.TERMINATE
- assert cb.best_score == -2
- assert cb.counter == 1
diff --git a/uv.lock b/uv.lock
index 55d69a588..4a0f0f34b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -13,24 +13,6 @@ resolution-markers = [
"(python_full_version < '3.12' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version < '3.12' and sys_platform != 'darwin' and sys_platform != 'linux')",
]
-[[package]]
-name = "accelerate"
-version = "1.12.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "huggingface-hub" },
- { name = "numpy" },
- { name = "packaging" },
- { name = "psutil" },
- { name = "pyyaml" },
- { name = "safetensors" },
- { name = "torch" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/4a/8e/ac2a9566747a93f8be36ee08532eb0160558b07630a081a6056a9f89bf1d/accelerate-1.12.0.tar.gz", hash = "sha256:70988c352feb481887077d2ab845125024b2a137a5090d6d7a32b57d03a45df6", size = 398399, upload-time = "2025-11-21T11:27:46.973Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/9f/d2/c581486aa6c4fbd7394c23c47b83fa1a919d34194e16944241daf9e762dd/accelerate-1.12.0-py3-none-any.whl", hash = "sha256:3e2091cd341423207e2f084a6654b1efcd250dc326f2a37d6dde446e07cabb11", size = 380935, upload-time = "2025-11-21T11:27:44.522Z" },
-]
-
[[package]]
name = "accessible-pygments"
version = "0.0.5"
@@ -960,7 +942,6 @@ dependencies = [
[package.optional-dependencies]
dev = [
- { name = "accelerate" },
{ name = "coverage" },
{ name = "diffusers" },
{ name = "ivy" },
@@ -975,6 +956,7 @@ dev = [
{ name = "pytest-timeout" },
{ name = "requests" },
{ name = "ruff" },
+ { name = "setuptools" },
{ name = "transformers" },
]
docs = [
@@ -996,15 +978,9 @@ docs = [
{ name = "sphinxcontrib-gtagjs" },
{ name = "sphinxcontrib-youtube" },
]
-x = [
- { name = "accelerate" },
- { name = "onnxruntime-gpu", marker = "sys_platform != 'darwin'" },
-]
[package.metadata]
requires-dist = [
- { name = "accelerate", marker = "extra == 'dev'" },
- { name = "accelerate", marker = "extra == 'x'" },
{ name = "coverage", marker = "extra == 'dev'" },
{ name = "diffusers", marker = "extra == 'dev'" },
{ name = "furo", marker = "extra == 'docs'" },
@@ -1018,7 +994,6 @@ requires-dist = [
{ name = "onnx", marker = "extra == 'docs'" },
{ name = "onnxruntime", marker = "extra == 'dev'" },
{ name = "onnxruntime", marker = "extra == 'docs'" },
- { name = "onnxruntime-gpu", marker = "sys_platform != 'darwin' and extra == 'x'", specifier = ">=1.16" },
{ name = "onnxscript", marker = "extra == 'dev'" },
{ name = "opencv-python", marker = "extra == 'docs'" },
{ name = "packaging" },
@@ -1030,6 +1005,7 @@ requires-dist = [
{ name = "pyyaml", marker = "extra == 'docs'", specifier = ">=5.1" },
{ name = "requests", marker = "extra == 'dev'" },
{ name = "ruff", marker = "extra == 'dev'" },
+ { name = "setuptools", marker = "extra == 'dev'" },
{ name = "sphinx", marker = "extra == 'docs'" },
{ name = "sphinx-autodoc-defaultargs", marker = "extra == 'docs'" },
{ name = "sphinx-autodoc-typehints", marker = "extra == 'docs'" },
@@ -1042,7 +1018,7 @@ requires-dist = [
{ name = "torch", specifier = ">=2.0.0" },
{ name = "transformers", marker = "extra == 'dev'", specifier = "<4.57" },
]
-provides-extras = ["dev", "docs", "x"]
+provides-extras = ["dev", "docs"]
[[package]]
name = "kornia-moons"
@@ -1603,28 +1579,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b6/ca/862b1e7a639460f0ca25fd5b6135fb42cf9deea86d398a92e44dfda2279d/onnxruntime-1.23.2-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2b9233c4947907fd1818d0e581c049c41ccc39b2856cc942ff6d26317cee145", size = 17394184, upload-time = "2025-10-22T03:47:08.127Z" },
]
-[[package]]
-name = "onnxruntime-gpu"
-version = "1.23.2"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "coloredlogs", marker = "sys_platform != 'darwin'" },
- { name = "flatbuffers", marker = "sys_platform != 'darwin'" },
- { name = "numpy", marker = "sys_platform != 'darwin'" },
- { name = "packaging", marker = "sys_platform != 'darwin'" },
- { name = "protobuf", marker = "sys_platform != 'darwin'" },
- { name = "sympy", marker = "sys_platform != 'darwin'" },
-]
-wheels = [
- { url = "https://files.pythonhosted.org/packages/43/a4/e3d7fbe32b44e814ae24ed642f05fac5d96d120efd82db7a7cac936e85a9/onnxruntime_gpu-1.23.2-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d76d1ac7a479ecc3ac54482eea4ba3b10d68e888a0f8b5f420f0bdf82c5eec59", size = 300525715, upload-time = "2025-10-22T16:56:19.928Z" },
- { url = "https://files.pythonhosted.org/packages/a9/5c/dba7c009e73dcce02e7f714574345b5e607c5c75510eb8d7bef682b45e5d/onnxruntime_gpu-1.23.2-cp311-cp311-win_amd64.whl", hash = "sha256:054282614c2fc9a4a27d74242afbae706a410f1f63cc35bc72f99709029a5ba4", size = 244506823, upload-time = "2025-10-22T16:55:09.526Z" },
- { url = "https://files.pythonhosted.org/packages/6c/d9/b7140a4f1615195938c7e358c0804bb84271f0d6886b5cbf105c6cb58aae/onnxruntime_gpu-1.23.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f2d1f720685d729b5258ec1b36dee1de381b8898189908c98cbeecdb2f2b5c2", size = 300509596, upload-time = "2025-10-22T16:56:31.728Z" },
- { url = "https://files.pythonhosted.org/packages/87/da/2685c79e5ea587beddebe083601fead0bdf3620bc2f92d18756e7de8a636/onnxruntime_gpu-1.23.2-cp312-cp312-win_amd64.whl", hash = "sha256:fe925a84b00e291e0ad3fac29bfd8f8e06112abc760cdc82cb711b4f3935bd95", size = 244508327, upload-time = "2025-10-22T16:55:19.397Z" },
- { url = "https://files.pythonhosted.org/packages/03/05/40d561636e4114b54aa06d2371bfbca2d03e12cfdf5d4b85814802f18a75/onnxruntime_gpu-1.23.2-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1e8f75af5da07329d0c3a5006087f4051d8abd133b4be7c9bae8cdab7bea4c26", size = 300515567, upload-time = "2025-10-22T16:56:43.794Z" },
- { url = "https://files.pythonhosted.org/packages/b6/3b/418300438063d403384c79eaef1cb13c97627042f2247b35a887276a355a/onnxruntime_gpu-1.23.2-cp313-cp313-win_amd64.whl", hash = "sha256:7f1b3f49e5e126b99e23ec86b4203db41c2a911f6165f7624f2bc8267aaca767", size = 244507535, upload-time = "2025-10-22T16:55:28.532Z" },
- { url = "https://files.pythonhosted.org/packages/b8/dc/80b145e3134d7eba31309b3299a2836e37c76e4c419a261ad9796f8f8d65/onnxruntime_gpu-1.23.2-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:20959cd4ae358aab6579ab9123284a7b1498f7d51ec291d429a5edc26511306f", size = 300525759, upload-time = "2025-10-22T16:56:56.925Z" },
-]
-
[[package]]
name = "onnxscript"
version = "0.5.7"