π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Added Batched forward function (#1058)
Dmytro Mishkina4367b154ec0
diff --git a/docs/source/utils.rst b/docs/source/utils.rstindex cd857d6e5..b9410af05 100644--- a/docs/source/utils.rst+++ b/docs/source/utils.rst@@ -28,3 +28,8 @@ Metrics.. autofunction:: confusion_matrix.. autofunction:: mean_iou.. autofunction:: one_hot++Memory+-------++.. autofunction:: batched_forwarddiff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex a2a4e8dd7..45d1e37e4 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -4,10 +4,12 @@ from .image import tensor_to_image, image_to_tensor, ImageToTensorfrom .pointcloud_io import save_pointcloud_ply, load_pointcloud_plyfrom .draw import draw_rectanglefrom .helpers import _extract_device_dtype+from .memory import batched_forwardfrom kornia.utils.metrics import *__all__ = [+ "batched_forward","one_hot","create_meshgrid","create_meshgrid3d",diff --git a/kornia/utils/memory.py b/kornia/utils/memory.pynew file mode 100644index 000000000..63eb8b37a--- /dev/null+++ b/kornia/utils/memory.py@@ -0,0 +1,48 @@+from typing import Optional, Union+import torch+import kornia+++def batched_forward(+ model: torch.nn.Module, data: torch.Tensor, device: torch.device, batch_size: int = 128, **kwargs+) -> torch.Tensor:+ r'''Convenience function, which allows to run the forward in micro-batches,+ when the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.+ In the end, it transfers the output to the device of the input data tensor.+ E.g. running HardNet on 8000x1x32x32 tensor.+ Args:+ model (torch.nn.Module): Any torch model, which outputs a single tensor as an output+ data (torch.Tensor): Input data of Bx(Any) shape+ device (torch.device): which device should we run on+ batch_size (int): "micro-batch" size. Default: 128+ **kwargs: any other arguments, which accepts model+ Returns:+ torch.Tensor: output of the model++ Example:+ >>> patches = torch.rand(8000, 1, 32, 32)+ >>> sift = kornia.feature.SIFTDescriptor(32)+ >>> desc_batched = batched_forward(sift, patches, torch.device('cpu'), 128)+ >>> desc = sift(patches)+ >>> assert torch.allclose(desc, desc_batched)'''+ model_dev = model.to(device)+ B: int = len(data)+ bs: int = batch_size+ if B > batch_size:+ out_list = []+ n_batches = int(B // bs + 1)+ for batch_idx in range(n_batches):+ st = batch_idx * bs+ if batch_idx == n_batches - 1:+ if (batch_idx + 1) * bs > B:+ end = B+ else:+ end = (batch_idx + 1) * bs+ else:+ end = (batch_idx + 1) * bs+ if st >= end:+ continue+ out_list.append(model_dev(data[st:end].to(device), **kwargs))+ out = torch.cat(out_list, dim=0)+ return out.to(data.device)+ return model(data, **kwargs)diff --git a/test/utils/test_memory.py b/test/utils/test_memory.pynew file mode 100644index 000000000..35d399ad4--- /dev/null+++ b/test/utils/test_memory.py@@ -0,0 +1,34 @@+import pytest+import torch++import kornia as kornia+import kornia.testing as utils++from torch.autograd import gradcheck+++class TestBatchedForward:+ def test_runbatch(self, device):+ patches = torch.rand(34, 1, 32, 32)+ sift = kornia.feature.SIFTDescriptor(32)+ desc_batched = kornia.utils.memory.batched_forward(sift, patches, device, 32)+ desc = sift(patches)+ assert torch.allclose(desc, desc_batched)++ def test_runone(self, device):+ patches = torch.rand(16, 1, 32, 32)+ sift = kornia.feature.SIFTDescriptor(32)+ desc_batched = kornia.utils.memory.batched_forward(sift, patches, device, 32)+ desc = sift(patches)+ assert torch.allclose(desc, desc_batched)++ def test_gradcheck(self, device):+ batch_size, channels, height, width = 3, 2, 5, 4+ img = torch.rand(batch_size, channels, height, width, device=device)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(+ kornia.utils.memory.batched_forward,+ (kornia.feature.BlobHessian(), img, device, 2),+ raise_exception=True,+ nondet_tol=1e-4,+ )