test_hsigmoid_op.py 12.7 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.

15 16
from __future__ import print_function

Y
Yancey1989 已提交
17 18
import unittest
import numpy as np
J
JiabinYang 已提交
19 20
import paddle.fluid.core as core
import paddle.fluid as fluid
Y
Yancey1989 已提交
21
import math
22
from op_test import OpTest, skip_check_grad_ci
Y
Yancey1989 已提交
23

D
dzhwinter 已提交
24 25
np.random.seed(100)

Y
Yancey1989 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

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)


45
class CodeTableWithCustomTree(object):
46 47 48
    def __init__(self, path_table, path_code, index):
        self.ptable_ = path_table
        self.pcode_ = path_code
49 50 51 52 53 54 55
        self.index_ = index

    def cal_index(self, bit):
        return self.ptable_[self.index_][bit]

    def get_length(self):
        length = 0
J
JiabinYang 已提交
56
        for ele in self.ptable_[self.index_]:  # find the first -1 to stop trace
57 58 59 60 61 62 63 64 65 66 67

            if ele >= 0:
                length = length + 1
            else:
                return length
        return length

    def cal_bit(self, bit):
        return self.pcode_[self.index_][bit]


W
weixing02 已提交
68
def hsigmoid(x, w, label, bias, num_classes):
Y
Yancey1989 已提交
69 70 71 72 73 74
    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 已提交
75
    for i in range(batch_size):
W
weixing02 已提交
76
        code_table = CodeTable(num_classes, label[i])
Y
Yancey1989 已提交
77
        length = code_table.get_length()
W
weixing02 已提交
78
        for j in range(length):
Y
Yancey1989 已提交
79
            idx = code_table.cal_index(j)
J
JiabinYang 已提交
80
            pre_output[i][j] += bias[idx][0]
81 82
    for i in range(batch_size):
        code_table = CodeTable(num_classes, label[i])
W
weixing02 已提交
83
        length = code_table.get_length()
84 85 86
        for j in range(length):
            idx = code_table.cal_index(j)
            pre_output[i][j] += np.dot(w[idx], x[i])
Y
Yancey1989 已提交
87
    # clip[-40.0, 40.0]
W
weixing02 已提交
88
    pre_output = np.clip(pre_output, -40.0, 40.0)
Y
Yancey1989 已提交
89
    # out(i, 0) = \sum_j  bit(i, j) * preout(i, j)
W
weixing02 已提交
90
    for i in range(batch_size):
W
weixing02 已提交
91
        code_table = CodeTable(num_classes, label[i])
Y
Yancey1989 已提交
92 93
        length = code_table.get_length()
        sum = 0.0
W
weixing02 已提交
94
        for j in range(length):
Y
Yancey1989 已提交
95 96 97 98 99 100 101
            if code_table.cal_bit(j):
                sum += pre_output[i][j]
        out[i] = -1.0 * sum
    # soft relu
    pre_output = np.log(1 + np.exp(pre_output))
    pre_sum = pre_output.sum(1).reshape((batch_size, 1))
    out += pre_sum
102
    return pre_output, out
Y
Yancey1989 已提交
103 104


105 106
def hsigmoidWithCustomTree(x, w, path_table, path_code, label, bias,
                           num_classes):
107
    batch_size = x.shape[0]
108
    code_length = len(path_table[0])
109
    code_table = [0 for _ in range(code_length)]
J
JiabinYang 已提交
110
    # init pre_out with shape [N, code_length]
111 112 113
    pre_output = np.zeros((batch_size, code_length))
    pre_sum = np.zeros((batch_size, 1))
    out = np.zeros((batch_size, 1)).astype("float32")
114 115
    if isinstance(bias, np.ndarray):
        for i in range(batch_size):
116
            code_table = CodeTableWithCustomTree(path_table, path_code, i)
117 118 119 120
            length = code_table.get_length()
            for j in range(length):
                idx = code_table.cal_index(j)
                pre_output[i][j] += bias[idx][0]
121
    for i in range(batch_size):
122
        code_table = CodeTableWithCustomTree(path_table, path_code, i)
123 124 125 126 127 128 129 130
        length = code_table.get_length()
        for j in range(length):
            idx = code_table.cal_index(j)
            pre_output[i][j] += np.dot(w[idx], x[i])
    # clip[-40.0, 40.0]
    pre_output = np.clip(pre_output, -40.0, 40.0)
    # out(i, 0) = \sum_j  bit(i, j) * preout(i, j)
    for i in range(batch_size):
131
        code_table = CodeTableWithCustomTree(path_table, path_code, i)
