test_hsigmoid_op.py 26.5 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
L
Leo Chen 已提交
17
import paddle
J
JiabinYang 已提交
18 19
import paddle.fluid.core as core
import paddle.fluid as fluid
20
import paddle.nn.functional as F
21
from paddle.fluid import Program, program_guard
22
import paddle.fluid.initializer as I
Y
Yancey1989 已提交
23
import math
24
from op_test import OpTest, skip_check_grad_ci
Y
Yancey1989 已提交
25

26
paddle.enable_static()
D
dzhwinter 已提交
27 28
np.random.seed(100)

Y
Yancey1989 已提交
29 30 31 32 33 34

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


class CodeTable(object):
35

Y
Yancey1989 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48
    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)


49
class CodeTableWithCustomTree(object):
50

51 52 53
    def __init__(self, path_table, path_code, index):
        self.ptable_ = path_table
        self.pcode_ = path_code
54 55 56 57 58 59 60
        self.index_ = index

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

    def get_length(self):
        length = 0
J
JiabinYang 已提交
61
        for ele in self.ptable_[self.index_]:  # find the first -1 to stop trace
62 63 64 65 66 67 68 69 70 71
            if ele >= 0:
                length = length + 1
            else:
                return length
        return length

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


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


109 110
def hsigmoid_grad(x, w, label, bias, num_classes):
    batch_size = x.shape[0]
111 112 113
    dx = np.zeros(x.shape).astype('float64')
    dw = np.zeros(w.shape).astype('float64')
    db = np.zeros(bias.shape).astype('float64')
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    for i in range(batch_size):
        code_table = CodeTable(num_classes, label[i])
        length = code_table.get_length()
        for j in range(length):
            idx = code_table.cal_index(j)
            t = 1 / (1 + np.exp(-(np.dot(w[idx], x[i]) + bias[idx])))
            dx[i] = dx[i] + t * w[idx]
            dw[idx] += t * x[i]
            db[idx] += t
            if code_table.cal_bit(j):
                dx[i] = dx[i] - w[idx]
                dw[idx] -= x[i]
                db[idx] -= 1
    dx /= batch_size
    dw /= batch_size
    db /= batch_size
    return [dx, dw, db]


133 134
def hsigmoidWithCustomTree(x, w, path_table, path_code, label, bias,
                           num_classes):
135
    batch_size = x.shape[0]
136
    code_length = len(path_table[0])
137
    code_table = [0 for _ in range(code_length)]
J
JiabinYang 已提交
138
    # init pre_out with shape [N, code_length]
139 140 141
    pre_output = np.zeros((batch_size, code_length)).astype('float64')
    pre_sum = np.zeros((batch_size, 1)).astype('float64')
    out = np.zeros((batch_size, 1)).astype('float64')
142 143
    if isinstance(bias, np.ndarray):
        for i in range(batch_size):
144
            code_table = CodeTableWithCustomTree(path_table, path_code, i)
145 146 147 148
            length = code_table.get_length()
            for j in range(length):
                idx = code_table.cal_index(j)
                pre_output[i][j] += bias[idx][0]
149
    for i in range(batch_size):
150
        code_table = CodeTableWithCustomTree(path_table, path_code, i)
151 152 153 154 155 156 157 158
        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):
159
        code_table = CodeTableWithCustomTree(path_table, path_code, i)
160 161 162 163 164 165 166 167 168 169 170 171 172
        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


173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
def python_api(input,
               weight,
               label,
               path_table=None,
               path_code=None,
               bias=None,
               num_classes=-1,
               is_sparse=False,
               remote_prefetch=False):
    assert is_sparse == remote_prefetch, "is_sparse is equal to remote_prefetch in dygraph."
    return paddle.nn.functional.hsigmoid_loss(input, label, num_classes, weight,
                                              bias, path_table, path_code,
                                              is_sparse)


python_out_sig = ["Out"]


J
JiabinYang 已提交
191
class TestHSigmoidOp(OpTest):
192

J
JiabinYang 已提交
193 194
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
195 196
        self.python_api = python_api
        self.python_out_sig = python_out_sig
197 198 199
        num_classes = 101
        feature_size = 5
        batch_size = 20
200 201 202 203 204 205 206
        x = np.random.uniform(-1, 1,
                              (batch_size, feature_size)).astype('float64')
        w = np.random.uniform(-1, 1,
                              (num_classes - 1, feature_size)).astype('float64')
        label = np.random.randint(0, num_classes,
                                  (batch_size, 1)).astype('int64')
        bias = np.random.uniform(-1, 1, (num_classes - 1, 1)).astype('float64')
