op_test_ipu.py 9.5 KB
Newer Older
J
jianghaicheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15
import os
J
jianghaicheng 已提交
16 17
import random
import unittest
18
from enum import IntEnum
A
Allen Guo 已提交
19
from typing import Dict, List, Optional
J
jianghaicheng 已提交
20

A
Allen Guo 已提交
21
import numpy as np
22 23
import paddle
import paddle.static
J
jianghaicheng 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36

map_np_dtype_to_fluid_dtype = {
    'bool': "bool",
    'int8': "int8",
    'uint8': "uint8",
    "int32": "int32",
    "int64": "int64",
    "float16": "float16",
    "float32": "float32",
    "float64": "float64",
}


A
Allen Guo 已提交
37 38 39 40
def np_dtype_to_fluid_str(dtype: np.dtype) -> str:
    return map_np_dtype_to_fluid_dtype[dtype.name]


41 42
class ExecutionModeFull(IntEnum):
    # Run fp32 model on cpu
43
    CPU_FP32 = 1
44
    # Run fp32 model on ipu
45
    IPU_FP32 = 2
A
Allen Guo 已提交
46
    # Convert model to fp16 using mixed-precision approch
47
    # All parameters will be converted to fp16
A
Allen Guo 已提交
48
    IPU_FP16 = 3
49 50


51 52 53
class ExecutionMode(IntEnum):
    CPU_FP32 = ExecutionModeFull.CPU_FP32
    IPU_FP32 = ExecutionModeFull.IPU_FP32
A
Allen Guo 已提交
54
    IPU_FP16 = ExecutionModeFull.IPU_FP16
55

J
jianghaicheng 已提交
56

A
Allen Guo 已提交
57
class IPUTest(unittest.TestCase):
58

J
jianghaicheng 已提交
59 60
    @classmethod
    def setUpClass(cls):
61
        # Get random seeds
J
jianghaicheng 已提交
62 63 64
        cls._np_rand_state = np.random.get_state()
        cls._py_rand_state = random.getstate()

65
        cls.SEED = 2021
J
jianghaicheng 已提交
66 67
        np.random.seed(cls.SEED)
        random.seed(cls.SEED)
A
Allen Guo 已提交
68
        paddle.seed(cls.SEED)
69

70 71
        # Enable paddle static graph mode
        paddle.enable_static()
J
jianghaicheng 已提交
72 73 74 75 76 77 78

    @classmethod
    def tearDownClass(cls):
        """Restore random seeds"""
        np.random.set_state(cls._np_rand_state)
        random.setstate(cls._py_rand_state)

A
Allen Guo 已提交
79
    # Check if ipumodel mode is enabled
80 81 82 83 84 85 86 87
    @classmethod
    def use_ipumodel(cls):
        if 'POPLAR_IPUMODEL' not in os.environ:
            return False
        else:
            flag = os.environ['POPLAR_IPUMODEL']
            if flag.upper() in ['1', "TRUE"]:
                return True
J
jianghaicheng 已提交
88

A
Allen Guo 已提交
89 90
    # Decorator for static graph building
    def static_graph(builder):
91

A
Allen Guo 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        def wrapper(self, *args, **kwargs):
            self.scope = paddle.static.Scope()
            self.main_prog = paddle.static.Program()
            self.startup_prog = paddle.static.Program()
            self.main_prog.random_seed = self.SEED
            self.startup_prog.random_seed = self.SEED
            with paddle.static.scope_guard(self.scope):
                with paddle.utils.unique_name.guard(
                        paddle.utils.unique_name.generate('')):
                    with paddle.static.program_guard(self.main_prog,
                                                     self.startup_prog):
                        builder(self, *args, **kwargs)

        return wrapper

    # Cast a fp32 model to a full-fp16 model
    @classmethod
    def cast_model_to_fp16(cls, main_program):
        amp_list = paddle.static.amp.CustomOpLists()
        amp_list.unsupported_list = {}
        to_fp16_var_names = paddle.static.amp.cast_model_to_fp16(
            main_program, amp_list, use_fp16_guard=False)
        paddle.static.amp.cast_parameters_to_fp16(
            paddle.CPUPlace(),
            main_program,
            to_fp16_var_names=to_fp16_var_names)


class IPUOpTest(IPUTest):
121

A
Allen Guo 已提交
122 123 124 125 126 127 128 129 130 131 132 133
    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        # Items that a op_tester needs
        cls.main_prog: paddle.static.Program = None
        cls.startup_prog: paddle.static.Program = None
        cls.scope: paddle.static.Scope = None
        cls.feed_list: List[str] = None
        cls.fetch_list: List[str] = None
        cls.output_dict: Optional[Dict] = {}

A
Allen Guo 已提交
134 135 136 137 138
    def tearDown(self):
        # Manual reset when using ipumodel
        if self.use_ipumodel():
            paddle.framework.core.IpuBackend.get_instance().reset()

A
Allen Guo 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    @property
    def fp16_enabled(self):
        return True

    def skip_mode(self, exec_mode):
        if exec_mode > ExecutionMode.IPU_FP32 and not self.fp16_enabled:
            return True
        else:
            return False

    def is_ipu_mode(self, exec_mode):
        if exec_mode == ExecutionMode.CPU_FP32:
            return False
        return True

    def is_fp16_mode(self, exec_mode):
        if exec_mode != ExecutionMode.IPU_FP16:
            return False
        return True

J
jianghaicheng 已提交
159
    def set_atol(self):
160 161 162 163
        self.atol = 1e-10
        self.rtol = 1e-6
        self.atol_fp16 = 1e-3
        self.rtol_fp16 = 1e-3
