test_fake_dequantize_op.py 9.1 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 16
from __future__ import print_function

17 18 19
import unittest
import numpy as np
import math
20
from op_test import OpTest
21
import paddle.fluid.core as core
22 23


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


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


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


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


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

82 83 84
    def set_dtype(self):
        self.dtype = np.float32

Z
Zhen Wang 已提交
85 86
    def setUp(self):
        self.set_args()
87
        self.set_dtype()
Z
Zhen Wang 已提交
88
        self.op_type = "fake_channel_wise_dequantize_max_abs"
89
        x = np.random.randn(4, 3, 64, 64).astype(self.dtype)
90 91
        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,
92
                                              self.activation_scale)
Z
Zhen Wang 已提交
93 94 95

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

    def test_check_output(self):
        self.check_output()


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

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


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

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

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

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

    def test_check_output(self):
        self.check_output()


148 149 150 151 152 153 154
class TestFakeChannelWiseDequantizeMaxAbsOpOneScale1(
        TestFakeChannelWiseDequantizeMaxAbsOpOneScale):
    def set_args(self):
        self.quant_bits = [8]
        self.quant_axis = 1


155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
class TestFakeChannelWiseDequantizeMaxAbsOpOneScaleFloat16(
        TestFakeChannelWiseDequantizeMaxAbsOpOneScale):
    def set_dtype(self):
        self.dtype = np.float16

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


class TestFakeChannelWiseDequantizeMaxAbsOpOneScale1Float16(
        TestFakeChannelWiseDequantizeMaxAbsOpOneScale1):
    def set_dtype(self):
        self.dtype = np.float16

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


173 174 175
class TestFakeDequantizeMaxAbsOp(OpTest):
    def set_args(self):
        self.num_bits = 8
176
        self.max_range = math.pow(2, self.num_bits - 1) - 1
177 178 179

    def set_dtype(self):
        self.dtype = np.float32
180 181 182

    def setUp(self):
        self.set_args()
183
        self.set_dtype()
184
        self.op_type = "fake_dequantize_max_abs"
185
        x = np.random.randn(31, 65).astype(self.dtype)
186 187
        yq, scale = quantize_max_abs(x, self.max_range)
        ydq = dequantize_max_abs(yq, scale, self.max_range)
188

189
        self.inputs = {'X': yq, 'Scale': np.array(scale).astype(self.dtype)}
190
        self.attrs = {'max_range': self.max_range}
191 192 193 194 195 196
        self.outputs = {'Out': ydq}

    def test_check_output(self):
        self.check_output()


197
class TestFakeDequantizeMaxAbsOpDouble(TestFakeDequantizeMaxAbsOp):
198 199
    def set_dtype(self):
        self.dtype = np.float64
200 201 202


class TestFakeDequantizeMaxAbsOp5Bits(TestFakeDequantizeMaxAbsOp):
203 204
    def set_args(self):
        self.num_bits = 5
205
        self.max_range = math.pow(2, self.num_bits - 1) - 1
206 207 208 209 210 211 212 213


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

    def test_check_output(self):
        self.check_output(atol=1e-2)
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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
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)
        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):
    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,
            'quant_axis': self.quant_axis
        }
        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


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


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