test_hsigmoid_op.py 3.4 KB
Newer Older
W
weixing02 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
W
weixing02 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

Y
Yancey1989 已提交
15 16
import unittest
import numpy as np
Y
Yancey1989 已提交
17
import math
W
weixing02 已提交
18
from op_test import OpTest
Y
Yancey1989 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38


def find_latest_set(num):
    return 1 + int(math.floor(math.log(num, 2)))


class CodeTable(object):
    def __init__(self, num_classes, code):
        self.c = num_classes + code

    def cal_index(self, bit):
        return (self.c >> (bit + 1)) - 1

    def get_length(self):
        return find_latest_set(self.c) - 1

    def cal_bit(self, bit):
        return self.c & (1 << bit)


W
weixing02 已提交
39
def hsigmoid(x, w, label, bias, num_classes):
W
weixing02 已提交
40
    global pre_output
Y
Yancey1989 已提交
41 42 43 44 45 46
    batch_size = x.shape[0]
    code_length = find_latest_set(num_classes - 1)
    code_table = [0 for _ in range(code_length)]
    pre_output = np.zeros((batch_size, code_length))
    pre_sum = np.zeros((batch_size, 1))
    out = np.zeros((batch_size, 1)).astype("float32")
W
weixing02 已提交
47
    for i in range(batch_size):
W
weixing02 已提交
48
        code_table = CodeTable(num_classes, label[i])
Y
Yancey1989 已提交
49
        length = code_table.get_length()
W
weixing02 已提交
50
        for j in range(length):
Y
Yancey1989 已提交
51 52
            idx = code_table.cal_index(j)
            pre_output[i][j] += bias[0][idx]
W
weixing02 已提交
53
    for j in range(batch_size):
W
weixing02 已提交
54
        code_table = CodeTable(num_classes, label[j])
W
weixing02 已提交
55 56 57 58 59 60 61
        length = code_table.get_length()
        for k in range(length):
            idx = code_table.cal_index(k)
            sum = 0.0
            for l in range(x.shape[1]):
                sum += w[idx][l] * x[j][l]
            pre_output[j][k] += sum
Y
Yancey1989 已提交
62
    # clip[-40.0, 40.0]
W
weixing02 已提交
63
    pre_output = np.clip(pre_output, -40.0, 40.0)
Y
Yancey1989 已提交
64
    # out(i, 0) = \sum_j  bit(i, j) * preout(i, j)
W
weixing02 已提交
65
    for i in range(batch_size):
W
weixing02 已提交
66
        code_table = CodeTable(num_classes, label[i])
Y
Yancey1989 已提交
67 68
        length = code_table.get_length()
        sum = 0.0
W
weixing02 已提交
69
        for j in range(length):
Y
Yancey1989 已提交
70 71 72 73 74 75 76 77 78
            if code_table.cal_bit(j):
                sum += pre_output[i][j]
        out[i] = -1.0 * sum
    # soft relu
    np.clip(pre_output, -40.0, 40.0)
    pre_output = np.log(1 + np.exp(pre_output))
    pre_sum = pre_output.sum(1).reshape((batch_size, 1))
    out += pre_sum
    return out
Y
Yancey1989 已提交
79 80 81 82


class TestHSigmoidOp(OpTest):
    def setUp(self):
Y
Yancey1989 已提交
83
        self.op_type = "hierarchical_sigmoid"
W
weixing02 已提交
84 85 86
        num_classes = 4
        embded_size = 1
        batch_size = 1
Y
Yancey1989 已提交
87
        x = np.random.random((batch_size, embded_size)).astype("float32")
W
weixing02 已提交
88
        w = np.random.random((num_classes - 1, embded_size)).astype("float32")
W
weixing02 已提交
89
        label = np.random.randint(0, num_classes, batch_size)
Y
Yancey1989 已提交
90
        bias = np.random.random((1, num_classes - 1)).astype("float32")
Y
Yancey1989 已提交
91
        self.attrs = {'num_classes': num_classes}
W
weixing02 已提交
92 93
        self.inputs = {'X': x, 'W': w, 'Label': label, 'Bias': bias}
        out = hsigmoid(x, w, label, bias, num_classes)
W
weixing02 已提交
94
        self.outputs = {'PreOut': pre_output, 'Out': out}
Y
Yancey1989 已提交
95 96 97 98 99

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
W
weixing02 已提交
100
        self.check_grad(['Bias', 'X', 'W'], 'Out', no_grad_set=set('Label'))
Y
Yancey1989 已提交
101 102 103 104


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