test_convert_operators.py 9.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 16
import unittest

17
import numpy as np
18

19 20 21
import paddle


22 23 24 25 26 27 28 29 30 31 32 33
class CallNotExist(paddle.nn.Layer):
    def __call__(self):
        # call a non-exist API to trigger exception
        return paddle.nn.not_exist_api


class ForwardNotExist(paddle.nn.Layer):
    def forward(self):
        return 0


net = ForwardNotExist()
34
net.forward = "A string so that convert forward will fail"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50


class TestConvertCall(unittest.TestCase):
    def test_class_exception(self):
        @paddle.jit.to_static
        def call_not_exist():
            net = CallNotExist()
            return net()

        with self.assertRaises(AttributeError):
            call_not_exist()

        @paddle.jit.to_static
        def forward_not_exist():
            return net()

51
        with self.assertRaises(AttributeError):
52 53 54
            forward_not_exist()


55 56 57
class TestConvertShapeCompare(unittest.TestCase):
    def test_non_variable(self):
        self.assertEqual(
58 59 60 61 62
            paddle.jit.dy2static.convert_shape_compare(1, "<", 2), True
        )
        self.assertEqual(
            paddle.jit.dy2static.convert_shape_compare(1, "<", 2, "<=", 3), True
        )
63 64
        self.assertEqual(
            paddle.jit.dy2static.convert_shape_compare(1, ">", 2, "<=", 3),
65 66
            False,
        )
67 68 69 70 71 72 73 74

        def error_func():
            """
            Function used to test that comparison doesn't run after first False
            """
            raise ValueError("Used for test")

        self.assertEqual(
75 76 77 78 79
            paddle.jit.dy2static.convert_shape_compare(
                1, ">", 2, "<=", lambda: error_func()
            ),
            False,
        )
80 81

        self.assertEqual(
82 83 84 85 86
            paddle.jit.dy2static.convert_shape_compare(
                1, "<", 2, "in", [1, 2, 3]
            ),
            True,
        )
87
        self.assertEqual(
88 89 90 91 92
            paddle.jit.dy2static.convert_shape_compare(
                1, "<", 2, "not in", [1, 2, 3]
            ),
            False,
        )
93 94
        self.assertEqual(
            paddle.jit.dy2static.convert_shape_compare(1, "<", 2, "is", 3),
95 96
            False,
        )
97
        self.assertEqual(
98 99 100 101 102
            paddle.jit.dy2static.convert_shape_compare(
                1, "<", 2, "is not", [1, 2, 3]
            ),
            True,
        )
103 104

        self.assertEqual(
105 106 107 108 109
            paddle.jit.dy2static.convert_shape_compare(
                [1, 2], "==", [1, 2], "!=", [1, 2, 3]
            ),
            True,
        )
110
        self.assertEqual(
111 112 113 114 115
            paddle.jit.dy2static.convert_shape_compare(
                [1, 2], "!=", [1, 2, 3], "==", [1, 2]
            ),
            False,
        )
116 117 118

    def test_variable(self):
        paddle.enable_static()
119 120 121
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
122 123 124
            x = paddle.static.data(name='x', shape=[3, 2], dtype='float32')
            y = paddle.static.data(name='y', shape=[3, 2], dtype='float32')
            self.assertEqual(
125
                paddle.jit.dy2static.convert_shape_compare(
126 127 128 129
                    x, "is", x, "is not", y
                ),
                True,
            )
130
            self.assertEqual(
131
                paddle.jit.dy2static.convert_shape_compare(
132 133 134 135
                    x, "is not", x, "is not", y
                ),
                False,
            )
136 137
            self.assertEqual(
                paddle.jit.dy2static.convert_shape_compare(x, "is", x, "is", y),
138 139
                False,
            )
140 141 142

            eq_out = paddle.jit.dy2static.convert_shape_compare(x, "==", y)
            not_eq_out = paddle.jit.dy2static.convert_shape_compare(x, "!=", y)
143
            long_eq_out = paddle.jit.dy2static.convert_shape_compare(
144 145 146 147 148 149 150 151
                x, "==", x, "!=", y
            )

            place = (
                paddle.CUDAPlace(0)
                if paddle.is_compiled_with_cuda()
                else paddle.CPUPlace()
            )
152
            exe = paddle.static.Executor(place)