132 133 134 135 136 137 138 139 140 141 142 143 144
        length = code_table.get_length()
        sum = 0.0
        for j in range(length):
            if code_table.cal_bit(j):
                sum += pre_output[i][j]
        out[i] = -1.0 * sum
    # soft relu
    pre_output = np.log(1 + np.exp(pre_output))
    pre_sum = pre_output.sum(1).reshape((batch_size, 1))
    out += pre_sum
    return pre_output, out


J
JiabinYang 已提交
145 146 147 148 149
class TestHSigmoidOp(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
        num_classes = 6
        feature_size = 8
Z
zhupengyang 已提交
150
        batch_size = 15
J
JiabinYang 已提交
151 152 153 154
        x = np.random.random((batch_size, feature_size)).astype("float32") * 2
        w = np.random.random(
            (num_classes - 1, feature_size)).astype("float32") * 2
        label = np.random.randint(0, num_classes, (batch_size, 1))
J
JiabinYang 已提交
155
        bias = np.random.random((num_classes - 1, 1)).astype("float32")
J
JiabinYang 已提交
156 157 158 159 160 161 162 163 164 165 166 167
        self.attrs = {'num_classes': num_classes, 'is_sparse': False}
        self.inputs = {'X': x, 'W': w, 'Label': label, 'Bias': bias}
        pre_output, out = hsigmoid(x, w, label, bias, num_classes)
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['Bias', 'X', 'W'], ['Out'], no_grad_set=set('Label'))


168 169 170
@skip_check_grad_ci(
    reason="For 'TestHSigmoidOpSparse', check_grad is 'TestHSigmoidOpWithSparseGrad'."
)
J
JiabinYang 已提交
171 172 173 174 175 176 177 178 179
class TestHSigmoidOpSparse(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
        num_classes = 6  #using 1,2,3,4,5,6 to build a huffman tree and select 1,2,5,6 as sample
        feature_size = 8
        batch_size = 4
        x = np.random.random((batch_size, feature_size)).astype("float32")
        w = np.random.random((num_classes - 1, feature_size)).astype("float32")
        label = np.array([0, 1, 4, 5])
180
        path_table = np.array(
J
JiabinYang 已提交
181 182 183
            [(0, 2, -1, -1, -1), (0, 1, 3, -1, -1), (0, 1, 4, -1, -1),
             (0, 2, -1, -1,
              -1)])  #np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
184
        path_code = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1), (
J
JiabinYang 已提交
185
            1, 0, 0, -1, -1), (0, 1, -1, -1, -1)])  #np.array to store 
J
JiabinYang 已提交
186
        bias = np.random.random((num_classes - 1, 1)).astype("float32")
J
JiabinYang 已提交
187 188 189 190
        self.attrs = {'num_classes': num_classes, 'is_sparse': True}
        self.inputs = {
            'X': x,
            'W': w,
191
            'PathTable': path_table,
192
            'PathCode': path_code,
J
JiabinYang 已提交
193 194 195
            'Label': label,
            'Bias': bias
        }
196 197
        pre_output, out = hsigmoidWithCustomTree(x, w, path_table, path_code,
                                                 label, bias, num_classes)
J
JiabinYang 已提交
198 199 200 201 202 203 204 205 206
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
        self.check_output()


class TestHSigmoidOpWithSparseGrad(unittest.TestCase):
    def hs_net_conf(self, is_sparse):
        input_word = fluid.layers.data(name="x", shape=[1], dtype='int64')
207 208 209 210
        path_table = fluid.layers.data(
            name='path_table', shape=[3], dtype='int64')
        path_code = fluid.layers.data(
            name='path_code', shape=[3], dtype='int64')
J
JiabinYang 已提交
211
        label = fluid.layers.data(name='label', shape=[1], dtype='int64')
J
JiabinYang 已提交
212

213
        data_list = [input_word, path_table, path_code, label]
J
JiabinYang 已提交
214 215 216

        emb = fluid.layers.embedding(
            input=input_word,
J
JiabinYang 已提交
217
            is_sparse=is_sparse,
J
JiabinYang 已提交
218 219 220 221
            size=[3, 3],
            param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
                scale=1 / math.sqrt(3))))

J
JiabinYang 已提交
222 223
        cost = fluid.layers.hsigmoid(
            input=emb,
J
JiabinYang 已提交
224
            label=label,
225
            bias_attr=True,
226
            num_classes=3,
227 228 229
            path_table=path_table,
            path_code=path_code,
            is_custom=True,
J
JiabinYang 已提交
230
            is_sparse=is_sparse)
J
JiabinYang 已提交
231 232 233 234 235

        avg_cost = fluid.layers.reduce_mean(cost)

        return avg_cost, data_list

J
JiabinYang 已提交
236 237 238 239 240
    def training_test(self, is_sparse):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            start_up = fluid.default_startup_program()
            start_up.random_seed = 1  # Fix random seed
            x = np.arange(6).reshape(6)