J
jianghaicheng 已提交
164 165 166 167

    def set_training(self):
        self.is_training = False
        self.epoch = 1
168

A
Allen Guo 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    def run_op_test(self, exec_mode, ipu_strategy=None):
        # NOTE: some op has no inputs
        # if len(self.feed_list) == 0 or len(self.fetch_list) == 0:
        #     raise ValueError('feed_list or fetch_list is empty')
        if self.is_ipu_mode(exec_mode):
            place = paddle.IPUPlace()
        else:
            place = paddle.CPUPlace()
        exe = paddle.static.Executor(place)
        exe.run(self.startup_prog)
        if self.is_ipu_mode(exec_mode):
            if ipu_strategy is None:
                ipu_strategy = paddle.static.IpuStrategy()
                ipu_strategy.set_graph_config(is_training=self.is_training)
            if self.is_fp16_mode(exec_mode):
                ipu_strategy.set_precision_config(enable_fp16=True)
                IPUOpTest.cast_model_to_fp16(self.main_prog)
            program = paddle.static.IpuCompiledProgram(
187 188 189
                self.main_prog,
                ipu_strategy=ipu_strategy).compile(self.feed_list,
                                                   self.fetch_list)
A
Allen Guo 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        else:
            program = self.main_prog

        feed = self.feed_fp32
        if self.is_fp16_mode(exec_mode):
            feed = self.feed_fp16

        if self.is_training:
            result = []
            for _ in range(self.epoch):
                loss_res = exe.run(program,
                                   feed=feed,
                                   fetch_list=self.fetch_list)
                result.append(loss_res)
        else:
            result = exe.run(program, feed=feed, fetch_list=self.fetch_list)

        if isinstance(result, list) and len(result) == 1:
            self.output_dict[exec_mode] = result[0]
        else:
            self.output_dict[exec_mode] = result

    def check(self, check_shape=False, output_dict=None):
        if output_dict is None:
            output_dict = self.output_dict
        if len(output_dict) == 0:
            raise ValueError("output_dict is empty")
        cpu_fp32 = output_dict[ExecutionMode.CPU_FP32]
        ipu_fp32 = output_dict[ExecutionMode.IPU_FP32]
A
Allen Guo 已提交
219 220 221 222 223 224 225 226 227
        if len(cpu_fp32) != len(ipu_fp32):
            raise ValueError("different outputs number between ipu and cpu.")
        for cpu_fp32_res, ipu_fp32_res in zip(cpu_fp32, ipu_fp32):
            cpu_fp32_res = np.asarray(cpu_fp32_res).astype(np.float32).flatten()
            ipu_fp32_res = np.asarray(ipu_fp32_res).astype(np.float32).flatten()
            pass_check = np.allclose(ipu_fp32_res,
                                     cpu_fp32_res,
                                     rtol=self.rtol,
                                     atol=self.atol)
A
Allen Guo 已提交
228
            if not pass_check:
A
Allen Guo 已提交
229 230
                max_atol = np.abs(ipu_fp32_res - cpu_fp32_res).max()
                cpu_fp32_abs = np.abs(cpu_fp32_res)
A
Allen Guo 已提交
231
                cpu_fp32_abs[cpu_fp32_abs == 0.0] = 1e-20
A
Allen Guo 已提交
232 233
                max_rtol = (np.abs(ipu_fp32_res - cpu_fp32_res) /
                            cpu_fp32_abs).max()
A
Allen Guo 已提交
234
                raise AssertionError(
A
Allen Guo 已提交
235
                    f"ipu_fp32 check failed. max_atol is {max_atol}, max_rtol is {max_rtol}"
A
Allen Guo 已提交
236
                )
237 238

            if check_shape:
A
Allen Guo 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                self.assertTrue(cpu_fp32_res.shape == ipu_fp32_res.shape)

        if ExecutionMode.IPU_FP16 in output_dict.keys():
            ipu_fp16 = output_dict[ExecutionMode.IPU_FP16]
            if len(cpu_fp32) != len(ipu_fp16):
                raise ValueError(
                    "different outputs number between ipu and cpu.")
            for cpu_fp32_res, ipu_fp16_res in zip(cpu_fp32, ipu_fp16):
                cpu_fp32_res = np.asarray(cpu_fp32_res).astype(
                    np.float32).flatten()
                ipu_fp16_res = np.asarray(ipu_fp16_res).astype(
                    np.float32).flatten()
                pass_check = np.allclose(ipu_fp16_res,
                                         cpu_fp32_res,
                                         rtol=self.rtol_fp16,
                                         atol=self.atol_fp16)
                if not pass_check:
                    max_atol = np.abs(ipu_fp16_res - cpu_fp32_res).max()
                    cpu_fp32_abs = np.abs(cpu_fp32_res)
                    cpu_fp32_abs[cpu_fp32_abs == 0.0] = 1e-20
                    max_rtol = (np.abs(ipu_fp16_res - cpu_fp32_res) /
                                cpu_fp32_abs).max()
                    raise AssertionError(
                        f"ipu_fp16 check failed. max_atol is {max_atol}, max_rtol is {max_rtol}"
                    )

                if check_shape:
                    self.assertTrue(ipu_fp16_res.shape == cpu_fp32_res.shape)
A
Allen Guo 已提交
267 268 269 270 271 272

    # Execution Mode
    class ExecutionMode(IntEnum):
        CPU_FP32 = ExecutionModeFull.CPU_FP32
        IPU_FP32 = ExecutionModeFull.IPU_FP32
        IPU_FP16 = ExecutionModeFull.IPU_FP16