test_fake_dequantize_op.py 10.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15
import math
16
import unittest
17

18
import numpy as np
19
from op_test import OpTest
20 21


22
def quantize_max_abs(x, max_range):
23
    scale = np.max(np.abs(x).flatten())
24
    y = np.round(x / scale * max_range)
25 26 27
    return y, scale


28
def dequantize_max_abs(x, scale, max_range):
29
    y = x * scale / max_range
30 31 32
    return y


33 34
def channel_wise_quantize_max_abs(x, quant_bit=8, quant_axis=0):
    assert quant_axis in [0, 1], "The quant_axis should be 0 or 1."
Z
Zhen Wang 已提交
35
    scales = []
36 37 38
    y = x.copy()
    max_range = math.pow(2, quant_bit - 1) - 1
    if quant_axis == 0:
39
        for i in range(x.shape[0]):
40 41 42 43 44 45 46 47
            scale = np.max(np.abs(x[i])).astype("float32")
            scales.append(scale)
            y[i] = np.round(x[i] * max_range / scale)
    elif quant_axis == 1:
        for i in range(x.shape[1]):
            scale = np.max(np.abs(x[:, i])).astype("float32")
            scales.append(scale)
            y[:, i] = np.round(x[:, i] * max_range / scale)
Z
Zhen Wang 已提交
48 49 50
    return y, scales


51 52 53
def channel_wise_dequantize_max_abs(
    x, scales, quant_bits, quant_axis, activation_scale=None
):
54 55 56 57
    assert quant_axis in [0, 1], "The quant_axis should be 0 or 1."

    if isinstance(quant_bits, list):
        max_range = math.pow(2, quant_bits[0] - 1) - 1
58
    else:
59 60 61
        max_range = math.pow(2, quant_bits - 1) - 1
    y = x.copy()
    if quant_axis == 0:
62
        for i in range(x.shape[0]):
63 64 65 66 67 68 69
            y[i] = x[i] * scales[i] / max_range
    elif quant_axis == 1:
        for i in range(x.shape[1]):
            y[:, i] = x[:, i] * scales[i] / max_range

    if activation_scale is not None:
        y = y * activation_scale / (math.pow(2, quant_bits[1] - 1) - 1)
Z
Zhen Wang 已提交
70 71 72
    return y


73
class TestFakeChannelWiseDequantizeMaxAbsOpTwoScales(OpTest):
Z
Zhen Wang 已提交
74
    def set_args(self):
75 76
        self.quant_bits = [8, 8]
        self.activation_scale = 0.7861
Z
Zhen Wang 已提交
77

78 79 80
    def set_dtype(self):
        self.dtype = np.float32

Z
Zhen Wang 已提交
81 82
    def setUp(self):
        self.set_args()
83
        self.set_dtype()
Z
Zhen Wang 已提交
84
        self.op_type = "fake_channel_wise_dequantize_max_abs"
85
        x = np.random.randn(4, 3, 64, 64).astype(self.dtype)
86
        yq, scales = channel_wise_quantize_max_abs(x, self.quant_bits[0], 1)
87 88 89
        ydq = channel_wise_dequantize_max_abs(
            yq, scales, self.quant_bits, 1, self.activation_scale
        )
Z
Zhen Wang 已提交
90 91

        self.inputs = {
92 93 94 95 96 97 98 99
            'X': yq,
            'Scales': [
                ("scales0", np.array(scales).astype(self.dtype)),
                (
                    "scales1",
                    np.array([self.activation_scale]).astype(self.dtype),
                ),
            ],
Z
Zhen Wang 已提交
100
        }
101
        self.attrs = {'quant_bits': self.quant_bits}
Z
Zhen Wang 已提交
102 103 104 105 106 107
        self.outputs = {'Out': ydq}

    def test_check_output(self):
        self.check_output()


108
class TestFakeChannelWiseDequantizeMaxAbsOpTwoScalesFloat16(
109 110
    TestFakeChannelWiseDequantizeMaxAbsOpTwoScales
):
111 112 113 114 115 116 117
    def set_dtype(self):
        self.dtype = np.float16

    def test_check_output(self):
        self.check_output(atol=1e-2)