153 154 155 156 157 158 159 160 161 162
            x_y_eq_out = exe.run(
                feed={
                    "x": np.ones([3, 2]).astype(np.float32),
                    "y": np.ones([3, 2]).astype(np.float32),
                },
                fetch_list=[eq_out, not_eq_out, long_eq_out],
            )
            np.testing.assert_array_equal(
                np.array(x_y_eq_out), np.array([[True], [False], [False]])
            )
163 164 165 166

            set_a_zero = np.ones([3, 2]).astype(np.float32)
            set_a_zero[0][0] = 0.0
            x_y_not_eq_out = exe.run(
167 168 169 170 171 172
                feed={"x": np.ones([3, 2]).astype(np.float32), "y": set_a_zero},
                fetch_list=[eq_out, not_eq_out, long_eq_out],
            )
            np.testing.assert_array_equal(
                np.array(x_y_not_eq_out), np.array([[False], [True], [True]])
            )
173 174 175
        paddle.disable_static()


176 177
class ShapeLayer(paddle.nn.Layer):
    def __init__(self):
178
        super().__init__()
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

    @paddle.jit.to_static(input_spec=[paddle.static.InputSpec(shape=[None, 1])])
    def forward(self, x):
        x = paddle.reshape(x, [-1, x.shape[1]])
        bs = x.shape[0]  # -1

        # for trigger choos_shape_attr_or_api
        out = paddle.zeros([bs, 1], dtype='float32')
        return out


class TestChooseShapeAttrOrApiWithLayer(unittest.TestCase):
    def test_tensor_shape(self):
        x = paddle.zeros(shape=[4, 1], dtype='float32')
        net = ShapeLayer()
        out = net(x)

196
        np.testing.assert_array_equal(out.numpy(), x.numpy())
197 198


0
0x45f 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
class TestIfElseNoValue(unittest.TestCase):
    def test_else_ret_none(self):
        input_x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])

        @paddle.jit.to_static
        def with_common_value(x, use_cache=False):
            if use_cache:
                y = x + 1
                z = x + 2
                return y, z
            else:
                c = x + 1
                z = x - 1
                return None

        @paddle.jit.to_static
        def without_common_value(x, use_cache=False):
            if use_cache:
                y = x + 1
                z = x + 2
                return y, z
            else:
                c = x + 1
                return None

        out = with_common_value(input_x, False)
        self.assertIsNone(out)
        out = without_common_value(input_x, False)
        self.assertIsNone(out)

    def test_else_ret_c(self):
        input_x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])

        @paddle.jit.to_static
        def with_common_value(x, use_cache=False):
            if use_cache:
                y = x + 1
                z = x + 2
                return y, z
            else:
                c = x + 1
                z = x - 1
                return c

        @paddle.jit.to_static
        def without_common_value(x, use_cache=False):
            if use_cache:
                y = x + 1
                z = x + 2
                return y, z
            else:
                c = x + 1
                return c

        out = with_common_value(input_x, False)
        self.assertListEqual(paddle.tolist(out), paddle.tolist(input_x + 1))
        out = without_common_value(input_x, False)
        self.assertListEqual(paddle.tolist(out), paddle.tolist(input_x + 1))
        y, z = with_common_value(input_x, True)
        self.assertListEqual(paddle.tolist(y), paddle.tolist(input_x + 1))
        self.assertListEqual(paddle.tolist(z), paddle.tolist(input_x + 2))

    def test_else_ret_cz(self):
        input_x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])

        @paddle.jit.to_static
        def with_common_value(x, use_cache=False):
            if use_cache:
                y = x + 1
                z = x + 2
                return y, z, 1
            else:
                c = x + 1
                z = x - 1
                return c, z

        @paddle.jit.to_static
        def without_common_value(x, use_cache=False):
            if use_cache:
                y = x + 1
                z = x + 2
                return y, z, 1
            else:
                c = x + 1
                d = x - 1
                return c, d

        c, z = with_common_value(input_x, False)
        self.assertListEqual(paddle.tolist(c), paddle.tolist(input_x + 1))
        self.assertListEqual(paddle.tolist(z), paddle.tolist(input_x - 1))
        c, d = without_common_value(input_x, False)
        self.assertListEqual(paddle.tolist(c), paddle.tolist(input_x + 1))
        self.assertListEqual(paddle.tolist(d), paddle.tolist(input_x - 1))


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