test_hsigmoid_op.py 25.3 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
import math
Y
Yancey1989 已提交
16
import unittest
17

Y
Yancey1989 已提交
18
import numpy as np
W
wanghuancoder 已提交
19
from eager_op_test import OpTest, skip_check_grad_ci
20

L
Leo Chen 已提交
21
import paddle
22
import paddle.nn.functional as F
23
from paddle import fluid
Y
Yancey1989 已提交
24

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

Y
Yancey1989 已提交
28 29 30 31 32

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


33
class CodeTable:
Y
Yancey1989 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46
    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)


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

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

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

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


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


106 107
def hsigmoid_grad(x, w, label, bias, num_classes):
    batch_size = x.shape[0]
108 109 110
    dx = np.zeros(x.shape).astype('float64')
    dw = np.zeros(w.shape).astype('float64')
    db = np.zeros(bias.shape).astype('float64')
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    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]


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


171 172 173
def python_api(
    input,
    label,
174 175
    weight,
    bias=None,
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    path_table=None,
    path_code=None,
    num_classes=-1,
    is_sparse=False,
):
    return paddle.nn.functional.hsigmoid_loss(
        input,
        label,
        num_classes,
        weight,
        bias,
        path_table,
        path_code,
        is_sparse,
    )
191 192 193 194 195


python_out_sig = ["Out"]


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

    def test_check_output(self):
W
wanghuancoder 已提交
221
        self.check_output()
J
JiabinYang 已提交
222 223

    def test_check_grad(self):
224 225 226 227 228
        self.check_grad(
            ['X', 'W', 'Bias'],
            ['Out'],
            user_defined_grads=self.user_grads,
        )
J
JiabinYang 已提交
229 230


231
@skip_check_grad_ci(
232
    reason="For 'TestHSigmoidOpSparse', check_grad is separately calculated by 'TestHSigmoidOpWithSparseGrad'."
233
)
J
JiabinYang 已提交
234 235 236
class TestHSigmoidOpSparse(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
237 238
        self.python_api = python_api
        self.python_out_sig = python_out_sig
239
        num_classes = 6  # using 1,2,3,4,5,6 to build a huffman tree and select 1,2,5,6 as sample
J
JiabinYang 已提交
240 241
        feature_size = 8
        batch_size = 4
242 243
        x = np.random.random((batch_size, feature_size))
        w = np.random.random((num_classes - 1, feature_size))
244
        label = np.array([0, 1, 4, 5]).astype('int64')
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        path_table = np.array(
            [
                (0, 2, -1, -1, -1),
                (0, 1, 3, -1, -1),
                (0, 1, 4, -1, -1),
                (0, 2, -1, -1, -1),
            ]
        ).astype(
            'int64'
        )  # np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
        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
265
        bias = np.random.random((num_classes - 1, 1))
J
JiabinYang 已提交
266 267 268 269
        self.attrs = {'num_classes': num_classes, 'is_sparse': True}
        self.inputs = {
            'X': x,
            'W': w,
270
            'PathTable': path_table,
271
            'PathCode': path_code,
J
JiabinYang 已提交
272
            'Label': label,
273
            'Bias': bias,
J
JiabinYang 已提交
274
        }
275 276 277
        pre_output, out = hsigmoidWithCustomTree(
            x, w, path_table, path_code, label, bias, num_classes
        )
J
JiabinYang 已提交
278 279 280
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
W
wanghuancoder 已提交
281
        self.check_output()
J
JiabinYang 已提交
282 283 284 285


class TestHSigmoidOpWithSparseGrad(unittest.TestCase):
    def hs_net_conf(self, is_sparse):
G
GGBond8488 已提交
286 287 288
        input_word = paddle.static.data(name="x", shape=[-1, 1], dtype='int64')
        path_table = paddle.static.data(
            name='path_table', shape=[-1, 3], dtype='int64'
289
        )
G
GGBond8488 已提交
290 291
        path_code = paddle.static.data(
            name='path_code', shape=[-1, 3], dtype='int64'
292
        )
G
GGBond8488 已提交
293
        label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64')
J
JiabinYang 已提交
294

295
        data_list = [input_word, path_table, path_code, label]
J
JiabinYang 已提交
296 297 298

        emb = fluid.layers.embedding(
            input=input_word,
J
JiabinYang 已提交
299
            is_sparse=is_sparse,
J
JiabinYang 已提交
300
            size=[3, 3],
301
            param_attr=fluid.ParamAttr(
302
                initializer=paddle.nn.initializer.Normal(std=1 / math.sqrt(3))
303 304 305
            ),
        )

306 307 308 309 310 311 312 313 314
        loss = paddle.nn.HSigmoidLoss(
            feature_size=emb.shape[1],
            num_classes=3,
            bias_attr=True,
            is_custom=True,
            is_sparse=is_sparse,
        )

        cost = loss(
315 316 317 318 319
            input=emb,
            label=label,
            path_table=path_table,
            path_code=path_code,
        )
J
JiabinYang 已提交
320

321
        avg_cost = paddle.mean(cost)
J
JiabinYang 已提交
322 323 324

        return avg_cost, data_list

J
JiabinYang 已提交
325 326
    def training_test(self, is_sparse):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
C
cnn 已提交
327
            paddle.seed(1)
J
JiabinYang 已提交
328 329
            start_up = fluid.default_startup_program()
            x = np.arange(6).reshape(6)
330 331 332
            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 已提交
333 334 335 336 337 338 339 340 341 342 343

            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)
