π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Make torchgeometry jit compatible.
Onur Kaplan81cda9eb08bb
diff --git a/test/test_jit_tracing.py b/test/test_jit_tracing.pynew file mode 100644index 000000000..063408f33--- /dev/null+++ b/test/test_jit_tracing.py@@ -0,0 +1,102 @@+import pytest+from common import TEST_DEVICES++import torch+import torchgeometry as tgm+import torch.nn as nn+import torchvision.models as models+++class WarpPerspective(nn.Module):++ def __init__(self, output_size):+ super(WarpPerspective, self).__init__()++ self.output_height, self.output_width = output_size++ def forward(self, x, M):++ x = tgm.warp_perspective(x, M,+ dsize=(self.output_height, self.output_width))++ return x+++class WarpAffine(nn.Module):++ def __init__(self, output_size):+ super(WarpAffine, self).__init__()++ self.output_height, self.output_width = output_size++ def forward(self, x, M):++ x = tgm.warp_affine(x, M,+ dsize=(self.output_height, self.output_width))++ return x+++class LocalizationNetwork(nn.Module):++ def __init__(self, output_size, pretrained=True, affine=True):+ super(LocalizationNetwork, self).__init__()++ self.cnn = models.__dict__['alexnet'](pretrained=pretrained)+ self.cnn = nn.Sequential(*list(self.cnn.children())[0])+ self.cnn = nn.Sequential(*list(self.cnn.children())[:-1])++ self.affine = affine++ if self.affine:+ self.linear = nn.Linear(256 * 3 * 3, 6)+ self.warper = WarpAffine(output_size)+ else:+ self.linear = nn.Linear(256 * 3 * 3, 9)+ self.warper = WarpPerspective(output_size)++ #self.linear.weight.data.zero_()+ #self.linear.bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0, 0, 0, 1], dtype=torch.float))+ #self.linear.bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))++ def forward(self, x):+ bs = x.size(0)++ inp_height = x.size(2)+ inp_width = x.size(3)++ x_down = nn.functional.interpolate(x, size=(64, 64), mode='bilinear')++ M = self.linear(self.cnn(x_down).view(bs, -1))+ if self.affine:+ M = M.view(-1, 2, 3)+ else:+ M = M.view(-1, 3, 3)++ out = self.warper(x, M)++ return (out, M)++[email protected]("device_type", TEST_DEVICES)[email protected]("affine", [True, False])+def test_jit_tracing(device_type, affine):++ net = LocalizationNetwork((128, 128), pretrained=False, affine=affine)+ net.eval()++ net = net.to(torch.device(device_type))++ dummy_input = torch.randn(1, 3, 128, 128)+ dummy_input = dummy_input.to(torch.device(device_type))++ output = net(dummy_input)++ traced_net = torch.jit.trace(net, dummy_input)+ traced_output = traced_net(dummy_input)++ out_comp1 = float(torch.mean((output[0] == traced_output[0]).float()))+ out_comp2 = float(torch.mean((output[1] == traced_output[1]).float()))++ assert(out_comp1 == 1.0)+ assert(out_comp2 == 1.0)diff --git a/torchgeometry/conversions.py b/torchgeometry/conversions.pyindex 11d9bd89a..688b4642f 100644--- a/torchgeometry/conversions.py+++ b/torchgeometry/conversions.py@@ -116,8 +116,15 @@ def convert_points_to_homogeneous(points):raise ValueError("Input must be at least a 2D tensor. Got {}".format(points.shape))+ if torch.is_tensor(points.shape[-1]):+ last_dim_bit_length = torch.floor(torch.log2(points.shape[-1].float())) + 1+ last_dim_bit_length = last_dim_bit_length.long()+ else:+ last_dim_bit_length = points.shape[-1].bit_length()+# create shape for ones tensor: Nx(...)xD-1- new_shape = points.shape[:-1] + (points.shape[-1].bit_length() - 1,)+ # new_shape = points.shape[:-1] + (int(points.shape[-1]).bit_length() - 1,)+ new_shape = points.shape[:-1] + (last_dim_bit_length - 1,)ones = torch.ones(new_shape, dtype=points.dtype)return torch.cat([points, ones.to(points.device)], dim=-1)diff --git a/torchgeometry/homography_warper.py b/torchgeometry/homography_warper.pyindex 8a3d73676..37abad2ee 100644--- a/torchgeometry/homography_warper.py+++ b/torchgeometry/homography_warper.py@@ -26,10 +26,16 @@ class HomographyWarper(nn.Module):height (int): The height of the image to warp.points (Tensor): Tensor[3, N] of homogeneous points in normalized imagespace [-1, 1] to sample. Optional parameter.+ padding_mode (string): Either 'zeros' to replace out of bounds with+ zeros or 'border' to choose the closest+ border data."""- def __init__(self, height, width, points=None):+ def __init__(self, height, width, points=None, padding_mode='zeros'):super(HomographyWarper, self).__init__()++ self.padding_mode = padding_mode+if points is not None:assert points.size(0) == 3, "Points must be 3xN"self.width = points.size(1)@@ -61,7 +67,7 @@ class HomographyWarper(nn.Module):def random_warp(self, patch, dist):return self(patch, random_homography(dist))- def crop_and_warp(self, H, image, roi, padding_mode='zeros'):+ def crop_and_warp(self, H, image, roi):grid = self.warp_grid(H)assert len(image.shape) == 4, image.shape@@ -88,18 +94,15 @@ class HomographyWarper(nn.Module):b = b.cuda()grid = grid * a + breturn F.grid_sample(- image, grid, mode='bilinear', padding_mode=padding_mode)+ image, grid, mode='bilinear', padding_mode=self.padding_mode)- def forward(self, patch, dst_homo_src, padding_mode='zeros'):+ def forward(self, patch, dst_homo_src):"""Warps an image or tensor from source into reference frame.Args:patch (Tensor): The image or tensor to warp. Should be from source.dst_homo_src (Tensor): The homography or stack of homographiesfrom source to destination.- padding_mode (string): Either 'zeros' to replace out of bounds with- zeros or 'border' to choose the closest- border data.Return:Tensor: Patch sampled at locations from source to destination.@@ -120,7 +123,7 @@ class HomographyWarper(nn.Module):.format(patch.device, dst_homo_src.device))return torch.nn.functional.grid_sample(patch, self.warp_grid(dst_homo_src), mode='bilinear',- padding_mode=padding_mode)+ padding_mode=self.padding_mode)# functional api@@ -156,5 +159,5 @@ def homography_warp(patch, dst_H_src, dsize, points=None,>>> output = tgm.homography_warp(input, homography, (32, 32)) # NxCxHxW"""height, width = dsize- warper = HomographyWarper(height, width, points)- return warper(patch, dst_H_src, padding_mode)+ warper = HomographyWarper(height, width, points, padding_mode)+ return warper(patch, dst_H_src)diff --git a/torchgeometry/imgwarp.py b/torchgeometry/imgwarp.pyindex d76dfd8ff..4fd248a1d 100644--- a/torchgeometry/imgwarp.py+++ b/torchgeometry/imgwarp.py@@ -1,4 +1,5 @@import torch+import torch.nn.functional as Ffrom .homography_warper import homography_warpfrom .conversions import deg2rad@@ -14,11 +15,19 @@ __all__ = [def normal_transform_pixel(height, width):- return torch.tensor([[- [2. / (width - 1), 0., -1.],- [0., 2. / (height - 1), -1.],- [0., 0., 1.]]- ]) # 1x3x3++ tr_mat = torch.Tensor([+ [1.0, 0.0, -1.0],+ [0.0, 1.0, -1.0],+ [0.0, 0.0, 1.0]+ ]) # 1x3x3++ tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / (width - 1.0)+ tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / (height - 1.0)++ tr_mat = tr_mat.unsqueeze(0)++ return tr_matdef dst_norm_to_dst_norm(dst_pix_trans_src_pix, dsize_src, dsize_dst):@@ -135,9 +144,9 @@ def warp_affine(src, M, dsize, flags='bilinear', border_mode=None,raise ValueError("Input M must be a Bx2x3 tensor. Got {}".format(src.shape))# we generate a 3x3 transformation matrix from 2x3 affine- M_3x3 = torch.eye(3, device=src.device, dtype=src.dtype)- M_3x3 = torch.unsqueeze(M_3x3, dim=0).repeat(src.shape[0], 1, 1)- M_3x3[..., :2, :3] = M+ M_3x3 = F.pad(M, (0, 0, 0, 1, 0, 0))+ M_3x3[:, 2, 2] += 1.0+# launches the warperreturn transform_warp_impl(src, M_3x3, (src.shape[-2:]), dsize)