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

import unittest
import numpy as np
import math
18
from op_test import OpTest
19 20


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


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


32 33
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 已提交
34
    scales = []
35 36 37
    y = x.copy()
    max_range = math.pow(2, quant_bit - 1) - 1
    if quant_axis == 0:
38
        for i in range(x.shape[0]):
39 40 41 42 43 44 45 46
            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 已提交
47 48 49
    return y, scales


50 51 52
def channel_wise_dequantize_max_abs(x,
                                    scales,
                                    quant_bits,
53
                                    quant_axis,
54
                                    activation_scale=None):
55 56 57 58
    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
59
    else:
60 61 62
        max_range = math.pow(2, quant_bits - 1) - 1
    y = x.copy()
    if quant_axis == 0:
63
        for i in range(x.shape[0]):
64 65 66 67 68 69 70
            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 已提交
71 72 73
    return y


74
class TestFakeChannelWiseDequantizeMaxAbsOpTwoScales(OpTest):
75

Z
Zhen Wang 已提交
76
    def set_args(self):
77 78
        self.quant_bits = [8, 8]
        self.activation_scale = 0.7861
Z
Zhen Wang 已提交
79

80 81 82
    def set_dtype(self):
        self.dtype = np.float32

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

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

    def test_check_output(self):
        self.check_output()


106 107
class TestFakeChannelWiseDequantizeMaxAbsOpTwoScalesFloat16(
        TestFakeChannelWiseDequantizeMaxAbsOpTwoScales):
108

109 110 111 112 113 114 115
    def set_dtype(self):
        self.dtype = np.float16

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


116
class TestFakeChannelWiseDequantizeMaxAbsOpOneScale(OpTest):
117

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

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

Z
Zhen Wang 已提交
125 126
    def setUp(self):
        self.set_args()
127
        self.set_dtype()
Z
Zhen Wang 已提交
128
        self.op_type = "fake_channel_wise_dequantize_max_abs"
129
        x = np.random.randn(4, 3, 64, 64).astype(self.dtype)
130 131 132 133
        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 已提交
134 135 136

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

    def test_check_output(self):
        self.check_output()


149 150
class TestFakeChannelWiseDequantizeMaxAbsOpOneScale1(
        TestFakeChannelWiseDequantizeMaxAbsOpOneScale):
151

152 153 154 155 156
    def set_args(self):
        self.quant_bits = [8]
        self.quant_axis = 1


157 158
class TestFakeChannelWiseDequantizeMaxAbsOpOneScaleFloat16(
        TestFakeChannelWiseDequantizeMaxAbsOpOneScale):
159

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

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


class TestFakeChannelWiseDequantizeMaxAbsOpOneScale1Float16(
        TestFakeChannelWiseDequantizeMaxAbsOpOneScale1):
169

170 171 172 173 174 175 176
    def set_dtype(self):
        self.dtype = np.float16

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


177
class TestFakeDequantizeMaxAbsOp(OpTest):
178

179 180
    def set_args(self):
        self.num_bits = 8
181
        self.max_range = math.pow(2, self.num_bits - 1) - 1
182 183 184

    def set_dtype(self):
        self.dtype = np.float32
185 186 187

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

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

    def test_check_output(self):
        self.check_output()


202
class TestFakeDequantizeMaxAbsOpDouble(TestFakeDequantizeMaxAbsOp):
203

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


class TestFakeDequantizeMaxAbsOp5Bits(TestFakeDequantizeMaxAbsOp):
209

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


class TestFakeDequantizeMaxAbsOpFloat16(TestFakeDequantizeMaxAbsOp):
216

217 218 219 220 221
    def set_dtype(self):
        self.dtype = np.float16

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


224
class TestChannelWiseDequantizeOp(OpTest):
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
    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)
        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)
        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,
            'quant_axis': self.quant_axis
        }
        self.outputs = {'Y': ydq}

    def test_check_output(self):
        self.check_output()


class TestChannelWiseDequantizeOp1(TestChannelWiseDequantizeOp):
254

255 256 257 258 259 260 261
    def set_args(self):
        self.bit_length = 8
        self.data_type = "float32"
        self.quant_axis = 1


class TestDequantizeOp(OpTest):
262

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    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,
            'quant_axis': self.quant_axis
        }
        self.outputs = {'Y': ydq}

    def test_check_output(self):
        self.check_output()


class TestDequantizeOpDouble(TestDequantizeOp):
290

291 292 293 294 295 296 297 298
    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


class TestDequantizeOp5Bits(TestDequantizeOp):
299

300 301 302 303 304 305 306
    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


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