test_full_name_usage.py 2.3 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
import paddle
20
from paddle import fluid
21
from paddle.jit import to_static
22 23


24
@paddle.jit.to_static
25 26
def dygraph_decorated_func(x):
    x = fluid.dygraph.to_variable(x)
27
    if paddle.mean(x) > 0:
28 29 30 31 32 33
        x_v = x - 1
    else:
        x_v = x + 1
    return x_v


34
@paddle.jit.to_static
35 36
def jit_decorated_func(x):
    x = fluid.dygraph.to_variable(x)
37
    if paddle.mean(x) > 0:
38 39 40 41 42 43
        x_v = x - 1
    else:
        x_v = x + 1
    return x_v


44
@paddle.jit.to_static
45 46 47 48
def decorated_call_decorated(x):
    return jit_decorated_func(x)


49
class DoubleDecorated:
50
    @classmethod
51
    @to_static
52 53 54 55
    def double_decorated_func1(self, x):
        return dygraph_decorated_func(x)

    @classmethod
56
    @paddle.jit.to_static
57 58 59 60 61 62 63 64
    def double_decorated_func2(self, x):
        return jit_decorated_func(x)


class TestFullNameDecorator(unittest.TestCase):
    def test_run_success(self):
        x = np.ones([1, 2]).astype("float32")
        answer = np.zeros([1, 2]).astype("float32")
65
        with fluid.dygraph.guard():
66 67 68 69 70 71 72 73 74
            np.testing.assert_allclose(
                dygraph_decorated_func(x).numpy(), answer, rtol=1e-05
            )
            np.testing.assert_allclose(
                jit_decorated_func(x).numpy(), answer, rtol=1e-05
            )
            np.testing.assert_allclose(
                decorated_call_decorated(x).numpy(), answer, rtol=1e-05
            )
75 76 77 78 79 80 81 82
            with self.assertRaises(NotImplementedError):
                DoubleDecorated().double_decorated_func1(x)
            with self.assertRaises(NotImplementedError):
                DoubleDecorated().double_decorated_func2(x)


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