J
JiabinYang 已提交
207 208 209 210
        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}
211
        self.user_grads = hsigmoid_grad(x, w, label, bias, num_classes)
J
JiabinYang 已提交
212 213

    def test_check_output(self):
214
        self.check_output(check_eager=True)
J
JiabinYang 已提交
215 216

    def test_check_grad(self):
217
        self.check_grad(['X', 'W', 'Bias'], ['Out'],
218 219
                        user_defined_grads=self.user_grads,
                        check_eager=True)
J
JiabinYang 已提交
220 221


222
@skip_check_grad_ci(
223 224
    reason=
    "For 'TestHSigmoidOpSparse', check_grad is separately calculated by 'TestHSigmoidOpWithSparseGrad'."
225
)
J
JiabinYang 已提交
226
class TestHSigmoidOpSparse(OpTest):
227

J
JiabinYang 已提交
228 229
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
230 231
        self.python_api = python_api
        self.python_out_sig = python_out_sig
J
JiabinYang 已提交
232 233 234
        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
235 236
        x = np.random.random((batch_size, feature_size))
        w = np.random.random((num_classes - 1, feature_size))
237 238
        label = np.array([0, 1, 4, 5]).astype('int64')
        path_table = np.array([
239 240
            (0, 2, -1, -1, -1), (0, 1, 3, -1, -1), (0, 1, 4, -1, -1),
            (0, 2, -1, -1, -1)
241 242
        ]).astype(
            'int64')  #np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
243 244 245
        path_code = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1),
                              (1, 0, 0, -1, -1), (0, 1, -1, -1, -1)
                              ]).astype('int64')  #np.array to store
246
        bias = np.random.random((num_classes - 1, 1))
J
JiabinYang 已提交
247 248 249 250
        self.attrs = {'num_classes': num_classes, 'is_sparse': True}
        self.inputs = {
            'X': x,
            'W': w,
251
            'PathTable': path_table,
252
            'PathCode': path_code,
J
JiabinYang 已提交
253 254 255
            'Label': label,
            'Bias': bias
        }
256 257
        pre_output, out = hsigmoidWithCustomTree(x, w, path_table, path_code,
                                                 label, bias, num_classes)
J
JiabinYang 已提交
258 259 260
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
261
        self.check_output(check_eager=True)
J
JiabinYang 已提交
262 263 264


class TestHSigmoidOpWithSparseGrad(unittest.TestCase):
265

J
JiabinYang 已提交
266 267
    def hs_net_conf(self, is_sparse):
        input_word = fluid.layers.data(name="x", shape=[1], dtype='int64')
268 269 270 271 272 273
        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 已提交
274
        label = fluid.layers.data(name='label', shape=[1], dtype='int64')
J
JiabinYang 已提交
275

276
        data_list = [input_word, path_table, path_code, label]
J
JiabinYang 已提交
277 278 279

        emb = fluid.layers.embedding(
            input=input_word,
J
JiabinYang 已提交
280
            is_sparse=is_sparse,
J
JiabinYang 已提交
281 282 283 284
            size=[3, 3],
            param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
                scale=1 / math.sqrt(3))))

285 286 287 288 289 290 291 292
        cost = fluid.layers.hsigmoid(input=emb,
                                     label=label,
                                     bias_attr=True,
                                     num_classes=3,
                                     path_table=path_table,
                                     path_code=path_code,
                                     is_custom=True,
                                     is_sparse=is_sparse)
J
JiabinYang 已提交
293 294 295 296 297

        avg_cost = fluid.layers.reduce_mean(cost)

        return avg_cost, data_list

J
JiabinYang 已提交
298 299
    def training_test(self, is_sparse):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
C
cnn 已提交
300
            paddle.seed(1)
J
JiabinYang 已提交
301 302
            start_up = fluid.default_startup_program()
            x = np.arange(6).reshape(6)
303 304 305
            path_table = np.array([(1, 2, -1), (1, 2, -1)]).astype('int64')
            path_code = np.array([(1, 0, -1), (0, 0, -1)]).astype('int64')
            label = np.array([1, 4]).astype('int64')
J
JiabinYang 已提交
306 307 308 309 310 311 312 313 314 315 316 317

            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 已提交
318
            for i in range(10):
319 320
                data = [([[x[i % 2]]], [list(path_table[i % 2])],
                         [list(path_code[i % 2])], [label[i % 2]])]
J
JiabinYang 已提交
321

J
JiabinYang 已提交
322 323 324
                loss_val = exe.run(main_program,
                                   feed=feeder.feed(data),
                                   fetch_list=[loss])
