test_activation_op.py 99.9 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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
from __future__ import print_function
Q
qijun 已提交
16
import unittest
J
joejiong 已提交
17

Q
qijun 已提交
18
import numpy as np
C
Clementine 已提交
19
from scipy.special import expit, erf
J
joejiong 已提交
20

21
from paddle.fluid.tests.unittests.op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
22
import paddle
23
import paddle.nn as nn
24
import paddle.nn.functional as F
J
joejiong 已提交
25 26
import paddle.fluid as fluid
import paddle.fluid.core as core
27
from paddle.fluid import compiler, Program, program_guard
Q
qijun 已提交
28

29 30
paddle.enable_static()

Q
qijun 已提交
31

32
class TestSqrtOpError(unittest.TestCase):
Z
Zhaolong Xing 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of sqrt op must be Variable or numpy.ndarray.
            in1 = 1
            self.assertRaises(TypeError, fluid.layers.sqrt, in1)
            # The input dtype of sqrt op must be float16, float32, float64.
            in2 = fluid.layers.data(
                name='input2', shape=[12, 10], dtype="int32")
            self.assertRaises(TypeError, fluid.layers.sqrt, in2)

            in3 = fluid.layers.data(
                name='input3', shape=[12, 10], dtype="float16")
            fluid.layers.sqrt(x=in3)


C
chengduo 已提交
48
class TestActivation(OpTest):
Q
qijun 已提交
49 50
    def setUp(self):
        self.op_type = "exp"
51
        self.init_dtype()
52
        self.init_kernel_type()
53

54
        np.random.seed(2049)
