test_requantize_mkldnn_op.py 9.9 KB
Newer Older
X
xiaolil1 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2018 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
19 20
import paddle.fluid as fluid
import paddle.fluid.core as core
X
xiaolil1 已提交
21 22 23 24 25 26 27
from paddle.fluid.tests.unittests.op_test import OpTest
from mkldnn_op_test import format_reorder


class TestReQuantizeOp(OpTest):
    def setUp(self):
        self.op_type = 'requantize'
28 29 30 31
        self.scale_in = 127.0
        self.shift_in = 0.0
        self.scale_out = 100.0
        self.shift_out = 0.0
32
        self.input_size = [1, 1, 10, 10]
33 34 35 36 37 38 39 40 41 42 43 44
        self.input_data_type = 'int8'
        self.set_scales()
        self.set_shifts()
        self.set_input_data_type()
        self.prepare_input()
        self.prepare_output()

    def prepare_input(self):
        if self.input_data_type == 'int8':
            # input data values are integers from interval [-128, 128)
            self.input = (np.random.randint(0, 256, self.input_size) - 128
                          ).astype(self.input_data_type)
X
xiaolil1 已提交
45
        else:
46
            # input data values are integers from interval [0, 256)
47
            self.input = (np.random.randint(
48
                0, 256, self.input_size)).astype(self.input_data_type)
X
xiaolil1 已提交
49

50
        self.inputs = {'Input': OpTest.np_dtype_to_fluid_dtype(self.input)}
51 52 53 54 55 56
        self.attrs = {
            'Scale_in': self.scale_in,
            'Scale_out': self.scale_out,
            'Shift_in': self.shift_in,
            'Shift_out': self.shift_out
        }
X
xiaolil1 已提交
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    def prepare_output(self):
        scale_ratio = self.scale_out / self.scale_in
        with_shift = (self.shift_in != 0.0 or self.shift_out != 0.0)

        if with_shift or self.input_data_type == 'uint8':
            dst_type = 'uint8'
            type_min = 0
            type_max = 255
            new_shift = np.clip(
                np.rint(self.shift_out - scale_ratio * self.shift_in), type_min,
                type_max)
        else:
            dst_type = 'int8'
            type_min = -128
            type_max = 127
            new_shift = 0
X
xiaolil1 已提交
74

75 76 77 78 79 80
        output_tmp = np.clip(
            np.rint(self.input.astype('float32') * scale_ratio + new_shift),
            type_min, type_max).astype(dst_type)

        self.output = format_reorder(output_tmp, self.input_size)
        self.outputs = {'Output': self.output}
X
xiaolil1 已提交
81 82

    def test_check_output(self):
83
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
84 85
        self.assertTrue(self.input_data_type == 'uint8' or self.shift_in == 0.0,
                        'Input data must be unsigned if it has nonzero shift.')
86
        self.check_output(check_dygraph=False)
X
xiaolil1 已提交
87

88 89 90 91 92 93 94 95 96 97
    def check_raise_error(self, msg):
        try:
            self.check_output()
        except Exception as e:
            if msg in str(e):
                raise AttributeError
            else:
                print(e)

    def set_scales(self):
X
xiaolil1 已提交
98 99
        pass

100
    def set_shifts(self):
X
xiaolil1 已提交
101 102
        pass

103 104 105 106 107 108
    def set_input_data_type(OpTest):
        pass


# ---------------test requantize with s8 input, no shift--------------------

X
xiaolil1 已提交
109