118
class TestFakeChannelWiseDequantizeMaxAbsOpOneScale(OpTest):
Z
Zhen Wang 已提交
119
    def set_args(self):
120
        self.quant_bits = [8]
121
        self.quant_axis = 0
Z
Zhen Wang 已提交
122

123 124 125
    def set_dtype(self):
        self.dtype = np.float32

Z
Zhen Wang 已提交
126 127
    def setUp(self):
        self.set_args()
128
        self.set_dtype()
Z
Zhen Wang 已提交
129
        self.op_type = "fake_channel_wise_dequantize_max_abs"
130
        x = np.random.randn(4, 3, 64, 64).astype(self.dtype)
131 132 133 134 135 136
        yq, scales = channel_wise_quantize_max_abs(
            x, self.quant_bits[0], self.quant_axis
        )
        ydq = channel_wise_dequantize_max_abs(
            yq, scales, self.quant_bits, self.quant_axis
        )
Z
Zhen Wang 已提交
137 138 139

        self.inputs = {
            'X': yq,
140
            'Scales': [("scales0", np.array(scales).astype(self.dtype))],
Z
Zhen Wang 已提交
141
        }
142 143
        self.attrs = {
            'quant_bits': self.quant_bits,
144
            'quant_axis': self.quant_axis,
145
        }
Z
Zhen Wang 已提交
146 147 148 149 150 151
        self.outputs = {'Out': ydq}

    def test_check_output(self):
        self.check_output()


152
class TestFakeChannelWiseDequantizeMaxAbsOpOneScale1(
153 154
    TestFakeChannelWiseDequantizeMaxAbsOpOneScale
):
155 156 157 158 159
    def set_args(self):
        self.quant_bits = [8]
        self.quant_axis = 1


160
class TestFakeChannelWiseDequantizeMaxAbsOpOneScaleFloat16(
161 162
    TestFakeChannelWiseDequantizeMaxAbsOpOneScale
):
163 164 165 166 167 168 169 170
    def set_dtype(self):
        self.dtype = np.float16

    def test_check_output(self):
        self.check_output(atol=1e-2)


class TestFakeChannelWiseDequantizeMaxAbsOpOneScale1Float16(
171 172
    TestFakeChannelWiseDequantizeMaxAbsOpOneScale1
):
173 174 175 176 177 178 179
    def set_dtype(self):
        self.dtype = np.float16

    def test_check_output(self):
        self.check_output(atol=1e-2)


180 181 182
class TestFakeDequantizeMaxAbsOp(OpTest):
    def set_args(self):
        self.num_bits = 8
183
        self.max_range = math.pow(2, self.num_bits - 1) - 1
184 185 186

    def set_dtype(self):
        self.dtype = np.float32
187 188 189

    def setUp(self):
        self.set_args()
190
        self.set_dtype()
191
        self.op_type = "fake_dequantize_max_abs"
192
        x = np.random.randn(31, 65).astype(self.dtype)
193 194
        yq, scale = quantize_max_abs(x, self.max_range)
        ydq = dequantize_max_abs(yq, scale, self.max_range)
195

196
        self.inputs = {'X': yq, 'Scale': np.array(scale).astype(self.dtype)}
197
        self.attrs = {'max_range': self.max_range}
198 199 200 201 202 203
        self.outputs = {'Out': ydq}

    def test_check_output(self):
        self.check_output()


204
class TestFakeDequantizeMaxAbsOpDouble(TestFakeDequantizeMaxAbsOp):
205 206
    def set_dtype(self):
        self.dtype = np.float64
207 208 209


class TestFakeDequantizeMaxAbsOp5Bits(TestFakeDequantizeMaxAbsOp):
210 211
    def set_args(self):
        self.num_bits = 5
212
        self.max_range = math.pow(2, self.num_bits - 1) - 1
213 214 215 216 217 218 219 220


class TestFakeDequantizeMaxAbsOpFloat16(TestFakeDequantizeMaxAbsOp):
    def set_dtype(self):
        self.dtype = np.float16

    def test_check_output(self):
        self.check_output(atol=1e-2)