344
            result = []
J
JiabinYang 已提交
345
            for i in range(10):
346 347 348 349 350 351 352 353 354 355 356 357
                data = [
                    (
                        [[x[i % 2]]],
                        [list(path_table[i % 2])],
                        [list(path_code[i % 2])],
                        [label[i % 2]],
                    )
                ]

                loss_val = exe.run(
                    main_program, feed=feeder.feed(data), fetch_list=[loss]
                )
J
JiabinYang 已提交
358 359 360 361 362 363
                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)
364
        assert dense_result == sparse_result
J
JiabinYang 已提交
365 366


367
@skip_check_grad_ci(
368
    reason="[skip shape check] The huffman tree is structed separately. It will be complicated if use large shape."
369
)
J
JiabinYang 已提交
370 371 372
class TestHSigmoidOpWithCostumTree(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
373 374
        self.python_api = python_api
        self.python_out_sig = python_out_sig
375
        num_classes = 6  # using 1,2,3,4,5,6 to build a huffman tree and select 1,2,5,6 as sample
J
JiabinYang 已提交
376 377
        feature_size = 8
        batch_size = 4
378 379
        x = np.random.uniform(-1, 1, (batch_size, feature_size))
        w = np.random.uniform(-1, 1, (num_classes - 1, feature_size))
380
        label = np.array([0, 1, 4, 5]).astype('int64')
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        path_table = np.array(
            [
                (0, 2, -1, -1, -1),
                (0, 1, 3, -1, -1),
                (0, 1, 4, -1, -1),
                (0, 2, -1, -1, -1),
            ]
        ).astype(
            'int64'
        )  # np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
        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
401
        bias = np.random.random((num_classes - 1, 1))
J
JiabinYang 已提交
402 403 404 405
        self.attrs = {'num_classes': num_classes, 'is_sparse': False}
        self.inputs = {
            'X': x,
            'W': w,
406
            'PathTable': path_table,
407
            'PathCode': path_code,
J
JiabinYang 已提交
408
            'Label': label,
409
            'Bias': bias,
J
JiabinYang 已提交
410
        }
411 412 413
        pre_output, out = hsigmoidWithCustomTree(
            x, w, path_table, path_code, label, bias, num_classes
        )
J
JiabinYang 已提交
414 415 416
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
W
wanghuancoder 已提交
417
        self.check_output()
J
JiabinYang 已提交
418 419

    def test_check_grad(self):
420 421 422 423 424
        self.check_grad(
            ['Bias', 'X', 'W'],
            ['Out'],
            no_grad_set=set('Label'),
        )
J
JiabinYang 已提交
425

Y
Yancey1989 已提交
426

427
@skip_check_grad_ci(
428
    reason="[skip shape check] The huffman tree is structed separately. It will be complicated if use large shape."
429
)
430 431 432
class TestHSigmoidOpWithCostumTreeWithoutBias(OpTest):
    def setUp(self):
        self.op_type = "hierarchical_sigmoid"
433 434
        self.python_api = python_api
        self.python_out_sig = python_out_sig
435
        num_classes = 6  # using 1,2,3,4,5,6 to build a huffman tree and select 1,2,5,6 as sample
436 437
        feature_size = 8
        batch_size = 4
438 439
        x = np.random.uniform(-1, 1, (batch_size, feature_size))
        w = np.random.uniform(-1, 1, (num_classes - 1, feature_size))
440
        label = np.array([0, 1, 4, 5]).astype('int64')
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        path_table = np.array(
            [
                (0, 2, -1, -1, -1),
                (0, 1, 3, -1, -1),
                (0, 1, 4, -1, -1),
                (0, 2, -1, -1, -1),
            ]
        ).astype(
            'int64'
        )  # np.array to store 1,2,5,6s' non-leaf path(root -> leaf)
        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
461 462 463 464 465
        # 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,
466
            'PathTable': path_table,
467
            'PathCode': path_code,
468 469
            'Label': label,
        }
