test_cache_program.py 5.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   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.

from __future__ import print_function

import unittest
import numpy as np
from collections import Counter

import paddle.fluid as fluid

23
from paddle.fluid.dygraph.dygraph_to_static import ProgramTranslator
24
from paddle.fluid.dygraph.dygraph_to_static import convert_function_with_cache
25 26 27 28 29 30 31 32 33 34 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

from test_fetch_feed import Pool2D, Linear


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

    def test_cache(self):
        prev_ops, cur_ops = Counter(), Counter()
        prev_out, cur_out = None, None
        main_program = fluid.Program()
        with fluid.program_guard(main_program):
            static_net = self.dygraph_class()
            for batch_id in range(self.batch_num):
                out = static_net(self.data)
                # Check outputs
                prev_out = cur_out
                cur_out = out
                # Check forward ops
                prev_ops = cur_ops
                cur_ops = Counter([
                    op.type for op in fluid.default_main_program().block(0).ops
                ])
                if batch_id > 0:
                    self.assertTrue(
                        np.allclose(prev_out[0], cur_out[0]),
                        msg='Output in previous batch is {}\n Output in current batch is \n{}'
                        .format(prev_out, cur_out))
                    self.assertEqual(prev_ops, cur_ops)


class TestCacheProgram2(TestCacheProgram):
    def setUp(self):
        self.batch_num = 5
        self.dygraph_class = Linear
        self.data = np.random.random((4, 10)).astype('float32')


class TestCacheProgramWithOptimizer(unittest.TestCase):
    def setUp(self):
        self.dygraph_class = Linear
        self.data = np.random.random((4, 10)).astype('float32')
        self.batch_num = 5

    def train_static(self):
        main_program = fluid.Program()
        loss_data = []
        with fluid.program_guard(main_program):
            static_net = self.dygraph_class()
            adam = fluid.optimizer.AdamOptimizer(learning_rate=0.001)
            # set optimizer
79
            program_translator = ProgramTranslator()
80
            program_translator.set_optimizer(adam, index_of_loss=1)
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

            for batch_id in range(self.batch_num):
                pred, avg_loss = static_net(self.data)
                loss_data.append(np.array(avg_loss))

        return loss_data

    def train_dygraph(self):
        with fluid.dygraph.guard(fluid.CPUPlace()):
            dygraph_net = self.dygraph_class()
            adam = fluid.optimizer.AdamOptimizer(
                learning_rate=0.001, parameter_list=dygraph_net.parameters())
            loss_data = []
            for batch_id in range(self.batch_num):
                pred, avg_loss = dygraph_net(self.data)

                loss_data.append(avg_loss.numpy())
                avg_loss.backward()
                adam.minimize(avg_loss)
                dygraph_net.clear_gradients()

        return loss_data

    def test_with_optimizer(self):
        dygraph_loss = self.train_dygraph()
        static_loss = self.train_static()
        self.assertTrue(
            np.allclose(dygraph_loss, static_loss),
            msg='dygraph is {}\n static_res is \n{}'.format(dygraph_loss,
                                                            static_loss))

112 113 114 115 116 117 118 119 120 121 122 123 124 125
    def test_exception(self):
        main_program = fluid.Program()
        loss_data = []
        with fluid.program_guard(main_program):
            static_net = self.dygraph_class()
            adam = fluid.optimizer.AdamOptimizer(learning_rate=0.001)
            # set optimizer
            program_translator = ProgramTranslator()

            with self.assertRaisesRegexp(ValueError, "has already been set"):
                for batch_id in range(self.batch_num):
                    program_translator.set_optimizer(adam, index_of_loss=1)
                    static_net(self.data)

126

127 128 129 130 131 132 133 134 135 136 137 138 139 140
def simple_func(x):
    inputs = fluid.dygraph.to_variable(x)
    mean = fluid.layers.mean(inputs)
    return mean


class TestConvertWithCache(unittest.TestCase):
    def test_cache(self):
        static_func = convert_function_with_cache(simple_func)
        # Get transformed function from cache.
        cached_func = convert_function_with_cache(simple_func)
        self.assertTrue(id(static_func), id(cached_func))


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