110 111 112 113
class TestReQuantizeOp_S8_SameScales(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 127.0
        self.scale_out = 127.0
X
xiaolil1 已提交
114 115


116 117 118 119
class TestReQuantizeOp_S8_DifferentScales_1(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 127.0
        self.scale_out = 100.0
X
xiaolil1 已提交
120 121


122 123 124 125
class TestReQuantizeOp_S8_DifferentScales_2(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 100.0
        self.scale_out = 127.0
X
xiaolil1 已提交
126 127


128 129 130 131
class TestReQuantizeOp_S8_ZeroInputScale(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 0.0
        self.scale_out = 127.0
X
xiaolil1 已提交
132

133 134 135 136 137 138 139
    def prepare_output(self):
        self.output = np.zeros(self.input_size)
        self.outputs = {'Output': self.output}

    def test_check_output(self):
        self.assertRaises(AttributeError, self.check_raise_error,
                          'Scale of input cannot be 0.0')
X
xiaolil1 已提交
140 141


142 143 144 145
class TestReQuantizeOp_S8_ZeroOutputScale(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 127.0
        self.scale_out = 0.0
X
xiaolil1 已提交
146

147 148 149
    def prepare_output(self):
        self.output = np.zeros(self.input_size)
        self.outputs = {'Output': self.output}
X
xiaolil1 已提交
150

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    def test_check_output(self):
        self.assertRaises(AttributeError, self.check_raise_error,
                          'Scale of output cannot be 0.0')


# ---------------test requantize with u8 input, no shift--------------------


class TestReQuantizeOp_U8_SameScales(TestReQuantizeOp_S8_SameScales):
    def set_input_data_type(self):
        self.input_data_type = 'uint8'


class TestReQuantizeOp_U8_DifferentScales_1(
        TestReQuantizeOp_S8_DifferentScales_1):
    def set_input_data_type(self):
        self.input_data_type = 'uint8'


class TestReQuantizeOp_U8_DifferentScales_2(
        TestReQuantizeOp_S8_DifferentScales_2):
    def set_input_data_type(self):
        self.input_data_type = 'uint8'


# ---------------test requantize with s8 input, with shift------------------


class TestReQuantizeOp_S8_WithShift(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 60.0
        self.scale_out = 127.0

    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 128.0

    def test_check_output(self):
        self.assertRaises(
            AttributeError, self.check_raise_error,
            'Requantize does not support nonzero shift for signed input.')
X
xiaolil1 已提交
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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 267 268 269

class TestReQuantizeOp_S8_WithOutputShift(TestReQuantizeOp):
    def set_scales(self):
        self.scale_in = 127.0
        self.scale_out = 60.0

    def set_shifts(self):
        self.shift_in = 0.0
        self.shift_out = 120.0


# ---------------test requantize with u8 input, with shift------------------


class TestReQuantizeOp_U8_SameScales_SameShift(TestReQuantizeOp_U8_SameScales):
    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 128.0


class TestReQuantizeOp_U8_SameScales_DifferentShift_1(
        TestReQuantizeOp_U8_SameScales):
    def set_shifts(self):
        self.shift_in = 60.0
        self.shift_out = 128.0


class TestReQuantizeOp_U8_SameScales_DifferentShift_2(
        TestReQuantizeOp_U8_SameScales):
    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 60.0


class TestReQuantizeOp_U8_DifferentScales_1_SameShift(
        TestReQuantizeOp_U8_DifferentScales_1):
    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 128.0


class TestReQuantizeOp_U8_DifferentScales_2_SameShift(
        TestReQuantizeOp_U8_DifferentScales_2):
    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 128.0


class TestReQuantizeOp_U8_DifferentScales_1_DifferentShift_1(
        TestReQuantizeOp_U8_DifferentScales_1):
    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 60.0


class TestReQuantizeOp_U8_DifferentScales_2_DifferentShift_1(
        TestReQuantizeOp_U8_DifferentScales_2):
    def set_shifts(self):
        self.shift_in = 128.0
        self.shift_out = 60.0


class TestReQuantizeOp_U8_DifferentScales_1_DifferentShift_2(
        TestReQuantizeOp_U8_DifferentScales_1):
    def set_shifts(self):
        self.shift_in = 60.0
        self.shift_out = 128.0


class TestReQuantizeOp_U8_DifferentScales_2_DifferentShift_2(
        TestReQuantizeOp_U8_DifferentScales_2):
    def set_shifts(self):
        self.shift_in = 60.0
        self.shift_out = 128.0


# ---------------test reused requantize op, no shift------------------------
270 271 272 273


class TestReQuantizeOpReused(TestReQuantizeOp):
    def setUp(self):
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        #  self.input_size = [1, 1, 10, 10]
        self.input_size = [1, 1, 2, 2]
        self.input_data_type = 'int8'
        self.set_scales()
        self.set_shifts()
        self.set_input_data_type()
        self.prepare_input()
        self.prepare_output()

    def set_scales(self):
        self.scale_in = 100.0
        self.scale_out = 120.0

    def set_shifts(self):
        self.shift_in = 0.0
        self.shift_out = 0.0

    def set_input_data_type(self):
        pass
293 294 295 296 297 298 299 300 301 302 303 304

    def test_check_output(self):
        variables = {
            "input": self.input,
            "output": self.output,
        }
        program = fluid.Program()
        with fluid.program_guard(program):
            block = program.global_block()
            for name in variables:
                block.create_var(
                    name=name, dtype="int8", shape=variables[name].shape)
305
            block.append_op(
306 307 308
                type="requantize",
                inputs={'Input': block.var('input'), },
                outputs={"Output": block.var('output')},
309 310 311 312 313 314
                attrs={
                    'Scale_in': self.scale_in,
                    'Scale_out': self.scale_out,
                    'Shift_in': self.shift_in,
                    'Shift_out': self.shift_out
                })
315 316 317 318 319 320 321 322 323 324 325 326
            place = core.CPUPlace()
            exe = fluid.Executor(place)
            for i in range(2):
                out = exe.run(program,
                              feed={'input': variables['input']},
                              fetch_list=['output'])

            self.assertTrue(
                np.allclose(
                    variables['output'], out[0], atol=1e-4), 'output')


327 328 329 330 331 332 333 334 335 336 337 338
# ---------------test reused requantize op, no shift------------------------


class TestReQuantizeOpReused_WithShift(TestReQuantizeOpReused):
    def set_input_data_type(self):
        self.input_data_type = 'uint8'

    def set_shifts(self):
        self.shift_in = 128
        self.shift_out = 60


X
xiaolil1 已提交
339 340
if __name__ == '__main__':
    unittest.main()