J
JiabinYang 已提交
325 326 327 328 329 330 331 332 333
                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)


334
@skip_check_grad_ci(
335 336
    reason=
    "[skip shape check] The huffman tree is structed separately. It will be complicated if use large shape."
337
)
J
JiabinYang 已提交
338
class TestHSigmoidOpWithCostumTree(OpTest):
339

J
JiabinYang 已提交
340 341
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
342 343
        self.python_api = python_api
        self.python_out_sig = python_out_sig
J
JiabinYang 已提交
344 345 346
        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
347 348
        x = np.random.uniform(-1, 1, (batch_size, feature_size))
        w = np.random.uniform(-1, 1, (num_classes - 1, feature_size))
349 350
        label = np.array([0, 1, 4, 5]).astype('int64')
        path_table = np.array([
351 352
            (0, 2, -1, -1, -1), (0, 1, 3, -1, -1), (0, 1, 4, -1, -1),
            (0, 2, -1, -1, -1)
353 354
        ]).astype(
            'int64')  #np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
355 356 357
        path_code = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1),
                              (1, 0, 0, -1, -1), (0, 1, -1, -1, -1)
                              ]).astype('int64')  #np.array to store
358
        bias = np.random.random((num_classes - 1, 1))
J
JiabinYang 已提交
359 360 361 362
        self.attrs = {'num_classes': num_classes, 'is_sparse': False}
        self.inputs = {
            'X': x,
            'W': w,
363
            'PathTable': path_table,
364
            'PathCode': path_code,
J
JiabinYang 已提交
365 366 367
            'Label': label,
            'Bias': bias
        }
368 369
        pre_output, out = hsigmoidWithCustomTree(x, w, path_table, path_code,
                                                 label, bias, num_classes)
J
JiabinYang 已提交
370 371 372
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
373
        self.check_output(check_eager=True)
J
JiabinYang 已提交
374 375

    def test_check_grad(self):
376 377 378
        self.check_grad(['Bias', 'X', 'W'], ['Out'],
                        no_grad_set=set('Label'),
                        check_eager=True)
J
JiabinYang 已提交
379

Y
Yancey1989 已提交
380

381
@skip_check_grad_ci(
382 383
    reason=
    "[skip shape check] The huffman tree is structed separately. It will be complicated if use large shape."
384
)
385
class TestHSigmoidOpWithCostumTreeWithoutBias(OpTest):
386

387 388
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
389 390
        self.python_api = python_api
        self.python_out_sig = python_out_sig
391 392 393
        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
394 395
        x = np.random.uniform(-1, 1, (batch_size, feature_size))
        w = np.random.uniform(-1, 1, (num_classes - 1, feature_size))
396 397
        label = np.array([0, 1, 4, 5]).astype('int64')
        path_table = np.array([
398 399
            (0, 2, -1, -1, -1), (0, 1, 3, -1, -1), (0, 1, 4, -1, -1),
            (0, 2, -1, -1, -1)
400 401
        ]).astype(
            'int64')  #np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
402 403 404
        path_code = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1),
                              (1, 0, 0, -1, -1), (0, 1, -1, -1, -1)
                              ]).astype('int64')  #np.array to store
405 406 407 408 409
        # 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,
410
            'PathTable': path_table,
411
            'PathCode': path_code,
412 413
            'Label': label,
        }
414 415 416 417 418 419 420
        pre_output, out = hsigmoidWithCustomTree(x=x,
                                                 w=w,
                                                 path_table=path_table,
                                                 path_code=path_code,
                                                 label=label,
                                                 bias=None,
                                                 num_classes=num_classes)
421 422 423
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
424
        self.check_output(check_eager=True)
425 426

    def test_check_grad(self):
427 428 429
        self.check_grad(['X', 'W'], ['Out'],
                        no_grad_set=set('Label'),
                        check_eager=True)
430 431


432 433 434 435 436 437 438 439 440 441 442 443 444 445
class TestHSigmoidLossAPI(unittest.TestCase):
    # test paddle.nn.functional.hsigmoid_loss, paddle.nn.HSigmoidLoss
    def setUp(self):
        self.dtype = 'float32'
        self.batch_size = 4
        self.feature_size = 6
        self.num_classes = 8
        self.is_custom = False
        self.place = paddle.CPUPlace()

        paddle.set_default_dtype(self.dtype)

        self.x_np = np.random.uniform(
            -1, 1, [self.batch_size, self.feature_size]).astype(self.dtype)
446 447 448
        self.labels_np = np.random.randint(self.num_classes,
                                           size=(self.batch_size, 1),
                                           dtype='int64')
