test_affine_grid_function.py 5.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

15
import paddle
16
import numpy as np
17
from paddle import fluid
18 19 20 21 22 23
import paddle.fluid.dygraph as dg
import paddle.nn.functional as F
import unittest


class AffineGridTestCase(unittest.TestCase):
24 25 26 27 28 29 30 31 32 33
    def __init__(
        self,
        methodName='runTest',
        theta_shape=(20, 2, 3),
        output_shape=[20, 2, 5, 7],
        align_corners=True,
        dtype="float32",
        invalid_theta=False,
        variable_output_shape=False,
    ):
34
        super().__init__(methodName)
35 36 37 38 39 40 41 42 43 44 45 46

        self.theta_shape = theta_shape
        self.output_shape = output_shape
        self.align_corners = align_corners
        self.dtype = dtype
        self.invalid_theta = invalid_theta
        self.variable_output_shape = variable_output_shape

    def setUp(self):
        self.theta = np.random.randn(*(self.theta_shape)).astype(self.dtype)

    def fluid_layer(self, place):
47
        paddle.enable_static()
48 49 50 51
        main = fluid.Program()
        start = fluid.Program()
        with fluid.unique_name.guard():
            with fluid.program_guard(main, start):
52 53 54
                theta_var = fluid.data(
                    "input", self.theta_shape, dtype=self.dtype
                )
55 56 57
                y_var = paddle.nn.functional.affine_grid(
                    theta_var, self.output_shape
                )
58 59 60
        feed_dict = {"input": self.theta}
        exe = fluid.Executor(place)
        exe.run(start)
61
        (y_np,) = exe.run(main, feed=feed_dict, fetch_list=[y_var])
62 63 64
        return y_np

    def functional(self, place):
65
        paddle.enable_static()
66 67 68 69
        main = fluid.Program()
        start = fluid.Program()
        with fluid.unique_name.guard():
            with fluid.program_guard(main, start):
70 71 72 73 74 75 76 77
                theta_var = fluid.data(
                    "input", self.theta_shape, dtype=self.dtype
                )
                y_var = F.affine_grid(
                    theta_var,
                    self.output_shape,
                    align_corners=self.align_corners,
                )
78 79 80
        feed_dict = {"input": self.theta}
        exe = fluid.Executor(place)
        exe.run(start)
81
        (y_np,) = exe.run(main, feed=feed_dict, fetch_list=[y_var])
82 83 84
        return y_np

    def paddle_dygraph_layer(self):
85
        paddle.disable_static()
86 87 88 89 90 91 92 93 94 95 96
        theta_var = (
            dg.to_variable(self.theta) if not self.invalid_theta else "invalid"
        )
        output_shape = (
            dg.to_variable(self.output_shape)
            if self.variable_output_shape
            else self.output_shape
        )
        y_var = F.affine_grid(
            theta_var, output_shape, align_corners=self.align_corners
        )
97 98 99 100 101 102 103
        y_np = y_var.numpy()
        return y_np

    def _test_equivalence(self, place):
        place = fluid.CPUPlace()
        result1 = self.fluid_layer(place)
        result2 = self.functional(place)
104
        result3 = self.paddle_dygraph_layer()
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        if self.align_corners:
            np.testing.assert_array_almost_equal(result1, result2)
        np.testing.assert_array_almost_equal(result2, result3)

    def runTest(self):
        place = fluid.CPUPlace()
        self._test_equivalence(place)

        if fluid.core.is_compiled_with_cuda():
            place = fluid.CUDAPlace(0)
            self._test_equivalence(place)


class AffineGridErrorTestCase(AffineGridTestCase):
    def runTest(self):
        place = fluid.CPUPlace()
        with dg.guard(place):
            with self.assertRaises(ValueError):
                self.paddle_dygraph_layer()


def add_cases(suite):
    suite.addTest(AffineGridTestCase(methodName='runTest'))
    suite.addTest(AffineGridTestCase(methodName='runTest', align_corners=True))

    suite.addTest(AffineGridTestCase(methodName='runTest', align_corners=False))
    suite.addTest(
132 133
        AffineGridTestCase(methodName='runTest', variable_output_shape=True)
    )
134 135

    suite.addTest(
136 137 138 139 140 141 142
        AffineGridTestCase(
            methodName='runTest',
            theta_shape=(20, 2, 3),
            output_shape=[20, 1, 7, 7],
            align_corners=True,
        )
    )
143 144 145 146


def add_error_cases(suite):
    suite.addTest(
147 148
        AffineGridErrorTestCase(methodName='runTest', output_shape="not_valid")
    )
149
    suite.addTest(
150 151
        AffineGridErrorTestCase(methodName='runTest', invalid_theta=True)
    )  # to test theta not variable error checking
152 153 154 155 156 157 158 159 160 161 162


def load_tests(loader, standard_tests, pattern):
    suite = unittest.TestSuite()
    add_cases(suite)
    add_error_cases(suite)
    return suite


if __name__ == '__main__':
    unittest.main()