241 242
            path_table = np.array([(1, 2, -1), (1, 2, -1)])
            path_code = np.array([(1, 0, -1), (0, 0, -1)])
J
JiabinYang 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255
            label = np.array([1, 4])

            loss, data_list = self.hs_net_conf(is_sparse)
            optimizer = fluid.optimizer.SGD(learning_rate=1e-3)
            optimizer.minimize(loss)

            main_program = fluid.default_main_program()
            place = fluid.CPUPlace()
            feeder = fluid.DataFeeder(feed_list=data_list, place=place)
            exe = fluid.Executor(place)

            exe.run(start_up)
            result = list()
J
JiabinYang 已提交
256
            for i in range(10):
257 258
                data = [([[x[i % 2]]], [list(path_table[i % 2])],
                         [list(path_code[i % 2])], [label[i % 2]])]
J
JiabinYang 已提交
259

J
JiabinYang 已提交
260 261 262
                loss_val = exe.run(main_program,
                                   feed=feeder.feed(data),
                                   fetch_list=[loss])
J
JiabinYang 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
                result.append(loss_val)
        return result

    def test_hs_grad_with_sparse(self):
        dense_result = self.training_test(is_sparse=False)
        sparse_result = self.training_test(is_sparse=True)
        assert (dense_result == sparse_result)


class TestHSigmoidOpWithCostumTree(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
        num_classes = 6  #using 1,2,3,4,5,6 to build a huffman tree and select 1,2,5,6 as sample
        feature_size = 8
        batch_size = 4
        x = np.random.random((batch_size, feature_size)).astype("float32") * 2
        w = np.random.random(
            (num_classes - 1, feature_size)).astype("float32") * 2
        label = np.array([0, 1, 4, 5])
282
        path_table = np.array(
J
JiabinYang 已提交
283 284 285
            [(0, 2, -1, -1, -1), (0, 1, 3, -1, -1), (0, 1, 4, -1, -1),
             (0, 2, -1, -1,
              -1)])  #np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
286
        path_code = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1), (
J
JiabinYang 已提交
287
            1, 0, 0, -1, -1), (0, 1, -1, -1, -1)])  #np.array to store 
J
JiabinYang 已提交
288
        bias = np.random.random((num_classes - 1, 1)).astype("float32")
J
JiabinYang 已提交
289 290 291 292
        self.attrs = {'num_classes': num_classes, 'is_sparse': False}
        self.inputs = {
            'X': x,
            'W': w,
293
            'PathTable': path_table,
294
            'PathCode': path_code,
J
JiabinYang 已提交
295 296 297
            'Label': label,
            'Bias': bias
        }
298 299
        pre_output, out = hsigmoidWithCustomTree(x, w, path_table, path_code,
                                                 label, bias, num_classes)
J
JiabinYang 已提交
300 301 302 303 304 305 306 307
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['Bias', 'X', 'W'], ['Out'], no_grad_set=set('Label'))

Y
Yancey1989 已提交
308

309 310 311 312 313 314 315 316 317 318
class TestHSigmoidOpWithCostumTreeWithoutBias(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
        num_classes = 6  #using 1,2,3,4,5,6 to build a huffman tree and select 1,2,5,6 as sample
        feature_size = 8
        batch_size = 4
        x = np.random.random((batch_size, feature_size)).astype("float32") * 2
        w = np.random.random(
            (num_classes - 1, feature_size)).astype("float32") * 2
        label = np.array([0, 1, 4, 5])
319
        path_table = np.array(
320 321 322
            [(0, 2, -1, -1, -1), (0, 1, 3, -1, -1), (0, 1, 4, -1, -1),
             (0, 2, -1, -1,
              -1)])  #np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
323
        path_code = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1), (
324 325 326 327 328 329
            1, 0, 0, -1, -1), (0, 1, -1, -1, -1)])  #np.array to store 
        # bias = np.random.random((num_classes - 1, 1)).astype("float32")
        self.attrs = {'num_classes': num_classes, 'is_sparse': False}
        self.inputs = {
            'X': x,
            'W': w,
330
            'PathTable': path_table,
331
            'PathCode': path_code,
332 333 334 335 336
            'Label': label,
        }
        pre_output, out = hsigmoidWithCustomTree(
            x=x,
            w=w,
337 338
            path_table=path_table,
            path_code=path_code,
339 340 341 342 343 344 345 346 347 348 349 350
            label=label,
            bias=None,
            num_classes=num_classes)
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X', 'W'], ['Out'], no_grad_set=set('Label'))


Y
Yancey1989 已提交
351 352
if __name__ == '__main__':
    unittest.main()