|
| 1 | +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. |
| 2 | + |
| 3 | + |
| 4 | +import unittest |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import torch |
| 8 | +from common_testing import TestCaseMixin |
| 9 | +from pytorch3d.transforms import acos_linear_extrapolation |
| 10 | + |
| 11 | + |
| 12 | +class TestAcosLinearExtrapolation(TestCaseMixin, unittest.TestCase): |
| 13 | + def setUp(self) -> None: |
| 14 | + super().setUp() |
| 15 | + torch.manual_seed(42) |
| 16 | + np.random.seed(42) |
| 17 | + |
| 18 | + @staticmethod |
| 19 | + def init_acos_boundary_values(batch_size: int = 10000): |
| 20 | + """ |
| 21 | + Initialize a tensor containing values close to the bounds of the |
| 22 | + domain of `acos`, i.e. close to -1 or 1; and random values between (-1, 1). |
| 23 | + """ |
| 24 | + device = torch.device("cuda:0") |
| 25 | + # one quarter are random values between -1 and 1 |
| 26 | + x_rand = 2 * torch.rand(batch_size // 4, dtype=torch.float32, device=device) - 1 |
| 27 | + x = [x_rand] |
| 28 | + for bound in [-1, 1]: |
| 29 | + for above_bound in [True, False]: |
| 30 | + for noise_std in [1e-4, 1e-2]: |
| 31 | + n_generate = (batch_size - batch_size // 4) // 8 |
| 32 | + x_add = ( |
| 33 | + bound |
| 34 | + + (2 * float(above_bound) - 1) |
| 35 | + * torch.randn( |
| 36 | + n_generate, device=device, dtype=torch.float32 |
| 37 | + ).abs() |
| 38 | + * noise_std |
| 39 | + ) |
| 40 | + x.append(x_add) |
| 41 | + x = torch.cat(x) |
| 42 | + return x |
| 43 | + |
| 44 | + @staticmethod |
| 45 | + def acos_linear_extrapolation(batch_size: int): |
| 46 | + x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size) |
| 47 | + torch.cuda.synchronize() |
| 48 | + |
| 49 | + def compute_acos(): |
| 50 | + acos_linear_extrapolation(x) |
| 51 | + torch.cuda.synchronize() |
| 52 | + |
| 53 | + return compute_acos |
| 54 | + |
| 55 | + def _test_acos_outside_bounds(self, x, y, dydx, bound): |
| 56 | + """ |
| 57 | + Check that `acos_linear_extrapolation` yields points on a line with correct |
| 58 | + slope, and that the function is continuous around `bound`. |
| 59 | + """ |
| 60 | + bound_t = torch.tensor(bound, device=x.device, dtype=x.dtype) |
| 61 | + # fit a line: slope * x + bias = y |
| 62 | + x_1 = torch.stack([x, torch.ones_like(x)], dim=-1) |
| 63 | + solution = torch.linalg.lstsq(x_1, y[:, None]).solution |
| 64 | + slope, bias = solution.view(-1)[:2] |
| 65 | + desired_slope = (-1.0) / torch.sqrt(1.0 - bound_t ** 2) |
| 66 | + # test that the desired slope is the same as the fitted one |
| 67 | + self.assertClose(desired_slope.view(1), slope.view(1), atol=1e-2) |
| 68 | + # test that the autograd's slope is the same as the desired one |
| 69 | + self.assertClose(desired_slope.expand_as(dydx), dydx, atol=1e-2) |
| 70 | + # test that the value of the fitted line at x=bound equals |
| 71 | + # arccos(x), i.e. the function is continuous around the bound |
| 72 | + y_bound_lin = (slope * bound_t + bias).view(1) |
| 73 | + y_bound_acos = bound_t.acos().view(1) |
| 74 | + self.assertClose(y_bound_lin, y_bound_acos, atol=1e-2) |
| 75 | + |
| 76 | + def _one_acos_test(self, x: torch.Tensor, lower_bound: float, upper_bound: float): |
| 77 | + """ |
| 78 | + Test that `acos_linear_extrapolation` returns correct values for |
| 79 | + `x` between/above/below `lower_bound`/`upper_bound`. |
| 80 | + """ |
| 81 | + x.requires_grad = True |
| 82 | + x.grad = None |
| 83 | + y = acos_linear_extrapolation(x, [lower_bound, upper_bound]) |
| 84 | + # compute the gradient of the acos w.r.t. x |
| 85 | + y.backward(torch.ones_like(y)) |
| 86 | + dacos_dx = x.grad |
| 87 | + x_lower = x <= lower_bound |
| 88 | + x_upper = x >= upper_bound |
| 89 | + x_mid = (~x_lower) & (~x_upper) |
| 90 | + # test that between bounds, the function returns plain acos |
| 91 | + self.assertClose(x[x_mid].acos(), y[x_mid]) |
| 92 | + # test that outside the bounds, the function is linear with the right |
| 93 | + # slope and continuous around the bound |
| 94 | + self._test_acos_outside_bounds( |
| 95 | + x[x_upper], y[x_upper], dacos_dx[x_upper], upper_bound |
| 96 | + ) |
| 97 | + self._test_acos_outside_bounds( |
| 98 | + x[x_lower], y[x_lower], dacos_dx[x_lower], lower_bound |
| 99 | + ) |
| 100 | + if abs(upper_bound + lower_bound) <= 1e-5: # lower_bound==-upper_bound |
| 101 | + # check that passing bounds=upper_bound gives the same |
| 102 | + # resut as bounds=[lower_bound, upper_bound] |
| 103 | + y_one_bound = acos_linear_extrapolation(x, upper_bound) |
| 104 | + self.assertClose(y_one_bound, y) |
| 105 | + |
| 106 | + def test_acos(self, batch_size: int = 10000): |
| 107 | + """ |
| 108 | + Tests whether the function returns correct outputs |
| 109 | + inside/outside the bounds. |
| 110 | + """ |
| 111 | + x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size) |
| 112 | + bounds = 1 - 10.0 ** torch.linspace(-1, -5, 5) |
| 113 | + for lower_bound in -bounds: |
| 114 | + for upper_bound in bounds: |
| 115 | + if upper_bound < lower_bound: |
| 116 | + continue |
| 117 | + self._one_acos_test(x, float(lower_bound), float(upper_bound)) |
| 118 | + |
| 119 | + def test_finite_gradient(self, batch_size: int = 10000): |
| 120 | + """ |
| 121 | + Tests whether gradients stay finite close to the bounds. |
| 122 | + """ |
| 123 | + x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size) |
| 124 | + x.requires_grad = True |
| 125 | + bounds = 1 - 10.0 ** torch.linspace(-1, -5, 5) |
| 126 | + for lower_bound in -bounds: |
| 127 | + for upper_bound in bounds: |
| 128 | + if upper_bound < lower_bound: |
| 129 | + continue |
| 130 | + x.grad = None |
| 131 | + y = acos_linear_extrapolation( |
| 132 | + x, |
| 133 | + [float(lower_bound), float(upper_bound)], |
| 134 | + ) |
| 135 | + self.assertTrue(torch.isfinite(y).all()) |
| 136 | + loss = y.mean() |
| 137 | + loss.backward() |
| 138 | + self.assertIsNotNone(x.grad) |
| 139 | + self.assertTrue(torch.isfinite(x.grad).all()) |
0 commit comments