470 471 472 473 474 475 476 477 478
        pre_output, out = hsigmoidWithCustomTree(
            x=x,
            w=w,
            path_table=path_table,
            path_code=path_code,
            label=label,
            bias=None,
            num_classes=num_classes,
        )
479 480 481
        self.outputs = {'PreOut': pre_output, 'Out': out}

    def test_check_output(self):
W
wanghuancoder 已提交
482
        self.check_output()
483 484

    def test_check_grad(self):
W
wanghuancoder 已提交
485
        self.check_grad(['X', 'W'], ['Out'], no_grad_set=set('Label'))
486 487


488 489 490 491 492 493 494 495 496 497 498 499 500
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(
501 502 503 504 505
            -1, 1, [self.batch_size, self.feature_size]
        ).astype(self.dtype)
        self.labels_np = np.random.randint(
            self.num_classes, size=(self.batch_size, 1), dtype='int64'
        )
506
        self.weight_np = np.random.uniform(
507 508 509 510 511
            -1, 1, [self.num_classes - 1, self.feature_size]
        ).astype(self.dtype)
        self.bias_np = np.random.uniform(-1, 1, (self.num_classes - 1,)).astype(
            self.dtype
        )
512 513
        self.path_table_np = None
        self.path_code_np = None
514 515 516 517 518 519 520
        _, self.out_np = hsigmoid(
            self.x_np,
            self.weight_np,
            self.labels_np,
            self.bias_np,
            self.num_classes,
        )
521 522 523
        self.set_attrs()

        if self.is_custom:
524 525 526 527 528 529 530 531 532
            _, 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,
            )
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

    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)
548 549 550
        out1 = F.hsigmoid_loss(
            x, labels, self.num_classes, weight, bias, path_table, path_code
        )
551

552 553
        weight_attr = paddle.nn.initializer.Assign(self.weight_np)
        bias_attr = paddle.nn.initializer.Assign(self.bias_np)
554 555 556 557 558 559 560
        m = paddle.nn.HSigmoidLoss(
            self.feature_size,
            self.num_classes,
            weight_attr,
            bias_attr,
            self.is_custom,
        )
561 562 563
        out2 = m(x, labels, path_table, path_code)

        for out in [out1, out2]:
564
            np.testing.assert_allclose(self.out_np, out.numpy(), rtol=1e-05)
565 566 567 568 569 570 571 572 573
        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])
574 575 576 577 578 579
            bias = paddle.static.data(
                'bias',
                [
                    -1,
                ],
            )
580 581 582 583 584
            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')
585 586 587
            out1 = F.hsigmoid_loss(
                x, labels, self.num_classes, weight, bias, path_table, path_code
            )
588 589

            weight_attr = paddle.framework.ParamAttr(
590
                initializer=paddle.nn.initializer.Assign(self.weight_np)
591
            )
