test_partial_program.py 6.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
from test_fetch_feed import Linear

20
import paddle
21
from paddle import fluid
H
hjyp 已提交
22
from paddle.jit.api import to_static
23 24 25 26 27 28 29 30 31 32 33

SEED = 2020


def nested_input(x, y):
    sum_res = x + y[0]

    z_elem = y[3]['z']
    sub_res = z_elem[0] - z_elem[1]

    mul_res = y[-1]['d']['da'] * y[-1]['d']['dc']
34
    mean_func = paddle.mean
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    out = mean_func(sub_res) + mean_func(sum_res) + mean_func(mul_res)
    return out


def nested_output(x, y):
    sum_res = x + y
    sub_res = x - y
    mul_res = x * y

    out = {}
    out['z'] = sum_res
    out['a'] = [sub_res, 64, [mul_res, "cmd"]]
    return out


def fake_data(shape):
    x_data = np.random.random(shape).astype('float32')
    return fluid.dygraph.to_variable(x_data)


class TestWithNestedInput(unittest.TestCase):
    def setUp(self):
        self.x = None
        self.y = None

    def fake_input(self):
        self.x = fake_data([10, 16])
        self.y = [
63 64 65 66 67
            fake_data([10, 16]),
            "preprocess_cmd",
            64,
            {
                'z': [fake_data([10, 12]), fake_data([10, 12])],
68
                'c': fake_data([10, 10]),
69 70
                'd': {'da': 12, 'dc': fake_data([10, 10])},
            },
71 72 73 74 75 76 77 78
        ]

    def _run(self, to_static):
        with fluid.dygraph.guard():
            if self.x is None or self.y is None:
                self.fake_input()

            if to_static:
H
hjyp 已提交
79
                out = paddle.jit.to_static(nested_input)(self.x, self.y)
80 81 82 83 84 85 86 87
            else:
                out = nested_input(self.x, self.y)

        return out.numpy()

    def test_nest(self):
        dygraph_res = self._run(to_static=False)
        static_res = self._run(to_static=True)
88
        np.testing.assert_allclose(dygraph_res, static_res, rtol=1e-05)
89 90 91 92 93 94 95 96 97 98 99 100 101 102


class TestWithNestedOutput(unittest.TestCase):
    def setUp(self):
        self.x = None
        self.y = None

    def _run(self, to_static):
        with fluid.dygraph.guard():
            if self.x is None or self.y is None:
                self.x = fake_data([10, 16])
                self.y = fake_data([10, 16])

            if to_static:
H
hjyp 已提交
103
                out = paddle.jit.to_static(nested_output)(self.x, self.y)
104 105 106 107 108 109 110
            else:
                out = nested_output(self.x, self.y)

        return out

    def test_nest(self):
        dygraph_res = self._run(to_static=False)
111
        dygraph_res = paddle.utils.flatten(dygraph_res)
112 113

        static_res = self._run(to_static=True)
114
        static_res = paddle.utils.flatten(static_res)
115 116 117 118

        self.assertTrue(len(dygraph_res) == len(static_res))

        for dy_var, st_var in zip(dygraph_res, static_res):
W
wanghuancoder 已提交
119
            if isinstance(dy_var, fluid.core.eager.Tensor):
120 121 122
                np.testing.assert_allclose(
                    dy_var.numpy(), st_var.numpy(), rtol=1e-05
                )
123 124 125 126
            else:
                self.assertTrue(dy_var, st_var)


127 128 129 130 131 132 133 134 135
class TestWithTrainAndEval(unittest.TestCase):
    def test_switch_eval_and_train(self):

        with fluid.dygraph.guard():
            linear_net = Linear()
            x_data = np.random.random((4, 10)).astype('float32')
            x = fluid.dygraph.to_variable(x_data)
            linear_net(x)

136
            _, train_partial_layer = linear_net.forward.program_cache.last()[-1]
137
            # check default mode is for training
138 139 140
            self.assertEqual(
                train_partial_layer.program, train_partial_layer._train_program
            )
141 142 143 144

            # switch to run test program after `eval()`
            linear_net.eval()
            linear_net(x)
145
            _, eval_partial_layer = linear_net.forward.program_cache.last()[-1]
146 147 148
            self.assertEqual(
                eval_partial_layer.program, eval_partial_layer._infer_program
            )
149 150 151 152

            # switch back into training
            linear_net.train()
            linear_net(x)
153 154 155
            self.assertEqual(
                train_partial_layer.program, train_partial_layer._train_program
            )
156 157 158 159 160 161 162 163 164 165 166 167 168


class TestWithNoGrad(unittest.TestCase):
    def test_with_no_grad(self):
        with fluid.dygraph.guard():
            linear_net = Linear()
            x_data = np.random.random((5, 10)).astype('float32')
            x = fluid.dygraph.to_variable(x_data)

            with paddle.no_grad():
                linear_net.train()
                linear_net(x)
                _, partial_layer = linear_net.forward.program_cache.last()[-1]
169 170 171
                self.assertEqual(
                    partial_layer.program, partial_layer._train_program
                )
172 173


174
class GPT2LMHeadModel(paddle.nn.Layer):
175
    def __init__(self):
176
        super().__init__()
177 178 179
        self.embedding0 = paddle.nn.Embedding(20, 16)
        self.embedding1 = paddle.nn.Embedding(20, 32)
        self.lm_head_weight = paddle.to_tensor(
180 181
            np.random.rand(2, 3).astype('float32')
        )
182

H
hjyp 已提交
183
    @to_static
184
    def forward(self, x):
185
        x = paddle.reshape(x, shape=[-1, 6])
186
        x1, x2, x3 = paddle.split(x=x, axis=1, num_or_sections=3)
187 188 189 190 191 192 193 194 195 196 197 198 199
        return x1


class TestPruneUnusedParamInProgram(unittest.TestCase):
    def test_prune(self):
        input_ids = np.array([[15, 11, 6, 3, 18, 13]]).astype("float32")

        place = fluid.CPUPlace()
        with fluid.dygraph.guard(place):
            model = GPT2LMHeadModel()
            model.eval()
            input_ids = paddle.to_tensor(input_ids)
            out = model(input_ids)
200
            np.testing.assert_array_equal(out.numpy(), [[15, 11]])
201 202


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