55 56 57 58 59
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.exp(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
Q
qijun 已提交
60 61 62 63 64

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
65 66
        if self.dtype == np.float16:
            return
67
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
68

69
    def init_dtype(self):
70
        self.dtype = np.float64
71

72 73 74
    def init_kernel_type(self):
        pass

Q
qijun 已提交
75

R
ronnywang 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
class TestExpm1(TestActivation):
    def setUp(self):
        self.op_type = "expm1"
        self.init_dtype()

        np.random.seed(2049)
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.expm1(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


class TestExpm1API(unittest.TestCase):
    def init_dtype(self):
        self.dtype = 'float64'
        self.shape = [11, 17]

    def setUp(self):
        self.init_dtype()
        self.x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
        self.out_ref = np.expm1(self.x)

        self.place = [paddle.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.place.append(paddle.CUDAPlace(0))

    def test_static_api(self):
        paddle.enable_static()

        def run(place):
            with paddle.static.program_guard(paddle.static.Program()):
                X = paddle.fluid.data('X', self.shape, dtype=self.dtype)
                out = paddle.expm1(X)
                exe = paddle.static.Executor(place)
                res = exe.run(feed={'X': self.x})
            for r in res:
                self.assertEqual(np.allclose(self.out_ref, r), True)

        for place in self.place:
            run(place)

    def test_dygraph_api(self):
        def run(place):
            paddle.disable_static(place)
            X = paddle.to_tensor(self.x)
            out = paddle.expm1(X)
            self.assertEqual(np.allclose(self.out_ref, out.numpy()), True)
            paddle.enable_static()

        for place in self.place:
            run(place)

    def test_errors(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            X = paddle.fluid.data('X', self.shape, dtype='int32')
            self.assertRaises(TypeError, paddle.expm1, X)
        # The input dtype must be float16, float32, float64.


140 141 142
class TestParameter(object):
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
W
WuHaobo 已提交
143
            np_x = np.array([0.1])
144
            data = fluid.layers.data(name="X", shape=[1])
W
WuHaobo 已提交
145
            out = eval("paddle.%s(data, name='Y')" % self.op_type)
146 147
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
W
WuHaobo 已提交
148 149 150
            result, = exe.run(feed={"X": np_x}, fetch_list=[out])
            expected = eval("np.%s(np_x)" % self.op_type)
            self.assertEqual(result, expected)
151 152 153 154 155 156 157

    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
            z = eval("paddle.%s(x).numpy()" % self.op_type)
            z_expected = eval("np.%s(np_x)" % self.op_type)
158 159 160 161 162
            # ROCM platform will fail in assertEqual
            if core.is_compiled_with_rocm():
                self.assertTrue(np.allclose(z, z_expected))
            else:
                self.assertEqual(z, z_expected)
163 164


C
chengduo 已提交
165
class TestSigmoid(TestActivation):
Q
qijun 已提交
166 167
    def setUp(self):
        self.op_type = "sigmoid"
168 169
        self.init_dtype()

170
        np.random.seed(1024)
171 172 173 174 175
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = 1 / (1 + np.exp(-x))

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
Q
qijun 已提交
176

177 178 179
    def init_dtype(self):
        self.dtype = np.float32

180
    def test_check_grad(self):
181 182 183 184
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.01)

185

M
minghaoBD 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
class TestSilu(TestActivation):
    def setUp(self):
        self.op_type = "silu"
        self.init_dtype()

        np.random.seed(1024)
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = x / (np.exp(-x) + 1)

        self.inputs = {'X': x}
        self.outputs = {'Out': out}

    def init_dtype(self):
        self.dtype = np.float32

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


class TestSiluAPI(unittest.TestCase):
    # test paddle.nn.Silu, paddle.nn.functional.silu
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.fluid.data('X', [11, 17])
            out1 = F.silu(x)
            m = paddle.nn.Silu()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = self.x_np / (1 + np.exp(-self.x_np))
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.silu(x)
        m = paddle.nn.Silu()
        out2 = m(x)
        out_ref = self.x_np / (1 + np.exp(-self.x_np))
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.silu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32')
            self.assertRaises(TypeError, F.silu, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16')
            F.silu(x_fp16)


C
chengduo 已提交
252
class TestLogSigmoid(TestActivation):
253 254
    def setUp(self):
        self.op_type = "logsigmoid"
255 256
        self.init_dtype()

257
        np.random.seed(2048)
258 259 260
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = np.log(1 / (1 + np.exp(-x)))

261
        self.inputs = {'X': x}
262
        self.outputs = {'Out': out}
263 264

    def test_check_grad(self):
265 266
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
267
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
268 269


270
class TestLogSigmoidAPI(unittest.TestCase):
271
    # test paddle.nn.LogSigmoid, paddle.nn.functional.log_sigmoid
272
    def setUp(self):
273
        np.random.seed(1024)
274
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
J
joejiong 已提交
275
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
276 277 278
            else paddle.CPUPlace()

    def test_static_api(self):
279
        paddle.enable_static()
280
        with paddle.static.program_guard(paddle.static.Program()):
281
            x = paddle.fluid.data('X', [11, 17])
282
            out1 = F.log_sigmoid(x)
283 284 285 286 287 288
            m = paddle.nn.LogSigmoid()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in res:
289
            self.assertTrue(np.allclose(out_ref, r))
290 291 292 293

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
294
        out1 = F.log_sigmoid(x)
295 296 297 298
        m = paddle.nn.LogSigmoid()
        out2 = m(x)
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in [out1, out2]:
299
            self.assertTrue(np.allclose(out_ref, r.numpy()))
300 301
        paddle.enable_static()

302
    def test_fluid_api(self):
303
        paddle.enable_static()
304
        with paddle.static.program_guard(paddle.static.Program()):
305
            x = paddle.fluid.data('X', [11, 17])
306 307 308 309 310 311
            out = paddle.fluid.layers.logsigmoid(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        self.assertTrue(np.allclose(out_ref, res[0]))

312
    def test_errors(self):
313
        paddle.enable_static()
314 315
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
316
            self.assertRaises(TypeError, F.log_sigmoid, 1)
317
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
318 319
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32')
320
            self.assertRaises(TypeError, F.log_sigmoid, x_int32)
321
            # support the input dtype is float16
J
joejiong 已提交
322 323
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16')
324
            F.log_sigmoid(x_fp16)
325 326


327
class TestTanh(TestActivation, TestParameter):
328 329
    def setUp(self):
        self.op_type = "tanh"
330
        self.init_dtype()
331
        np.random.seed(1024)
332 333 334 335 336
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.tanh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
337 338

    def test_check_grad(self):
339 340
        if self.dtype == np.float16:
            return
341
        self.check_grad(['X'], 'Out')
342

343 344 345 346 347 348
    def init_dtype(self):
        #TODO If dtype is float64, the output (Out) has diff at CPUPlace
        # when using and not using inplace. Therefore, set dtype as float32
        # for now.
        self.dtype = np.float32

349

W
WangXi 已提交
350 351 352 353
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
354
        np.random.seed(1024)
W
WangXi 已提交
355
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
J
joejiong 已提交
356
        self.place = paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
W
WangXi 已提交
357
            else paddle.CPUPlace()
358 359 360 361
        self.executed_api()

    def executed_api(self):
        self.tanh = F.tanh
W
WangXi 已提交
362 363

    def test_static_api(self):
364
        paddle.enable_static()
W
WangXi 已提交
365
        with paddle.static.program_guard(paddle.static.Program()):
366
            x = paddle.fluid.data('X', [10, 12], self.dtype)
367
            out1 = self.tanh(x)
W
WangXi 已提交
368 369 370 371 372 373 374 375 376 377
            th = paddle.nn.Tanh()
            out2 = th(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = np.tanh(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
378
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
379 380 381 382 383 384 385 386 387 388
        out1 = F.tanh(x)
        out2 = paddle.tanh(x)
        th = paddle.nn.Tanh()
        out3 = th(x)
        out_ref = np.tanh(self.x_np)
        for r in [out1, out2, out3]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
389
        paddle.enable_static()
W
WangXi 已提交
390 391 392 393 394 395 396 397 398
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12], self.dtype)
            out = fluid.layers.tanh(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = np.tanh(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
399
        paddle.enable_static()
W
WangXi 已提交
400 401
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
402
            self.assertRaises(TypeError, self.tanh, 1)
W
WangXi 已提交
403
            # The input dtype must be float16, float32.
J
joejiong 已提交
404 405
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
406
            self.assertRaises(TypeError, self.tanh, x_int32)
W
WangXi 已提交
407
            # support the input dtype is float16
J
joejiong 已提交
408 409
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
410 411 412 413 414 415 416
            self.tanh(x_fp16)


class TestTanhInplaceAPI(TestTanhAPI):
    # test paddle.tanh_
    def executed_api(self):
        self.tanh = paddle.tanh_
W
WangXi 已提交
417 418


419
class TestAtan(TestActivation, TestParameter):
420 421 422 423
    def setUp(self):
        self.op_type = "atan"
        self.init_dtype()

424
        np.random.seed(1024)
425 426 427 428 429 430 431 432 433
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.arctan(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
434
        self.check_grad(['X'], 'Out')
435

W
WuHaobo 已提交
436 437 438 439 440 441 442 443 444 445 446
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
            np_x = np.array([0.1])
            data = fluid.layers.data(name="X", shape=[1])
            out = paddle.atan(data, name='Y')
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(feed={"X": np_x}, fetch_list=[out])
            expected = np.arctan(np_x)
            self.assertEqual(result, expected)

447 448 449 450 451 452 453 454
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
            z = paddle.atan(x).numpy()
            z_expected = np.arctan(np_x)
            self.assertEqual(z, z_expected)

455

456 457 458 459 460
class TestSinh(TestActivation):
    def setUp(self):
        self.op_type = "sinh"
        self.init_dtype()

461
        np.random.seed(1024)
462 463 464 465 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 491 492 493 494 495 496 497 498 499 500 501 502 503 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
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.sinh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
            z = fluid.layers.sinh(x).numpy()
            z_expected = np.sinh(np_x)
            self.assertTrue(np.allclose(z, z_expected))

    def test_api(self):
        test_data_shape = [11, 17]
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input_x = np.random.uniform(0.1, 1,
                                        test_data_shape).astype("float32")
            data_x = fluid.layers.data(
                name="data_x",
                shape=test_data_shape,
                append_batch_size=False,
                dtype="float32")

            pd_sinh_out = fluid.layers.sinh(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
            np_sinh_res = exe.run(fluid.default_main_program(),
                                  feed={"data_x": input_x},
                                  fetch_list=[pd_sinh_out])

        expected_res = np.sinh(input_x)
        self.assertTrue(np.allclose(np_sinh_res, expected_res))

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
            input_x = np.random.uniform(0.1, 1,
                                        test_data_shape).astype("float32")
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
            loss = fluid.layers.sinh(var)
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


class TestSinhOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.sinh, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.sinh, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.sinh(x_fp16)


class TestCosh(TestActivation):
    def setUp(self):
        self.op_type = "cosh"
        self.init_dtype()

533
        np.random.seed(1024)
534 535 536 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 563 564 565 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 591 592 593 594 595 596 597 598 599
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.cosh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
            z = fluid.layers.cosh(x).numpy()
            z_expected = np.cosh(np_x)
            self.assertTrue(np.allclose(z, z_expected))

    def test_api(self):
        test_data_shape = [11, 17]
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input_x = np.random.uniform(0.1, 1,
                                        test_data_shape).astype("float32")
            data_x = fluid.layers.data(
                name="data_x",
                shape=test_data_shape,
                append_batch_size=False,
                dtype="float32")

            pd_cosh_out = paddle.cosh(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
            np_cosh_res = exe.run(fluid.default_main_program(),
                                  feed={"data_x": input_x},
                                  fetch_list=[pd_cosh_out])

        expected_res = np.cosh(input_x)
        self.assertTrue(np.allclose(np_cosh_res, expected_res))

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
            input_x = np.random.uniform(0.1, 1,
                                        test_data_shape).astype("float32")
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
            loss = fluid.layers.cosh(var)
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


class TestCoshOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.cosh, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.cosh, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.cosh(x_fp16)


600 601 602 603 604 605
def ref_tanhshrink(x):
    out = x - np.tanh(x)
    return out


class TestTanhshrink(TestActivation):
K
Kavya Srinet 已提交
606 607
    def setUp(self):
        self.op_type = "tanh_shrink"
608 609
        self.init_dtype()

610
        np.random.seed(1024)
611 612
        x = np.random.uniform(10, 20, [10, 17]).astype(self.dtype)
        out = ref_tanhshrink(x)
613

614
        self.inputs = {'X': x}
615
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
616 617

    def test_check_grad(self):
618 619
        if self.dtype == np.float16:
            return
620
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
621

622

623 624 625
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
626
        np.random.seed(1024)
627
        self.x_np = np.random.uniform(10, 20, [10, 17]).astype(np.float64)
J
joejiong 已提交
628
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
629 630 631
            else paddle.CPUPlace()

    def test_static_api(self):
632
        paddle.enable_static()
633
        with paddle.static.program_guard(paddle.static.Program()):
634
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
            out1 = F.tanhshrink(x)
            tanhshrink = paddle.nn.Tanhshrink()
            out2 = tanhshrink(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_tanhshrink(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.tanhshrink(x)
        tanhshrink = paddle.nn.Tanhshrink()
        out2 = tanhshrink(x)
        out_ref = ref_tanhshrink(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
656
        paddle.enable_static()
657 658 659 660 661 662 663 664 665
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.tanh_shrink(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_tanhshrink(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
666
        paddle.enable_static()
667 668 669 670
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.tanhshrink, 1)
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
671 672
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
673 674
            self.assertRaises(TypeError, F.tanhshrink, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
675 676
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
677 678 679
            F.tanhshrink(x_fp16)


680 681 682 683 684 685
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
686
class TestHardShrink(TestActivation):
687 688
    def setUp(self):
        self.op_type = "hard_shrink"
689 690
        self.init_dtype()

691 692
        self.threshold = 0.5
        self.set_attrs()
693
        np.random.seed(1024)
Z
zhupengyang 已提交
694
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype) * 10
695
        out = ref_hardshrink(x, self.threshold)
696

697
        self.attrs = {'threshold': self.threshold}
698
        self.inputs = {'X': x}
699
        self.outputs = {'Out': out}
700

701 702 703
    def set_attrs(self):
        pass

704
    def test_check_grad(self):
705 706
        if self.dtype == np.float16:
            return
707
        self.check_grad(['X'], 'Out')
708 709


710 711 712 713 714
class TestHardShrink_threshold_negative(TestHardShrink):
    def set_attrs(self):
        self.threshold = -0.1


715 716 717
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
718
        np.random.seed(1024)
719
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
720
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
721 722 723
            else paddle.CPUPlace()

    def test_static_api(self):
724
        paddle.enable_static()
725
        with paddle.static.program_guard(paddle.static.Program()):
726
            x = paddle.fluid.data('X', [10, 12])
727 728 729 730 731 732 733 734 735 736 737
            out1 = F.hardshrink(x)
            hd = paddle.nn.Hardshrink()
            out2 = hd(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardshrink(self.x_np, 0.5)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
738
        x = paddle.to_tensor(self.x_np)
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        out1 = F.hardshrink(x)
        hd = paddle.nn.Hardshrink()
        out2 = hd(x)
        out_ref = ref_hardshrink(self.x_np, 0.5)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

        out1 = F.hardshrink(x, 0.6)
        hd = paddle.nn.Hardshrink(0.6)
        out2 = hd(x)
        out_ref = ref_hardshrink(self.x_np, 0.6)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
755
        paddle.enable_static()
756 757 758 759 760 761 762 763
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
            out = fluid.layers.hard_shrink(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardshrink(self.x_np, 0.5)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

764
    def test_errors(self):
765
        paddle.enable_static()
766
        with paddle.static.program_guard(paddle.static.Program()):
767
            # The input type must be Variable.
768
            self.assertRaises(TypeError, F.hardshrink, 1)
769
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
770 771
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
772
            self.assertRaises(TypeError, F.hardshrink, x_int32)
773
            # support the input dtype is float16
J
joejiong 已提交
774 775
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
776
            F.hardshrink(x_fp16)
777 778


779 780 781 782 783 784 785 786 787 788 789
def ref_hardtanh(x, min=-1.0, max=1.0):
    out = np.copy(x)
    out[np.abs(x - min) < 0.005] = min + 0.02
    out[np.abs(x - max) < 0.005] = max + 0.02
    out = np.minimum(np.maximum(x, min), max)
    return out


class TestHardtanhAPI(unittest.TestCase):
    # test paddle.nn.Hardtanh, paddle.nn.functional.hardtanh
    def setUp(self):
790
        np.random.seed(1024)
791
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
J
joejiong 已提交
792
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
793 794 795
            else paddle.CPUPlace()

    def test_static_api(self):
796
        paddle.enable_static()
797
        with paddle.static.program_guard(paddle.static.Program()):
798
            x = paddle.fluid.data('X', [10, 12])
799 800 801 802 803 804 805 806 807 808 809
            out1 = F.hardtanh(x)
            m = paddle.nn.Hardtanh()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardtanh(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
810
        x = paddle.to_tensor(self.x_np)
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
        out1 = F.hardtanh(x)
        m = paddle.nn.Hardtanh()
        out2 = m(x)
        out_ref = ref_hardtanh(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

        out1 = F.hardtanh(x, -2.0, 2.0)
        m = paddle.nn.Hardtanh(-2.0, 2.0)
        out2 = m(x)
        out_ref = ref_hardtanh(self.x_np, -2.0, 2.0)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_errors(self):
827
        paddle.enable_static()
828 829 830 831
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.hardtanh, 1)
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
832 833
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
834 835
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
836 837
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
838 839 840
            F.hardtanh(x_fp16)


841 842 843 844 845 846 847 848
def ref_softshrink(x, threshold=0.5):
    out = np.copy(x)
    out = (out < -threshold) * (out + threshold) + (out > threshold) * (
        out - threshold)
    return out


class TestSoftshrink(TestActivation):
849 850
    def setUp(self):
        self.op_type = "softshrink"
851 852
        self.init_dtype()

853
        threshold = 0.8
854

855
        np.random.seed(1023)
856 857 858 859
        x = np.random.uniform(0.25, 10, [10, 12]).astype(self.dtype)
        out = ref_softshrink(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"lambda": threshold}
860
        self.outputs = {'Out': out}
861 862

    def test_check_grad(self):
863 864
        if self.dtype == np.float16:
            return
865
        self.check_grad(['X'], 'Out')
866

867

868 869 870 871
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
872
        np.random.seed(1024)
873
        self.x_np = np.random.uniform(0.25, 10, [10, 12]).astype(np.float64)
J
joejiong 已提交
874
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
875 876 877
            else paddle.CPUPlace()

    def test_static_api(self):
878
        paddle.enable_static()
879
        with paddle.static.program_guard(paddle.static.Program()):
880
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
            out1 = F.softshrink(x, self.threshold)
            softshrink = paddle.nn.Softshrink(self.threshold)
            out2 = softshrink(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_softshrink(self.x_np, self.threshold)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.softshrink(x, self.threshold)
        softshrink = paddle.nn.Softshrink(self.threshold)
        out2 = softshrink(x)
        out_ref = ref_softshrink(self.x_np, self.threshold)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
902
        paddle.enable_static()
903 904 905 906 907 908 909 910
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.softshrink(x, self.threshold)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_softshrink(self.x_np, self.threshold)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

911
    def test_errors(self):
912
        paddle.enable_static()
913
        with paddle.static.program_guard(paddle.static.Program()):
914
            # The input type must be Variable.
915
            self.assertRaises(TypeError, F.softshrink, 1)
916
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
917 918
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
919
            self.assertRaises(TypeError, F.softshrink, x_int32)
920
            # The threshold must be no less than zero
J
joejiong 已提交
921 922
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[12, 10], dtype='float32')
923
            self.assertRaises(ValueError, F.softshrink, x_fp32, -1.0)
924
            # support the input dtype is float16
J
joejiong 已提交
925 926
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
927
            F.softshrink(x_fp16)
928 929


930
class TestSqrt(TestActivation, TestParameter):
931 932
    def setUp(self):
        self.op_type = "sqrt"
933 934
        self.init_dtype()

935
        np.random.seed(1023)
936 937 938 939 940
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.sqrt(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
941 942

    def test_check_grad(self):
943 944
        if self.dtype == np.float16:
            return
945
        self.check_grad(['X'], 'Out')
946

947

Z
zhoukunsheng 已提交
948 949 950 951 952
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
        self.init_dtype()

953
        np.random.seed(1024)
Z
zhupengyang 已提交
954
        x = np.random.uniform(0.1, 1, [10, 12]).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
955 956 957 958 959 960 961 962 963 964 965
        out = 1.0 / np.sqrt(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.0005)


C
chengduo 已提交
966
class TestAbs(TestActivation):
967 968
    def setUp(self):
        self.op_type = "abs"
969 970
        self.init_dtype()

971
        np.random.seed(1024)
972
        x = np.random.uniform(-1, 1, [4, 25]).astype(self.dtype)
C
chengduo 已提交
973
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
974
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
975
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
976 977
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
978 979 980 981
        out = np.abs(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
982 983

    def test_check_grad(self):
984 985
        if self.dtype == np.float16:
            return
986
        self.check_grad(['X'], 'Out')
987

988

C
chengduo 已提交
989
class TestCeil(TestActivation):
D
dzhwinter 已提交
990 991
    def setUp(self):
        self.op_type = "ceil"
992 993
        self.init_dtype()

994
        np.random.seed(1024)
Z
zhupengyang 已提交
995
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
996 997 998 999
        out = np.ceil(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
D
dzhwinter 已提交
1000

D
dzhwinter 已提交
1001
    # The same reason with TestFloor
C
chengduo 已提交
1002
    def test_check_grad(self):
1003 1004 1005
        pass


C
chengduo 已提交
1006
class TestFloor(TestActivation):
D
dzhwinter 已提交
1007 1008
    def setUp(self):
        self.op_type = "floor"
1009 1010
        self.init_dtype()

1011
        np.random.seed(1024)
Z
zhupengyang 已提交
1012
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1013 1014 1015 1016
        out = np.floor(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
D
dzhwinter 已提交
1017

D
dzhwinter 已提交
1018
    # the gradient on floor, ceil, round is undefined.
1019
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
1020 1021
    # The same reason with TestFloor
    def test_check_grad(self):
1022 1023 1024
        pass


C
chengduo 已提交
1025
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
1026 1027
    def setUp(self):
        self.op_type = "cos"
1028 1029
        self.init_dtype()

1030
        np.random.seed(1024)
Z
zhupengyang 已提交
1031
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1032 1033 1034 1035
        out = np.cos(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
C
add sin  
chengduoZH 已提交
1036 1037

    def test_check_grad(self):
1038 1039
        if self.dtype == np.float16:
            return
1040
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
1041

1042

J
joejiong 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
class TestTan(TestActivation):
    def setUp(self):
        np.random.seed(1024)
        self.op_type = "tan"
        self.init_dtype()
        self.dtype = 'float32'
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        self.place = paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
            else paddle.CPUPlace()

        out = np.tan(self.x_np)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(self.x_np)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out_test = paddle.tan(x)
        out_ref = np.tan(self.x_np)
        self.assertTrue(np.allclose(out_ref, out_test.numpy()))
        paddle.enable_static()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.static.data('X', [10, 12], self.dtype)
            out = paddle.tan(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = np.tan(self.x_np)
        self.assertTrue(np.allclose(out_ref, res[0]))

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
            input_x = np.random.uniform(0.1, 1,
                                        test_data_shape).astype("float32")
            var = paddle.to_tensor(input_x)
            var.stop_gradient = False
            loss = paddle.tan(var)
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


1094 1095 1096 1097 1098
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()

1099
        np.random.seed(1024)
Z
zhupengyang 已提交
1100
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
1101 1102 1103 1104 1105 1106 1107 1108
        out = np.arccos(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1109
        self.check_grad(['X'], 'Out')
1110 1111


1112
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
1113 1114
    def setUp(self):
        self.op_type = "sin"
1115 1116
        self.init_dtype()

1117
        np.random.seed(1024)
Z
zhupengyang 已提交
1118
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1119 1120 1121 1122
        out = np.sin(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
C
add cos  
chengduoZH 已提交
1123 1124

    def test_check_grad(self):
1125 1126
        if self.dtype == np.float16:
            return
1127
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
1128 1129


1130 1131 1132 1133 1134
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()

1135
        np.random.seed(2048)
Z
zhupengyang 已提交
1136
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
1137 1138 1139 1140 1141 1142 1143 1144
        out = np.arcsin(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1145
        self.check_grad(['X'], 'Out')
1146 1147


C
chengduo 已提交
1148
class TestRound(TestActivation):
D
dzhwinter 已提交
1149 1150
    def setUp(self):
        self.op_type = "round"
1151 1152
        self.init_dtype()

1153
        np.random.seed(1024)
Z
zhupengyang 已提交
1154
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1155 1156 1157 1158
        out = np.round(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
D
dzhwinter 已提交
1159

C
chengduo 已提交
1160
    def test_check_grad(self):
1161 1162 1163
        pass


C
chengduo 已提交
1164
class TestRelu(TestActivation):
1165
    def setUp(self):
Q
qijun 已提交
1166
        self.op_type = "relu"
K
Kexin Zhao 已提交
1167 1168
        self.init_dtype()

1169
        np.random.seed(1024)
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        if self.dtype == np.uint16:
            x = np.random.uniform(-1, 1, [11, 17]).astype(np.float32)
            # The same reason with TestAbs
            x[np.abs(x) < 0.005] = 0.02
            out = convert_float_to_uint16(np.maximum(x, 0))
            self.inputs = {'X': convert_float_to_uint16(x)}
        else:
            x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
            # The same reason with TestAbs
            x[np.abs(x) < 0.005] = 0.02
            out = np.maximum(x, 0)
            self.inputs = {'X': x}
K
Kexin Zhao 已提交
1182 1183

        self.outputs = {'Out': out}
1184 1185

    def test_check_grad(self):
K
Kexin Zhao 已提交
1186 1187
        if self.dtype == np.float16:
            return
1188
        self.check_grad(['X'], 'Out')
A
Adam 已提交
1189 1190


1191 1192 1193
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1194
        np.random.seed(1024)
1195
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
1196
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1197
            else paddle.CPUPlace()
1198 1199 1200 1201
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1202 1203

    def test_static_api(self):
1204
        paddle.enable_static()
1205
        with paddle.static.program_guard(paddle.static.Program()):
1206
            x = paddle.fluid.data('X', [10, 12])
1207
            out1 = self.relu(x)
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
            m = paddle.nn.ReLU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = np.maximum(self.x_np, 0)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.ReLU()
1220 1221
        out1 = m(x)
        out2 = self.relu(x)
1222 1223 1224 1225 1226
        out_ref = np.maximum(self.x_np, 0)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

1227
    def test_errors(self):
1228
        paddle.enable_static()
1229
        with paddle.static.program_guard(paddle.static.Program()):
1230
            # The input type must be Variable.
1231
            self.assertRaises(TypeError, self.relu, 1)
1232
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1233 1234
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
1235
            self.assertRaises(TypeError, self.relu, x_int32)
1236
            # support the input dtype is float16
J
joejiong 已提交
1237 1238
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
1239 1240 1241 1242 1243 1244 1245
            self.relu(x_fp16)


class TestReluInplaceAPI(TestReluAPI):
    # test paddle.nn.functional.relu_
    def executed_api(self):
        self.relu = F.relu_
1246 1247


1248 1249 1250 1251 1252 1253
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1254
class TestLeakyRelu(TestActivation):
1255 1256 1257
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1258 1259 1260
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()
1261
        alpha = self.get_alpha()
A
Adam 已提交
1262

1263
        np.random.seed(1024)
A
Adam 已提交
1264 1265
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        # The same reason with TestAbs
1266 1267
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1268

1269
        self.inputs = {'X': x}
A
Adam 已提交
1270
        self.outputs = {'Out': out}
1271
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1272 1273 1274 1275

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1276
        self.check_grad(['X'], 'Out')
1277 1278


1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
class TestLeakyReluAlpha1(TestLeakyRelu):
    def get_alpha(self):
        return 2


class TestLeakyReluAlpha2(TestLeakyRelu):
    def get_alpha(self):
        return -0.01


class TestLeakyReluAlpha3(TestLeakyRelu):
    def get_alpha(self):
        return -2.0


class TestLeakyReluAPI(unittest.TestCase):
    # test paddle.nn.LeakyReLU, paddle.nn.functional.leaky_relu,
    # fluid.layers.leaky_relu
    def setUp(self):
1298
        np.random.seed(1024)
1299
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
1300
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1301 1302 1303
            else paddle.CPUPlace()

    def test_static_api(self):
1304
        paddle.enable_static()
1305
        with paddle.static.program_guard(paddle.static.Program()):
1306
            x = paddle.fluid.data('X', [10, 12])
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            out1 = F.leaky_relu(x)
            m = paddle.nn.LeakyReLU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_leaky_relu(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
1318
        x = paddle.to_tensor(self.x_np)
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
        out1 = F.leaky_relu(x)
        m = paddle.nn.LeakyReLU()
        out2 = m(x)
        out_ref = ref_leaky_relu(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

        out1 = F.leaky_relu(x, 0.6)
        m = paddle.nn.LeakyReLU(0.6)
        out2 = m(x)
        out_ref = ref_leaky_relu(self.x_np, 0.6)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
1335
        paddle.enable_static()
1336 1337 1338 1339 1340 1341 1342 1343
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
            out = fluid.layers.leaky_relu(x, 0.01)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_leaky_relu(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

1344
    def test_errors(self):
1345
        paddle.enable_static()
1346
        with paddle.static.program_guard(paddle.static.Program()):
1347
            # The input type must be Variable.
1348
            self.assertRaises(TypeError, F.leaky_relu, 1)
1349
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1350 1351
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1352 1353
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
1354 1355
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1356
            F.leaky_relu(x_fp16)
1357 1358


1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
def gelu(x, approximate):
    if approximate:
        y_ref = 0.5 * x * (1.0 + np.tanh(
            np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
    else:
        y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
    return y_ref.astype(x.dtype)


class TestGeluApproximate(TestActivation):
C
Clementine 已提交
1369 1370 1371
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1372
        approximate = True
1373
        np.random.seed(1024)
1374 1375
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
1376

1377
        self.inputs = {'X': x}
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
        self.outputs = {'Out': out}
        self.attrs = {"approximate": approximate}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


class TestGelu(TestActivation):
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
        approximate = False
1392
        np.random.seed(2048)
C
Clementine 已提交
1393
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1394
        out = gelu(x, approximate)
C
Clementine 已提交
1395

1396
        self.inputs = {'X': x}
C
Clementine 已提交
1397
        self.outputs = {'Out': out}
1398
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1399 1400 1401 1402

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1403
        self.check_grad(['X'], 'Out')
C
Clementine 已提交
1404 1405


1406 1407 1408
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1409
        np.random.seed(1024)
1410
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
J
joejiong 已提交
1411
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1412 1413 1414
            else paddle.CPUPlace()

    def test_static_api(self):
1415
        paddle.enable_static()
1416
        with paddle.static.program_guard(paddle.static.Program()):
1417
            x = paddle.fluid.data('X', [11, 17])
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
            out1 = F.gelu(x)
            m = paddle.nn.GELU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = gelu(self.x_np, False)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.gelu(x)
        m = paddle.nn.GELU()
        out2 = m(x)
        out_ref = gelu(self.x_np, False)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

        out1 = F.gelu(x, True)
        m = paddle.nn.GELU(True)
        out2 = m(x)
        out_ref = gelu(self.x_np, True)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_errors(self):
1446
        paddle.enable_static()
1447 1448 1449 1450
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.gelu, 1)
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1451 1452
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32')
1453 1454
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
1455 1456
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16')
1457 1458 1459
            F.gelu(x_fp16)


C
chengduo 已提交
1460
class TestBRelu(TestActivation):
1461 1462
    def setUp(self):
        self.op_type = "brelu"
1463 1464
        self.init_dtype()

1465
        np.random.seed(1024)
Z
zhupengyang 已提交
1466
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1467 1468
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
1469 1470
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
1471
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
1472 1473 1474
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
1475 1476 1477

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.attrs = {'t_min': t_min, 't_max': t_max}
F
fengjiayi 已提交
1478
        self.outputs = {'Out': t}
1479 1480

    def test_check_grad(self):
1481 1482
        if self.dtype == np.float16:
            return
1483
        self.check_grad(['X'], 'Out')
1484

1485

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
class TestBreluAPI(unittest.TestCase):
    # test paddle.fluid.layers.brelu
    def setUp(self):
        np.random.seed(1024)
        self.t_min = 0.
        self.t_max = 24.
        self.x_np = np.random.uniform(-1, 30, [10, 12]).astype('float32')
        self.out_ref = np.copy(self.x_np)
        self.out_ref[self.out_ref < self.t_min] = self.t_min
        self.out_ref[self.out_ref > self.t_max] = self.t_max
        self.out_ref = self.out_ref.astype('float32')
J
joejiong 已提交
1497
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
            else paddle.CPUPlace()

    def test_fluid_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.static.data('X', [10, 12])
            out = paddle.fluid.layers.brelu(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            self.assertTrue(np.allclose(self.out_ref, res[0]))

            paddle.disable_static(self.place)
            x = paddle.to_tensor(self.x_np)
            out = paddle.fluid.layers.brelu(x)
            self.assertTrue(np.allclose(self.out_ref, out.numpy()))
            paddle.enable_static()

1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.brelu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.brelu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.layers.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.brelu(x_fp16)


1527 1528 1529 1530 1531 1532 1533
def ref_relu6(x, threshold=6.0):
    out = np.copy(x)
    out[np.abs(x - threshold) < 0.005] = threshold + 0.02
    out = np.minimum(np.maximum(x, 0), threshold)
    return out


C
chengduo 已提交
1534
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
1535
    def setUp(self):
1536
        self.op_type = "relu6"
1537 1538
        self.init_dtype()

1539
        np.random.seed(1024)
Z
zhupengyang 已提交
1540
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
1541
        x[np.abs(x) < 0.005] = 0.02
1542
        out = ref_relu6(x)
1543

1544 1545
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
1546
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
1547

1548 1549 1550
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1551
        self.check_grad(['X'], 'Out')
1552 1553


1554 1555 1556
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
1557
        np.random.seed(1024)
1558 1559
        self.x_np = np.random.uniform(-1, 10, [10, 12]).astype(np.float64)
        self.x_np[np.abs(self.x_np) < 0.005] = 0.02
J
joejiong 已提交
1560
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1561 1562 1563
            else paddle.CPUPlace()

    def test_static_api(self):
1564
        paddle.enable_static()
1565
        with paddle.static.program_guard(paddle.static.Program()):
1566
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
            out1 = F.relu6(x)
            relu6 = paddle.nn.ReLU6()
            out2 = relu6(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_relu6(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.relu6(x)
        relu6 = paddle.nn.ReLU6()
        out2 = relu6(x)
        out_ref = ref_relu6(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
1588
        paddle.enable_static()
1589 1590 1591 1592 1593 1594 1595 1596
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.relu6(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_relu6(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

1597
    def test_errors(self):
1598
        paddle.enable_static()
1599
        with paddle.static.program_guard(paddle.static.Program()):
1600
            # The input type must be Variable.
1601
            self.assertRaises(TypeError, F.relu6, 1)
1602
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1603 1604
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1605
            self.assertRaises(TypeError, F.relu6, x_int32)
1606
            # support the input dtype is float16
J
joejiong 已提交
1607 1608
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1609
            F.relu6(x_fp16)
1610 1611


1612 1613 1614 1615 1616
def ref_hardswish(x, threshold=6.0, scale=6.0, offset=3.0):
    return (x * np.minimum(np.maximum(x + offset, 0.), threshold) /
            scale).astype(x.dtype)


H
huangjun12 已提交
1617 1618 1619 1620 1621
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()

J
jakpiase 已提交
1622 1623
        skip_check_grad_ci(reason="not implemented yet")

1624
        np.random.seed(1024)
Z
zhupengyang 已提交
1625
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
1626 1627 1628 1629 1630 1631
        threshold = 6.0
        scale = 6.0
        offset = 3.0
        #the same with TestAbs
        x[np.abs(x + offset) < 0.005] = 0.02
        x[np.abs(x - threshold + offset) < 0.005] = threshold - offset + 0.02
1632
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
1633

1634
        self.inputs = {'X': x}
H
huangjun12 已提交
1635 1636 1637 1638 1639 1640
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
J
jakpiase 已提交
1641 1642

        return  # not implemented yet
1643
        self.check_grad(['X'], 'Out')
H
huangjun12 已提交
1644 1645


1646 1647 1648 1649
class TestHardswishAPI(unittest.TestCase):
    # test paddle.nn.Hardswish, paddle.nn.functional.hardswish
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
1650
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1651 1652 1653 1654
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
1655
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
            out1 = F.hardswish(x)
            m = paddle.nn.Hardswish()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardswish(self.x_np)
        for r in res:
            self.assertTrue(np.allclose(out_ref, r))

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.hardswish(x)
        m = paddle.nn.Hardswish()
        out2 = m(x)
        out_ref = ref_hardswish(self.x_np)
        for r in [out1, out2]:
            self.assertTrue(np.allclose(out_ref, r.numpy()))
1674
        paddle.enable_static()
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.hard_swish(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardswish(self.x_np)
        self.assertTrue(np.allclose(out_ref, res[0]))

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out = paddle.fluid.layers.hard_swish(x)
        self.assertTrue(np.allclose(out_ref, out.numpy()))
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
1693
            # The input type must be Variable.
1694
            self.assertRaises(TypeError, F.hardswish, 1)
1695
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1696 1697
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1698
            self.assertRaises(TypeError, F.hardswish, x_int32)
1699
            # support the input dtype is float16
J
joejiong 已提交
1700 1701
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1702
            F.hardswish(x_fp16)
1703 1704


C
chengduo 已提交
1705
class TestSoftRelu(TestActivation):
1706 1707
    def setUp(self):
        self.op_type = "soft_relu"
1708 1709
        self.init_dtype()

1710
        np.random.seed(4096)
1711
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1712
        threshold = 2.0
Q
qijun 已提交
1713 1714
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
1715
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
1716 1717 1718
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
1719 1720 1721 1722 1723
        out = np.log((np.exp(t) + 1))

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.attrs = {'threshold': threshold}
        self.outputs = {'Out': out}
1724 1725

    def test_check_grad(self):
1726 1727
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1728
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
1729

1730

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
class TestSoftReluOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.soft_relu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.soft_relu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.soft_relu(x_fp16)


1744 1745 1746 1747 1748
def elu(x, alpha):
    out_ref = np.maximum(0, x) + np.minimum(0, alpha * (np.exp(x) - 1))
    return out_ref.astype(x.dtype)


C
chengduo 已提交
1749
class TestELU(TestActivation):
1750 1751
    def setUp(self):
        self.op_type = "elu"
1752 1753
        self.init_dtype()

1754
        np.random.seed(1024)
Z
zhupengyang 已提交
1755
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
1756
        alpha = 1.
1757
        out = elu(x, alpha)
1758 1759 1760 1761
        # Note: unlike other Relu extensions, point 0 on standard ELU function (i.e. alpha = 1)
        # is differentiable, so we can skip modifications like x[np.abs(x) < 0.005] = 0.02 here
        self.inputs = {'X': x}
        self.attrs = {'alpha': alpha}
1762
        self.outputs = {'Out': out}
1763 1764

    def test_check_grad(self):
1765 1766
        if self.dtype == np.float16:
            return
1767
        self.check_grad(['X'], 'Out')
1768 1769


1770 1771 1772
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
1773
        np.random.seed(1024)
1774
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
J
joejiong 已提交
1775
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1776
            else paddle.CPUPlace()
1777 1778 1779 1780
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
1781 1782

    def test_static_api(self):
1783
        paddle.enable_static()
1784
        with paddle.static.program_guard(paddle.static.Program()):
1785
            x = paddle.fluid.data('X', [10, 12])
1786
            out1 = self.elu(x)
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
            m = paddle.nn.ELU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = elu(self.x_np, 1.0)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
1798 1799
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
1800 1801 1802 1803 1804 1805
        m = paddle.nn.ELU()
        out2 = m(x)
        out_ref = elu(self.x_np, 1.0)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

1806 1807
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
1808 1809 1810 1811 1812 1813 1814
        m = paddle.nn.ELU(0.2)
        out2 = m(x)
        out_ref = elu(self.x_np, 0.2)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

1815
    def test_errors(self):
1816
        paddle.enable_static()
1817 1818
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
1819
            self.assertRaises(TypeError, self.elu, 1)
1820
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1821 1822
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
1823
            self.assertRaises(TypeError, self.elu, x_int32)
1824
            # support the input dtype is float16
J
joejiong 已提交
1825 1826
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
1827 1828 1829
            self.elu(x_fp16)


1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
def celu(x, alpha):
    out_ref = np.maximum(0, x) + np.minimum(0, alpha * (np.exp(x / alpha) - 1))
    return out_ref.astype(x.dtype)


class TestCELU(TestActivation):
    def setUp(self):
        self.op_type = "celu"
        self.init_dtype()

        np.random.seed(1024)
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
        alpha = 1.5
        out = celu(x, alpha)
        self.inputs = {'X': x}
        self.attrs = {'alpha': alpha}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


class TestCELUAPI(unittest.TestCase):
    # test paddle.nn.CELU, paddle.nn.functional.celu
    def setUp(self):
        np.random.seed(1024)
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
            else paddle.CPUPlace()
        self.executed_api()

    def executed_api(self):
        self.celu = F.celu

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.fluid.data('X', [10, 12])
            out1 = self.celu(x, 1.5)
            m = paddle.nn.CELU(1.5)
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = celu(self.x_np, 1.5)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = self.celu(x, 1.5)
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.CELU(1.5)
        out2 = m(x)
        out_ref = celu(self.x_np, 1.5)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

        out1 = self.celu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.CELU(0.2)
        out2 = m(x)
        out_ref = celu(self.x_np, 0.2)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_errors(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, self.celu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
            self.assertRaises(TypeError, self.celu, x_int32)
            # The alpha must be not equal 0
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[10, 12], dtype='float32')
            self.assertRaises(ZeroDivisionError, F.celu, x_fp32, 0)
            # support the input dtype is float16
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
            self.celu(x_fp16)


1918 1919 1920 1921
class TestELUInplaceAPI(TestELUAPI):
    # test paddle.nn.functional.elu_
    def executed_api(self):
        self.elu = F.elu_
1922 1923


C
chengduo 已提交
1924
class TestReciprocal(TestActivation):
Q
qijun 已提交
1925 1926
    def setUp(self):
        self.op_type = "reciprocal"
1927 1928
        self.init_dtype()

1929
        np.random.seed(1024)
1930 1931 1932 1933 1934
        x = np.random.uniform(1, 2, [11, 17]).astype(self.dtype)
        out = np.reciprocal(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
Q
qijun 已提交
1935 1936

    def test_check_grad(self):
1937 1938
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1939
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Q
qijun 已提交
1940 1941


C
chengduo 已提交
1942
class TestLog(TestActivation):
Q
qijun 已提交
1943 1944
    def setUp(self):
        self.op_type = "log"
1945 1946
        self.init_dtype()

1947
        np.random.seed(1024)
1948 1949 1950 1951 1952
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
Q
qijun 已提交
1953 1954

    def test_check_grad(self):
1955 1956
        if self.dtype == np.float16:
            return
1957
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1958

1959 1960 1961 1962 1963 1964 1965 1966 1967
    def test_error(self):
        in1 = fluid.layers.data(
            name="in1", shape=[11, 17], append_batch_size=False, dtype="int32")
        in2 = fluid.layers.data(
            name="in2", shape=[11, 17], append_batch_size=False, dtype="int64")

        self.assertRaises(TypeError, fluid.layers.log, in1)
        self.assertRaises(TypeError, fluid.layers.log, in2)

1968

J
joejiong 已提交
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
class TestLog2(TestActivation):
    def setUp(self):
        self.op_type = "log2"
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log2(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

    def test_error(self):
        in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
        in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")

        self.assertRaises(TypeError, paddle.log2, in1)
        self.assertRaises(TypeError, paddle.log2, in2)

    def test_api(self):
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = paddle.static.data(
                name="data_x", shape=[11, 17], dtype="float64")

            out1 = paddle.log2(data_x)
            exe = paddle.static.Executor(place=fluid.CPUPlace())
            exe.run(paddle.static.default_startup_program())
            res1 = exe.run(paddle.static.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
        expected_res = np.log2(input_x)
        self.assertTrue(np.allclose(res1, expected_res))

        # dygraph
        with fluid.dygraph.guard():
            np_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = paddle.to_tensor(np_x)
            z = paddle.log2(data_x)
            np_z = z.numpy()
            z_expected = np.array(np.log2(np_x))
        self.assertTrue(np.allclose(np_z, z_expected))


J
joejiong 已提交
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
class TestLog10(TestActivation):
    def setUp(self):
        self.op_type = "log10"
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log10(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

    def test_error(self):
        in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
        in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")

        self.assertRaises(TypeError, paddle.log10, in1)
        self.assertRaises(TypeError, paddle.log10, in2)

    def test_api(self):
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = paddle.static.data(
                name="data_x", shape=[11, 17], dtype="float64")

            out1 = paddle.log10(data_x)
            exe = paddle.static.Executor(place=paddle.CPUPlace())
            exe.run(paddle.static.default_startup_program())
            res1 = exe.run(paddle.static.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
        expected_res = np.log10(input_x)
        self.assertTrue(np.allclose(res1, expected_res))

        # dygraph
        with fluid.dygraph.guard():
            np_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = paddle.to_tensor(np_x)
            z = paddle.log10(data_x)
            np_z = z.numpy()
            z_expected = np.array(np.log10(np_x))
        self.assertTrue(np.allclose(np_z, z_expected))


2067 2068 2069 2070 2071
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
        self.init_dtype()

2072
        np.random.seed(1024)
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log1p(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

    def test_api(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = fluid.layers.data(
                name="data_x",
                shape=[11, 17],
                append_batch_size=False,
                dtype="float64")

            out1 = paddle.log1p(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
2096 2097 2098
            res1 = exe.run(fluid.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
2099
        expected_res = np.log1p(input_x)
2100
        self.assertTrue(np.allclose(res1, expected_res))
2101 2102 2103 2104 2105 2106 2107 2108

        # dygraph
        with fluid.dygraph.guard():
            np_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = fluid.dygraph.to_variable(np_x)
            z = paddle.log1p(data_x)
            np_z = z.numpy()
            z_expected = np.array(np.log1p(np_x))
2109
        self.assertTrue(np.allclose(np_z, z_expected))
2110 2111


C
chengduo 已提交
2112
class TestSquare(TestActivation):
Q
qijun 已提交
2113 2114
    def setUp(self):
        self.op_type = "square"
2115 2116
        self.init_dtype()

2117
        np.random.seed(1024)
2118 2119 2120 2121 2122
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.square(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
Q
qijun 已提交
2123 2124

    def test_check_grad(self):
2125 2126
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
2127
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
Q
qijun 已提交
2128

2129

C
chengduo 已提交
2130
class TestPow(TestActivation):
2131 2132
    def setUp(self):
        self.op_type = "pow"
2133 2134
        self.init_dtype()

2135
        np.random.seed(1024)
2136 2137 2138 2139
        x = np.random.uniform(1, 2, [11, 17]).astype(self.dtype)
        out = np.power(x, 3)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
Y
Yang Yang(Tony) 已提交
2140
        self.attrs = {'factor': 3.0}
2141
        self.outputs = {'Out': out}
2142 2143

    def test_check_grad(self):
2144 2145
        if self.dtype == np.float16:
            return
2146
        self.check_grad(['X'], 'Out')
2147

2148

2149 2150 2151 2152 2153
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
        self.init_dtype()

2154
        np.random.seed(1024)
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
        x = np.random.uniform(1, 2, [11, 17]).astype(self.dtype)
        out = np.power(x, 3)

        self.inputs = {
            'X': OpTest.np_dtype_to_fluid_dtype(x),
            'FactorTensor': np.array([3.0]).astype("float32")
        }

        self.attrs = {}
        self.outputs = {'Out': out}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
2172
        self.check_grad(['X'], 'Out')
2173 2174 2175 2176 2177

    def test_api(self):
        input = np.random.uniform(1, 2, [11, 17]).astype("float32")
        x = fluid.layers.data(
            name="x", shape=[11, 17], append_batch_size=False, dtype="float32")
2178 2179 2180 2181 2182
        res = fluid.layers.data(
            name="res",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
2183 2184 2185 2186 2187

        factor_1 = 2.0
        factor_2 = fluid.layers.fill_constant([1], "float32", 3.0)
        out_1 = fluid.layers.pow(x, factor=factor_1)
        out_2 = fluid.layers.pow(x, factor=factor_2)
2188 2189 2190
        out_4 = paddle.pow(x, factor_1, name='pow_res')
        out_6 = paddle.pow(x, factor_2)
        self.assertEqual(('pow_res' in out_4.name), True)
2191 2192

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
2193
        res_1, res_2, res, res_6 = exe.run(
2194 2195
            fluid.default_main_program(),
            feed={"x": input},
W
WuHaobo 已提交
2196
            fetch_list=[out_1, out_2, res, out_6])
2197

2198 2199 2200
        assert np.allclose(res_1, np.power(input, 2))
        assert np.allclose(res_2, np.power(input, 3))
        assert np.allclose(res_6, np.power(input, 3))
2201

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
    def test_error(self):
        in1 = fluid.layers.data(
            name="in1", shape=[11, 17], append_batch_size=False, dtype="int32")
        in2 = fluid.layers.data(
            name="in2", shape=[11, 17], append_batch_size=False, dtype="int64")
        in3 = fluid.layers.data(
            name="in3",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
        in4 = fluid.layers.data(
            name="in4",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float64")

        factor_1 = fluid.layers.fill_constant([1], "float64", 3.0)

        self.assertRaises(TypeError, fluid.layers.pow, x=in1, factor=factor_1)
        self.assertRaises(TypeError, fluid.layers.pow, x=in2, factor=factor_1)
        self.assertRaises(TypeError, fluid.layers.pow, x=in3, factor=factor_1)
        self.assertRaises(TypeError, fluid.layers.pow, x=in4, factor=factor_1)

2225

2226 2227 2228 2229 2230
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
2231
class TestSTanh(TestActivation):
2232 2233 2234 2235 2236 2237
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

2238 2239
    def setUp(self):
        self.op_type = "stanh"
2240
        self.init_dtype()
2241 2242
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
2243

2244
        np.random.seed(1024)
2245
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
2246 2247
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
2248

2249
        self.inputs = {'X': x}
2250
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
2251
        self.outputs = {'Out': out}
2252

Q
qijun 已提交
2253
    def test_check_grad(self):
2254 2255
        if self.dtype == np.float16:
            return
2256
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
2257

2258

2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
class TestSTanhScaleA(TestSTanh):
    def get_scale_a(self):
        return 2.0


class TestSTanhScaleB(TestSTanh):
    def get_scale_b(self):
        return 0.5


class TestSTanhAPI(unittest.TestCase):
    # test paddle.nn.stanh
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

    def setUp(self):
        np.random.seed(1024)
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.scale_a = self.get_scale_a()
        self.scale_b = self.get_scale_b()
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.fluid.data('X', [10, 12])
            out = paddle.stanh(x, self.scale_a, self.scale_b)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out = paddle.stanh(x, self.scale_a, self.scale_b)
        out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
        for r in [out]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
            out = fluid.layers.stanh(x, self.scale_a, self.scale_b)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

2315
    def test_errors(self):
2316 2317
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2318
            # The input type must be Variable.
2319
            self.assertRaises(TypeError, paddle.stanh, 1)
2320
            # The input dtype must be float16, float32, float64.
2321 2322 2323
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, paddle.stanh, x_int32)
2324
            # support the input dtype is float16
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
            paddle.stanh(x_fp16)


class TestSTanhAPIScaleA(TestSTanhAPI):
    def get_scale_a(self):
        return 2.0


class TestSTanhAPIScaleB(TestSTanhAPI):
    def get_scale_b(self):
        return 0.5
2338 2339


2340 2341 2342 2343 2344 2345 2346
def ref_softplus(x, beta=1, threshold=20):
    x_beta = beta * x
    out = np.select([x_beta <= threshold, x_beta > threshold],
                    [np.log(1 + np.exp(x_beta)) / beta, x])
    return out


C
chengduo 已提交
2347
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
2348 2349
    def setUp(self):
        self.op_type = "softplus"
2350 2351
        self.init_dtype()

2352 2353
        beta = 2
        threshold = 15
2354

2355
        np.random.seed(1024)
2356 2357 2358 2359
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softplus(x, beta, threshold)
        self.inputs = {'X': x}
        self.attrs = {'beta': beta, "threshold": threshold}
2360
        self.outputs = {'Out': out}
K
kexinzhao 已提交
2361 2362

    def test_check_grad(self):
2363 2364
        if self.dtype == np.float16:
            return
2365
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
2366

2367

2368 2369 2370 2371 2372
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
2373
        np.random.seed(1024)
2374
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2375
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2376 2377 2378
            else paddle.CPUPlace()

    def test_static_api(self):
2379
        paddle.enable_static()
2380
        with paddle.static.program_guard(paddle.static.Program()):
2381
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
            out1 = F.softplus(x, self.beta, self.threshold)
            softplus = paddle.nn.Softplus(self.beta, self.threshold)
            out2 = softplus(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_softplus(self.x_np, self.beta, self.threshold)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.softplus(x, self.beta, self.threshold)
        softplus = paddle.nn.Softplus(self.beta, self.threshold)
        out2 = softplus(x)
        out_ref = ref_softplus(self.x_np, self.beta, self.threshold)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
2403
        paddle.enable_static()
2404 2405 2406 2407 2408 2409 2410 2411 2412
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.softplus(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_softplus(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
2413
        paddle.enable_static()
2414 2415 2416 2417
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.softplus, 1)
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2418 2419
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2420 2421
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
2422 2423
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2424 2425 2426 2427 2428 2429 2430 2431
            F.softplus(x_fp16)


def ref_softsign(x):
    out = np.divide(x, 1 + np.abs(x))
    return out


C
chengduo 已提交
2432
class TestSoftsign(TestActivation):
2433 2434
    def setUp(self):
        self.op_type = "softsign"
2435 2436
        self.init_dtype()

2437
        np.random.seed(1024)
2438 2439 2440
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softsign(x)
        self.inputs = {'X': x}
2441
        self.outputs = {'Out': out}
2442 2443

    def test_check_grad(self):
2444 2445
        if self.dtype == np.float16:
            return
2446
        self.check_grad(['X'], 'Out')
2447 2448


2449 2450 2451
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
2452
        np.random.seed(1024)
2453
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2454
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2455 2456 2457
            else paddle.CPUPlace()

    def test_static_api(self):
2458
        paddle.enable_static()
2459
        with paddle.static.program_guard(paddle.static.Program()):
2460
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
            out1 = F.softsign(x)
            softsign = paddle.nn.Softsign()
            out2 = softsign(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_softsign(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.softsign(x)
        softsign = paddle.nn.Softsign()
        out2 = softsign(x)
        out_ref = ref_softsign(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
2482
        paddle.enable_static()
2483 2484 2485 2486 2487 2488 2489 2490 2491
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.softsign(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_softsign(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
2492
        paddle.enable_static()
2493 2494 2495 2496
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.softsign, 1)
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2497 2498
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2499 2500
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
2501 2502
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2503 2504 2505
            F.softsign(x_fp16)


2506 2507 2508 2509 2510
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
2511
class TestThresholdedRelu(TestActivation):
2512 2513
    def setUp(self):
        self.op_type = "thresholded_relu"
2514 2515
        self.init_dtype()

2516
        threshold = 15
2517

2518 2519 2520 2521 2522 2523
        np.random.seed(1024)
        x = np.random.uniform(-20, 20, [10, 12]).astype(self.dtype)
        x[np.abs(x) < 0.005] = 0.02
        out = ref_thresholded_relu(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"threshold": threshold}
2524
        self.outputs = {'Out': out}
2525 2526

    def test_check_grad(self):
2527 2528
        if self.dtype == np.float16:
            return
2529
        self.check_grad(['X'], 'Out')
2530 2531


2532 2533 2534 2535 2536 2537 2538
class TestThresholdedReluAPI(unittest.TestCase):
    # test paddle.nn.ThresholdedReLU, paddle.nn.functional.thresholded_relu
    def setUp(self):
        self.threshold = 15
        np.random.seed(1024)
        self.x_np = np.random.uniform(-20, 20, [10, 12]).astype(np.float64)
        self.x_np[np.abs(self.x_np) < 0.005] = 0.02
J
joejiong 已提交
2539
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2540 2541 2542 2543 2544
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2545
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
            out1 = F.thresholded_relu(x, self.threshold)
            thresholded_relu = paddle.nn.ThresholdedReLU(self.threshold)
            out2 = thresholded_relu(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_thresholded_relu(self.x_np, self.threshold)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.thresholded_relu(x, self.threshold)
        thresholded_relu = paddle.nn.ThresholdedReLU(self.threshold)
        out2 = thresholded_relu(x)
        out_ref = ref_thresholded_relu(self.x_np, self.threshold)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.thresholded_relu(x, self.threshold)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_thresholded_relu(self.x_np, self.threshold)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

2576
    def test_errors(self):
2577 2578
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2579
            # The input type must be Variable.
2580
            self.assertRaises(TypeError, F.thresholded_relu, 1)
2581
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2582 2583
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2584
            self.assertRaises(TypeError, F.thresholded_relu, x_int32)
2585
            # support the input dtype is float16
J
joejiong 已提交
2586 2587
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2588
            F.thresholded_relu(x_fp16)
2589 2590


2591 2592 2593 2594
def ref_hardsigmoid(x, slope=0.166666666666667, offset=0.5):
    return np.maximum(np.minimum(x * slope + offset, 1.), 0.).astype(x.dtype)


C
chengduo 已提交
2595
class TestHardSigmoid(TestActivation):
2596 2597
    def setUp(self):
        self.op_type = "hard_sigmoid"
2598 2599 2600 2601
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
2602

2603 2604 2605
        x = np.random.uniform(-5, 5, [10, 12]).astype(self.dtype)
        lower_threshold = -self.offset / self.slope
        upper_threshold = (1. - self.offset) / self.slope
Z
zhupengyang 已提交
2606

2607
        # Same reason as TestAbs
2608 2609 2610
        delta = 0.005
        x[np.abs(x - lower_threshold) < delta] = lower_threshold - 0.02
        x[np.abs(x - upper_threshold) < delta] = upper_threshold - 0.02
2611

2612
        out = ref_hardsigmoid(x, self.slope, self.offset)
2613

2614 2615
        self.attrs = {'slope': self.slope, 'offset': self.offset}
        self.inputs = {'X': x}
2616
        self.outputs = {'Out': out}
2617

2618 2619
    def set_attrs(self):
        pass
2620

2621

2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
class TestHardSigmoidFP32(TestHardSigmoid):
    def set_attrs(self):
        self.dtype = 'float32'


class TestHardSigmoidSlopeOffset(TestHardSigmoid):
    def set_attrs(self):
        self.slope = 0.2
        self.offset = 0.4


class TestHardsigmoidAPI(unittest.TestCase):
    # test paddle.nn.Hardsigmoid, paddle.nn.functional.hardsigmoid
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2637
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2638 2639 2640 2641
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
2642
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
            out1 = F.hardsigmoid(x)
            m = paddle.nn.Hardsigmoid()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardsigmoid(self.x_np)
        for r in res:
            self.assertTrue(np.allclose(out_ref, r))

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.hardsigmoid(x)
        m = paddle.nn.Hardsigmoid()
        out2 = m(x)
        out_ref = ref_hardsigmoid(self.x_np)
        for r in [out1, out2]:
            self.assertTrue(np.allclose(out_ref, r.numpy()))
2661
        paddle.enable_static()
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.hard_sigmoid(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardsigmoid(self.x_np, 0.2, 0.5)
        self.assertTrue(np.allclose(out_ref, res[0]))

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out = paddle.fluid.layers.hard_sigmoid(x)
        self.assertTrue(np.allclose(out_ref, out.numpy()))
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
2680
            # The input type must be Variable.
2681
            self.assertRaises(TypeError, F.hardsigmoid, 1)
2682
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2683 2684
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2685
            self.assertRaises(TypeError, F.hardsigmoid, x_int32)
2686
            # support the input dtype is float16
J
joejiong 已提交
2687 2688
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2689
            F.hardsigmoid(x_fp16)
2690 2691


2692 2693 2694 2695 2696
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
2697
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
2698 2699
    def setUp(self):
        self.op_type = "swish"
2700 2701
        self.init_dtype()

2702
        np.random.seed(1024)
2703 2704 2705
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_swish(x)
        self.inputs = {'X': x}
H
hong19860320 已提交
2706
        self.attrs = {'beta': 1.0}
2707
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
2708 2709

    def test_check_grad(self):
2710 2711
        if self.dtype == np.float16:
            return
2712 2713
        self.check_grad(['X'], 'Out')

A
Abhinav Arora 已提交
2714

2715 2716 2717 2718 2719
class TestSwishAPI(unittest.TestCase):
    # test paddle.nn.Swish, paddle.nn.functional.swish
    def setUp(self):
        np.random.seed(1024)
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2720
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2721 2722 2723 2724 2725
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
2726
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
            out1 = F.swish(x)
            swish = paddle.nn.Swish()
            out2 = swish(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_swish(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.swish(x)
        swish = paddle.nn.Swish()
        out2 = swish(x)
        out_ref = ref_swish(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.swish(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_swish(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)
2756

2757
    def test_errors(self):
2758 2759
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2760
            # The input type must be Variable.
2761
            self.assertRaises(TypeError, F.swish, 1)
2762
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2763 2764
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2765
            self.assertRaises(TypeError, F.swish, x_int32)
2766
            # support the input dtype is float16
J
joejiong 已提交
2767 2768
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2769
            F.swish(x_fp16)
2770 2771


2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
#------------------ Test Error Activation----------------------
def create_test_error_class(op_type):
    class TestOpErrors(unittest.TestCase):
        def test_errors(self):
            with program_guard(Program(), Program()):
                op = getattr(fluid.layers, op_type)
                # The input dtype of op_type must be float32, float64.
                in1 = fluid.layers.data(
                    name='input2', shape=[12, 10], dtype="int32")
                in2 = fluid.layers.data(
                    name='input3', shape=[12, 10], dtype="int64")
                self.assertRaises(TypeError, op, in1)
                self.assertRaises(TypeError, op, in2)

    cls_name = "{0}_{1}".format(op_type, "test_errors")
    TestOpErrors.__name__ = cls_name
    globals()[cls_name] = TestOpErrors


create_test_error_class('acos')
create_test_error_class('asin')
create_test_error_class('atan')
create_test_error_class('ceil')
create_test_error_class('cos')
create_test_error_class('floor')
create_test_error_class('reciprocal')
create_test_error_class('round')
create_test_error_class('rsqrt')
create_test_error_class('sin')
create_test_error_class('sqrt')
create_test_error_class('tanh')
J
joejiong 已提交
2803
create_test_error_class('tan')
2804 2805


2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
#------------------ Test Cudnn Activation----------------------
def create_test_act_cudnn_class(parent, atol=1e-3, grad_atol=1e-3):
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActCudnn(parent):
        def init_kernel_type(self):
            self.attrs = {"use_cudnn": True}

    cls_name = "{0}_{1}".format(parent.__name__, "cudnn")
    TestActCudnn.__name__ = cls_name
    globals()[cls_name] = TestActCudnn


create_test_act_cudnn_class(TestRelu)
create_test_act_cudnn_class(TestRelu6)
create_test_act_cudnn_class(TestSigmoid)
create_test_act_cudnn_class(TestTanh)


C
chengduo 已提交
2825 2826 2827 2828 2829
#------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(parent,
                               atol=1e-3,
                               grad_check=True,
                               grad_atol=0.80):
J
joejiong 已提交
2830
    @unittest.skipIf(not paddle.is_compiled_with_cuda(),
C
chengduo 已提交
2831 2832 2833 2834
                     "core is not compiled with CUDA")
    class TestActFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16
2835

C
chengduo 已提交
2836
        def test_check_output(self):
2837
            place = core.CUDAPlace(0)
C
chengduo 已提交
2838 2839 2840
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
2841

C
chengduo 已提交
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854
        def test_check_grad(self):
            place = core.CUDAPlace(0)
            support_fp16 = core.is_float16_supported(place)
            if support_fp16 and grad_check:
                self.check_grad_with_place(
                    place, ['X'], 'Out', max_relative_error=grad_atol)

    cls_name = "{0}_{1}".format(parent.__name__, "fp16")
    TestActFp16.__name__ = cls_name
    globals()[cls_name] = TestActFp16


create_test_act_fp16_class(TestActivation)
R
ronnywang 已提交
2855
create_test_act_fp16_class(TestExpm1)
C
chengduo 已提交
2856
create_test_act_fp16_class(TestSigmoid)
M
minghaoBD 已提交
2857
create_test_act_fp16_class(TestSilu)
C
chengduo 已提交
2858 2859
create_test_act_fp16_class(TestLogSigmoid)
create_test_act_fp16_class(TestTanh)
2860
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
2861
create_test_act_fp16_class(TestHardShrink)
2862
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
2863 2864 2865 2866 2867
create_test_act_fp16_class(TestSqrt)
create_test_act_fp16_class(TestAbs)
create_test_act_fp16_class(TestCeil, grad_check=False)
create_test_act_fp16_class(TestFloor, grad_check=False)
create_test_act_fp16_class(TestCos, grad_atol=0.85)
J
joejiong 已提交
2868
create_test_act_fp16_class(TestTan, grad_atol=0.85)
2869
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
2870
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
2871
create_test_act_fp16_class(TestSin)
2872
create_test_act_fp16_class(TestSinh)
2873 2874
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
C
chengduo 已提交
2875 2876
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
2877
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
2878 2879
create_test_act_fp16_class(TestBRelu)
create_test_act_fp16_class(TestRelu6)
2880
create_test_act_fp16_class(TestSoftRelu, grad_atol=0.85)
C
chengduo 已提交
2881
create_test_act_fp16_class(TestELU)
2882
create_test_act_fp16_class(TestCELU)
C
chengduo 已提交
2883 2884
create_test_act_fp16_class(TestReciprocal)
create_test_act_fp16_class(TestLog)
2885 2886 2887 2888
if core.is_compiled_with_rocm():
    create_test_act_fp16_class(TestLog2, atol=5e-2, grad_atol=0.85)
else:
    create_test_act_fp16_class(TestLog2, atol=5e-2)
J
joejiong 已提交
2889
create_test_act_fp16_class(TestLog10, atol=5e-2)
2890
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
2891 2892
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
2893
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
2894 2895 2896 2897 2898
create_test_act_fp16_class(TestSTanh, grad_atol=0.9)
create_test_act_fp16_class(TestSoftplus)
create_test_act_fp16_class(TestSoftsign)
create_test_act_fp16_class(TestThresholdedRelu)
create_test_act_fp16_class(TestHardSigmoid)
2899
create_test_act_fp16_class(TestSwish, grad_atol=0.85)
H
huangjun12 已提交
2900
create_test_act_fp16_class(TestHardSwish)
A
Abhinav Arora 已提交
2901

2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928

def create_test_act_bf16_class(parent,
                               atol=1e-2,
                               grad_check=True,
                               grad_atol=0.80):
    @unittest.skipIf(not paddle.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActBF16(parent):
        def init_dtype(self):
            self.dtype = np.uint16

        def test_check_output(self):
            place = core.CUDAPlace(0)
            self.check_output_with_place(place, atol=atol)

        def test_check_grad(self):
            place = core.CUDAPlace(0)
            self.check_grad_with_place(
                place, ['X'], 'Out', max_relative_error=grad_atol)

    cls_name = "{0}_{1}".format(parent.__name__, "bf16")
    TestActBF16.__name__ = cls_name
    globals()[cls_name] = TestActBF16


create_test_act_bf16_class(TestRelu)

Q
qijun 已提交
2929 2930
if __name__ == "__main__":
    unittest.main()