test_instancenorm_op_ipu.py 5.0 KB
Newer Older
J
jianghaicheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#  Copyright (c) 2021 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

import numpy as np
import paddle
import paddle.static
20
from paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest, ExecutionMode
J
jianghaicheng 已提交
21 22 23 24 25 26 27 28


@unittest.skipIf(not paddle.is_compiled_with_ipu(),
                 "core is not compiled with IPU")
class TestBase(IPUOpTest):
    def setUp(self):
        self.set_atol()
        self.set_training()
29
        self.set_data_feed()
J
jianghaicheng 已提交
30
        self.set_feed_attr()
31 32 33 34 35 36 37 38 39 40 41
        self.set_op_attrs()

    @property
    def fp16_enabled(self):
        return True

    def set_atol(self):
        self.atol = 1e-6
        self.rtol = 1e-5
        self.atol_fp16 = 1e-2
        self.rtol_fp16 = 1e-3
J
jianghaicheng 已提交
42

43 44 45 46
    def set_data_feed(self):
        x = np.random.uniform(size=[1, 3, 10, 10])
        self.feed_fp32 = {"x": x.astype(np.float32)}
        self.feed_fp16 = {"x": x.astype(np.float16)}
J
jianghaicheng 已提交
47 48

    def set_feed_attr(self):
49 50
        self.feed_shape = [x.shape for x in self.feed_fp32.values()]
        self.feed_list = list(self.feed_fp32.keys())
J
jianghaicheng 已提交
51

52
    def set_op_attrs(self):
J
jianghaicheng 已提交
53 54
        self.attrs = {"epsilon": 1e-05}

55 56
    def _test_base(self, exec_mode):
        scope = paddle.static.Scope()
J
jianghaicheng 已提交
57 58
        main_prog = paddle.static.Program()
        startup_prog = paddle.static.Program()
59 60
        main_prog.random_seed = self.SEED
        startup_prog.random_seed = self.SEED
J
jianghaicheng 已提交
61

62
        with paddle.static.scope_guard(scope):
J
jianghaicheng 已提交
63 64 65 66
            with paddle.static.program_guard(main_prog, startup_prog):
                x = paddle.static.data(
                    name=self.feed_list[0],
                    shape=self.feed_shape[0],
67
                    dtype='float32')
J
jianghaicheng 已提交
68 69 70 71 72 73 74 75 76

                if self.is_training:
                    ch = self.feed_shape[0][1]
                    conv1 = paddle.static.nn.conv2d(
                        x, num_filters=ch, filter_size=3, bias_attr=False)
                    scale = paddle.ParamAttr(trainable=True)
                    bias = paddle.ParamAttr(trainable=True)
                    out = paddle.fluid.layers.nn.instance_norm(
                        conv1, param_attr=scale, bias_attr=bias, **self.attrs)
77 78 79
                    loss = paddle.mean(out)
                    adam = paddle.optimizer.Adam(learning_rate=1e-2)
                    adam.minimize(loss)
J
jianghaicheng 已提交
80 81
                else:
                    out = paddle.fluid.layers.nn.instance_norm(
82
                        x, param_attr=True, bias_attr=True, **self.attrs)
J
jianghaicheng 已提交
83 84 85 86 87 88

                if self.is_training:
                    fetch_list = [loss.name]
                else:
                    fetch_list = [out.name]

89
            if exec_mode == ExecutionMode.CPU_FP32:
J
jianghaicheng 已提交
90
                place = paddle.CPUPlace()
91 92 93
            else:
                place = paddle.IPUPlace()

J
jianghaicheng 已提交
94 95 96
            exe = paddle.static.Executor(place)
            exe.run(startup_prog)

97
            if exec_mode != ExecutionMode.CPU_FP32:
J
jianghaicheng 已提交
98
                feed_list = self.feed_list
Y
yaozhixin 已提交
99
                ipu_strategy = paddle.static.IpuStrategy()
100 101 102 103
                ipu_strategy.set_graph_config(is_training=self.is_training)
                if exec_mode == ExecutionMode.IPU_POPART_FP16:
                    ipu_strategy.set_precision_config(enable_fp16=True)
                program = paddle.static.IpuCompiledProgram(
J
jianghaicheng 已提交
104 105 106 107 108
                    main_prog,
                    ipu_strategy=ipu_strategy).compile(feed_list, fetch_list)
            else:
                program = main_prog

109 110 111 112
            feed = self.feed_fp32
            if exec_mode > ExecutionMode.IPU_FP32:
                feed = self.feed_fp16

J
jianghaicheng 已提交
113 114 115 116
            if self.is_training:
                result = []
                for _ in range(self.epoch):
                    loss_res = exe.run(program,
117
                                       feed=feed,
J
jianghaicheng 已提交
118 119 120 121
                                       fetch_list=fetch_list)
                    result.append(loss_res)
                return np.array(result)
            else:
122
                result = exe.run(program, feed=feed, fetch_list=fetch_list)
J
jianghaicheng 已提交
123 124
                return result[0]

125 126 127 128 129 130 131 132
    def test(self):
        output_dict = {}
        for mode in ExecutionMode:
            if mode > ExecutionMode.IPU_FP32 and not self.fp16_enabled:
                break
            if mode > ExecutionMode.IPU_FP32 and self.is_training:
                break
            output_dict[mode] = self._test_base(mode).flatten()
J
jianghaicheng 已提交
133

134
        self.check(output_dict)
J
jianghaicheng 已提交
135 136 137 138 139 140 141 142 143 144


class TestTrainCase1(TestBase):
    def set_training(self):
        self.is_training = True
        self.epoch = 10


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