test_fake_dequantize_op.py 2.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 22


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


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


class TestFakeDequantizeMaxAbsOp(OpTest):
    def set_args(self):
        self.num_bits = 8
37 38
        self.max_range = math.pow(2, self.num_bits - 1) - 1
        self.data_type = "float32"
39 40 41 42

    def setUp(self):
        self.set_args()
        self.op_type = "fake_dequantize_max_abs"
43 44 45
        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)
46

47 48
        self.inputs = {'X': yq, 'Scale': np.array(scale).astype(self.data_type)}
        self.attrs = {'max_range': self.max_range}
49 50 51 52 53 54
        self.outputs = {'Out': ydq}

    def test_check_output(self):
        self.check_output()


55 56 57 58 59 60 61 62
class TestFakeDequantizeMaxAbsOpDouble(TestFakeDequantizeMaxAbsOp):
    def set_args(self):
        self.num_bits = 8
        self.max_range = math.pow(2, self.num_bits - 1) - 1
        self.data_type = "float64"


class TestFakeDequantizeMaxAbsOp5Bits(TestFakeDequantizeMaxAbsOp):
63 64
    def set_args(self):
        self.num_bits = 5
65 66
        self.max_range = math.pow(2, self.num_bits - 1) - 1
        self.data_type = "float32"
67 68 69 70


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