test_fetch_feed.py 3.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.

import unittest
16 17 18

import numpy as np

19
import paddle
20
from paddle import fluid
H
hjyp 已提交
21
from paddle.jit.api import to_static
22 23 24 25

SEED = 2020


26
class Pool2D(paddle.nn.Layer):
27
    def __init__(self):
28
        super().__init__()
29
        self.pool2d = paddle.nn.AvgPool2D(kernel_size=2, stride=1)
30

H
hjyp 已提交
31
    @to_static
32
    def forward(self, x):
33 34 35 36
        # Add func `get_result` for testing arg_name_to_idx in ast transformation.
        def get_result(x):
            return self.pool2d(x)

37
        pre = get_result(x)
38 39 40
        return pre


41
class Linear(paddle.nn.Layer):
42
    def __init__(self, input_dim=10, output_dim=5):
43
        super().__init__()
44
        self.fc = paddle.nn.Linear(
45 46
            input_dim,
            output_dim,
47 48
            weight_attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(value=0.99)
49
            ),
50 51
            bias_attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(value=0.5)
52 53
            ),
        )
54
        self.act = paddle.nn.ReLU()
55

H
hjyp 已提交
56
    @to_static
57
    def forward(self, x):
58
        pre = self.fc(x)
59
        pre = self.act(pre)
60
        loss = paddle.mean(pre)
61
        return pre, loss
62 63 64 65 66 67 68


class TestPool2D(unittest.TestCase):
    def setUp(self):
        self.dygraph_class = Pool2D
        self.data = np.random.random((1, 2, 4, 4)).astype('float32')

69
    def train(self, to_static=False):
R
Ryan 已提交
70
        paddle.jit.enable_to_static(to_static)
71

72 73
        with fluid.dygraph.guard():
            dy_layer = self.dygraph_class()
74 75
            x = fluid.dygraph.to_variable(self.data)
            prediction = dy_layer(x)
76 77
            if isinstance(prediction, (list, tuple)):
                prediction = prediction[0]
78

79
            return prediction.numpy()
80

81 82 83 84 85 86 87 88 89
    def train_static(self):
        return self.train(to_static=True)

    def train_dygraph(self):
        return self.train(to_static=False)

    def test_declarative(self):
        dygraph_res = self.train_dygraph()
        static_res = self.train_static()
90

91 92 93 94 95
        np.testing.assert_allclose(
            dygraph_res,
            static_res,
            rtol=1e-05,
            err_msg='dygraph_res is {}\n static_res is \n{}'.format(
96 97 98
                dygraph_res, static_res
            ),
        )
99 100


101
class TestLinear(TestPool2D):
102 103 104 105 106 107 108
    def setUp(self):
        self.dygraph_class = Linear
        self.data = np.random.random((4, 10)).astype('float32')


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