449 450
        self.weight_np = np.random.uniform(
            -1, 1, [self.num_classes - 1, self.feature_size]).astype(self.dtype)
451 452
        self.bias_np = np.random.uniform(
            -1, 1, (self.num_classes - 1, )).astype(self.dtype)
453 454 455 456 457 458 459
        self.path_table_np = None
        self.path_code_np = None
        _, self.out_np = hsigmoid(self.x_np, self.weight_np, self.labels_np,
                                  self.bias_np, self.num_classes)
        self.set_attrs()

        if self.is_custom:
460 461 462 463 464 465
            _, self.out_np = hsigmoidWithCustomTree(self.x_np, self.weight_np,
                                                    self.path_table_np,
                                                    self.path_code_np,
                                                    self.labels_np,
                                                    self.bias_np.reshape(-1, 1),
                                                    self.num_classes)
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

    def set_attrs(self):
        pass

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        labels = paddle.to_tensor(self.labels_np)
        weight = paddle.to_tensor(self.weight_np)
        bias = paddle.to_tensor(self.bias_np)
        path_table = None
        path_code = None
        if self.is_custom:
            path_table = paddle.to_tensor(self.path_table_np)
            path_code = paddle.to_tensor(self.path_code_np)
        out1 = F.hsigmoid_loss(x, labels, self.num_classes, weight, bias,
                               path_table, path_code)

        weight_attr = I.NumpyArrayInitializer(self.weight_np)
        bias_attr = I.NumpyArrayInitializer(self.bias_np)
        m = paddle.nn.HSigmoidLoss(self.feature_size, self.num_classes,
                                   weight_attr, bias_attr, self.is_custom)
        out2 = m(x, labels, path_table, path_code)

        for out in [out1, out2]:
491
            np.testing.assert_allclose(self.out_np, out.numpy(), rtol=1e-05)
492 493 494 495 496 497 498 499 500
        paddle.enable_static()

    def test_static_api(self):
        train_program = paddle.static.Program()
        startup_program = paddle.static.Program()
        with paddle.static.program_guard(train_program, startup_program):
            x = paddle.static.data('x', [-1, self.feature_size])
            labels = paddle.static.data('labels', [-1, 1], 'int64')
            weight = paddle.static.data('weight', [-1, self.feature_size])
501 502 503
            bias = paddle.static.data('bias', [
                -1,
            ])
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
            path_table = None
            path_code = None
            if self.is_custom:
                path_table = paddle.static.data('path_table', [-1, -1], 'int64')
                path_code = paddle.static.data('path_code', [-1, -1], 'int64')
            out1 = F.hsigmoid_loss(x, labels, self.num_classes, weight, bias,
                                   path_table, path_code)

            weight_attr = paddle.framework.ParamAttr(
                initializer=I.NumpyArrayInitializer(self.weight_np))
            bias_attr = paddle.framework.ParamAttr(
                initializer=I.NumpyArrayInitializer(self.bias_np))
            m = paddle.nn.HSigmoidLoss(self.feature_size, self.num_classes,
                                       weight_attr, bias_attr, self.is_custom)
            out2 = m(x, labels, path_table, path_code)

            exe = paddle.static.Executor(self.place)
            exe.run(startup_program)
            feed_dict = {
                'x': self.x_np,
                'labels': self.labels_np,
                'weight': self.weight_np,
                'bias': self.bias_np
            }
            if self.is_custom:
                feed_dict["path_code"] = self.path_code_np
                feed_dict["path_table"] = self.path_table_np
            ret1, ret2 = exe.run(train_program,
                                 feed=feed_dict,
                                 fetch_list=[out1, out2])

            for ret in [ret1, ret2]:
536
                np.testing.assert_allclose(self.out_np, ret, rtol=1e-05)
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

    def test_fluid_api(self):
        train_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(train_program, startup_program):
            x = fluid.data('x', [-1, self.feature_size])
            labels = fluid.data('labels', [-1, 1], 'int64')
            path_table = None
            path_code = None
            if self.is_custom:
                path_table = fluid.data('path_table', [-1, -1], 'int64')
                path_code = fluid.data('path_code', [-1, -1], 'int64')
            weight_attr = I.NumpyArrayInitializer(self.weight_np)
            bias_attr = I.NumpyArrayInitializer(self.bias_np)
            out = fluid.layers.hsigmoid(x, labels, self.num_classes,
                                        weight_attr, bias_attr, 'out',
                                        path_table, path_code, self.is_custom)

            exe = fluid.Executor(self.place)
            exe.run(startup_program)
            feed_dict = {'x': self.x_np, 'labels': self.labels_np}
            if self.is_custom:
                feed_dict["path_code"] = self.path_code_np
                feed_dict["path_table"] = self.path_table_np
            ret, = exe.run(train_program, feed=feed_dict, fetch_list=[out])