592
            bias_attr = paddle.framework.ParamAttr(
593
                initializer=paddle.nn.initializer.Assign(self.bias_np)
594 595 596 597 598 599 600 601
            )
            m = paddle.nn.HSigmoidLoss(
                self.feature_size,
                self.num_classes,
                weight_attr,
                bias_attr,
                self.is_custom,
            )
602 603 604 605 606 607 608 609
            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,
610
                'bias': self.bias_np,
611 612 613 614
            }
            if self.is_custom:
                feed_dict["path_code"] = self.path_code_np
                feed_dict["path_table"] = self.path_table_np
615 616 617
            ret1, ret2 = exe.run(
                train_program, feed=feed_dict, fetch_list=[out1, out2]
            )
618 619

            for ret in [ret1, ret2]:
620
                np.testing.assert_allclose(self.out_np, ret, rtol=1e-05)
621 622 623 624 625

    def test_fluid_api(self):
        train_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(train_program, startup_program):
626 627
            x = paddle.static.data('x', [-1, self.feature_size])
            labels = paddle.static.data('labels', [-1, 1], 'int64')
628 629 630
            path_table = None
            path_code = None
            if self.is_custom:
631 632
                path_table = paddle.static.data('path_table', [-1, -1], 'int64')
                path_code = paddle.static.data('path_code', [-1, -1], 'int64')
633 634
            weight_attr = paddle.nn.initializer.Assign(self.weight_np)
            bias_attr = paddle.nn.initializer.Assign(self.bias_np)
635 636 637 638 639 640 641 642 643 644 645 646 647
            loss = paddle.nn.HSigmoidLoss(
                feature_size=x.shape[1],
                num_classes=self.num_classes,
                weight_attr=weight_attr,
                bias_attr=bias_attr,
                is_custom=self.is_custom,
                name='out',
            )
            out = loss(
                input=x,
                label=labels,
                path_table=path_table,
                path_code=path_code,
648
            )
649 650 651 652 653 654 655

            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
656
            (ret,) = exe.run(train_program, feed=feed_dict, fetch_list=[out])
657

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

660
    def test_errors(self):
661 662 663
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
664 665 666 667 668 669 670 671 672 673
            # 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')
674 675 676
            self.assertRaises(
                TypeError, F.hsigmoid_loss, x_int32, label, 8, weight
            )
677

678 679 680 681 682 683
            label_float32 = paddle.static.data(
                'label_float32', [4, 1], 'float32'
            )
            self.assertRaises(
                TypeError, F.hsigmoid_loss, x, label_float32, 8, weight
            )
684 685

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

            bias_int32 = paddle.static.data('bias_int32', [7], 'int32')
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
            self.assertRaises(
                TypeError, F.hsigmoid_loss, x, label, 8, weight, bias=bias_int32
            )

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

            path_code_int32 = paddle.static.data(
                'path_code_int32', [7], 'int32'
            )
            self.assertRaises(
                TypeError,
                F.hsigmoid_loss,
                x,
                label,
                8,
                weight,
                path_code=path_code_int32,
            )
720

L
Linjie Chen 已提交
721 722 723 724 725 726 727 728 729 730 731
        # 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')
L
Linjie Chen 已提交
732 733 734 735 736
        self.assertRaises(ValueError, F.hsigmoid_loss, x, label, 2, weight)

        x = paddle.to_tensor(np.reshape(x_arr, [1, 0, 0, 1]), dtype='float32')
        label = paddle.to_tensor(np.reshape(x_arr, [1, 1, 0]), dtype='int64')
        weight = paddle.to_tensor([], dtype='float32')
L
Linjie Chen 已提交
737 738 739
        self.assertRaises(ValueError, F.hsigmoid_loss, x, label, 0, weight)
        paddle.enable_static()

740

741 742 743
class TestHSigmoidLossAPICustom(TestHSigmoidLossAPI):
    def set_attrs(self):
        self.is_custom = True
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        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)
760 761 762 763 764

    def test_errors(self):
        pass


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