221 222


223 224 225 226 227 228 229 230 231 232
class TestChannelWiseDequantizeOp(OpTest):
    def set_args(self):
        self.bit_length = 8
        self.data_type = "float32"
        self.quant_axis = 0

    def setUp(self):
        self.set_args()
        self.op_type = "dequantize_linear"
        x = np.random.randn(4, 3, 64, 64).astype(self.data_type)
233 234 235 236 237 238
        yq, scale = channel_wise_quantize_max_abs(
            x, self.bit_length, self.quant_axis
        )
        ydq = channel_wise_dequantize_max_abs(
            yq, scale, self.bit_length, self.quant_axis
        )
239 240 241 242 243 244
        scale = np.array(scale).astype(self.data_type)
        zero_point = np.zeros(scale.shape, dtype="int32")
        print('TestChannelWiseDequantizeOp:')
        self.inputs = {'X': yq, 'Scale': scale, 'ZeroPoint': zero_point}
        self.attrs = {
            'bit_length': self.bit_length,
245
            'quant_axis': self.quant_axis,
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
        }
        self.outputs = {'Y': ydq}

    def test_check_output(self):
        self.check_output()


class TestChannelWiseDequantizeOp1(TestChannelWiseDequantizeOp):
    def set_args(self):
        self.bit_length = 8
        self.data_type = "float32"
        self.quant_axis = 1


class TestDequantizeOp(OpTest):
    def set_args(self):
        self.bit_length = 8
        self.quant_axis = -1
        self.max_range = math.pow(2, self.bit_length - 1) - 1
        self.data_type = "float32"

    def setUp(self):
        self.set_args()
        self.op_type = "dequantize_linear"
        x = np.random.randn(31, 65).astype(self.data_type)
        yq, scale = quantize_max_abs(x, self.max_range)
        ydq = dequantize_max_abs(yq, scale, self.max_range)
        scale = np.array(scale).astype(self.data_type)
        zero_point = np.zeros(scale.shape, dtype="int32")

        self.inputs = {'X': yq, 'Scale': scale, 'ZeroPoint': zero_point}
        self.attrs = {
            'bit_length': self.bit_length,
279
            'quant_axis': self.quant_axis,
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        }
        self.outputs = {'Y': ydq}

    def test_check_output(self):
        self.check_output()


class TestDequantizeOpDouble(TestDequantizeOp):
    def set_args(self):
        self.bit_length = 8
        self.max_range = math.pow(2, self.bit_length - 1) - 1
        self.data_type = "float64"
        self.quant_axis = -1


295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
class TestDequantizeOpHalf(TestDequantizeOp):
    def set_args(self):
        self.bit_length = 8
        self.max_range = math.pow(2, self.bit_length - 1) - 1
        self.data_type = "float16"
        self.quant_axis = -1

    def setUp(self):
        self.set_args()
        self.op_type = "dequantize_linear"
        x = np.random.randn(31, 65).astype(np.float16)
        yq, scale = quantize_max_abs(x, self.max_range)
        scale = np.array(scale).astype('float16')
        yq = np.array(yq).astype('int8')
        ydq = dequantize_max_abs(yq, scale, self.max_range)
        ydq = ydq.astype('float16')
        zero_point = np.zeros(scale.shape, dtype="int32")

        self.inputs = {'X': yq, 'Scale': scale, 'ZeroPoint': zero_point}
        self.attrs = {
            'bit_length': self.bit_length,
            'quant_axis': self.quant_axis,
        }
        self.outputs = {'Y': ydq}

    def _get_places(self):
        import paddle
        import paddle.fluid.core as core

        if core.is_compiled_with_cuda():
            place = paddle.fluid.core.CUDAPlace(0)
            if paddle.fluid.core.is_float16_supported(place):
                return [place]
            else:
                return []
        else:
            return []


334 335 336 337 338 339 340 341
class TestDequantizeOp5Bits(TestDequantizeOp):
    def set_args(self):
        self.bit_length = 5
        self.max_range = math.pow(2, self.bit_length - 1) - 1
        self.data_type = "float32"
        self.quant_axis = -1


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