563
            np.testing.assert_allclose(ret, self.out_np, rtol=1e-05)
564

565
    def test_errors(self):
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
            # test paddle.nn.HSigmoidLoss
            self.assertRaises(ValueError, paddle.nn.HSigmoidLoss, 6, 1)

            # test paddle.nn.functional.hsigmoid_loss
            x = paddle.static.data('x', [4, 6])
            label = paddle.static.data('label', [4, 1], 'int64')
            weight = paddle.static.data('weight', [7, 6])
            bias = paddle.static.data('bias', [7])

            x_int32 = paddle.static.data('x_int32', [4, 6], 'int32')
            self.assertRaises(TypeError, F.hsigmoid_loss, x_int32, label, 8,
                              weight)

            label_float32 = paddle.static.data('label_float32', [4, 1],
                                               'float32')
            self.assertRaises(TypeError, F.hsigmoid_loss, x, label_float32, 8,
                              weight)

            weight_int32 = paddle.static.data('weight_int32', [7, 6], 'int32')
            self.assertRaises(TypeError, F.hsigmoid_loss, x, label, 8,
                              weight_int32)

            bias_int32 = paddle.static.data('bias_int32', [7], 'int32')
591 592 593 594 595 596 597
            self.assertRaises(TypeError,
                              F.hsigmoid_loss,
                              x,
                              label,
                              8,
                              weight,
                              bias=bias_int32)
598 599 600

            path_table_int32 = paddle.static.data('path_table_int32', [7],
                                                  'int32')
601 602 603 604 605 606 607
            self.assertRaises(TypeError,
                              F.hsigmoid_loss,
                              x,
                              label,
                              8,
                              weight,
                              path_table=path_table_int32)
608 609 610

            path_code_int32 = paddle.static.data('path_code_int32', [7],
                                                 'int32')
611 612 613 614 615 616 617
            self.assertRaises(TypeError,
                              F.hsigmoid_loss,
                              x,
                              label,
                              8,
                              weight,
                              path_code=path_code_int32)
618

L
Linjie Chen 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632
        # test paddle.nn.HSigmoidLoss
        paddle.disable_static(self.place)
        x_arr = np.array([], dtype=np.float32)
        x = paddle.to_tensor(np.reshape(x_arr, (100000, 0)))
        label = paddle.to_tensor(0, dtype='int64')
        self.assertRaises(ValueError, paddle.nn.HSigmoidLoss, x, label)

        # test paddle.nn.functional.hsigmoid_loss
        x = paddle.to_tensor(np.reshape(x_arr, (10, 0)), dtype='float32')
        label = paddle.to_tensor([], dtype='int64')
        weight = paddle.to_tensor([], dtype='float32')
        self.assertRaises(ValueError, F.hsigmoid_loss, x, label, 0, weight)
        paddle.enable_static()

633
        # test paddle.fluid.layers.hsigmoid
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
        with program_guard(Program()):
            label = fluid.data('label', [4, 1], 'int64')
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hsigmoid, 1, label, 2)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[4, 3], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.hsigmoid, x_int32, label,
                              2)
            # support the input dtype is float32
            x_fp32 = fluid.data(name='x_fp32', shape=[4, 3], dtype='float32')
            fluid.layers.hsigmoid(x_fp32, label, 2)

            # The label type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hsigmoid, x_fp32, 1, 2)
            # The label dtype must be int64.
            label_int32 = fluid.data('label_int32', [4, 1], 'int32')
            self.assertRaises(TypeError, fluid.layers.hsigmoid, x_fp32,
                              label_int32, 2)


654
class TestHSigmoidLossAPICustom(TestHSigmoidLossAPI):
655

656 657
    def set_attrs(self):
        self.is_custom = True
658 659 660 661 662 663
        self.path_table_np = np.array([(0, 2, -1, -1, -1), (0, 1, 3, -1, -1),
                                       (0, 1, 4, -1, -1),
                                       (0, 2, -1, -1, -1)]).astype(np.int64)
        self.path_code_np = np.array([(0, 0, -1, -1, -1), (1, 1, 1, -1, -1),
                                      (1, 0, 0, -1, -1),
                                      (0, 1, -1, -1, -1)]).astype(np.int64)
664 665 666 667 668

    def test_errors(self):
        pass


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