test_activation_op.py 115.1 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 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
28
from paddle.fluid.framework import _test_eager_guard
Q
qijun 已提交
29

30 31
paddle.enable_static()

Q
qijun 已提交
32

33
class TestSqrtOpError(unittest.TestCase):
34

Z
Zhaolong Xing 已提交
35 36 37 38 39 40
    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.
41 42 43
            in2 = fluid.layers.data(name='input2',
                                    shape=[12, 10],
                                    dtype="int32")
Z
Zhaolong Xing 已提交
44 45
            self.assertRaises(TypeError, fluid.layers.sqrt, in2)

46 47 48
            in3 = fluid.layers.data(name='input3',
                                    shape=[12, 10],
                                    dtype="float16")
Z
Zhaolong Xing 已提交
49 50 51
            fluid.layers.sqrt(x=in3)


C
chengduo 已提交
52
class TestActivation(OpTest):
53

Q
qijun 已提交
54 55
    def setUp(self):
        self.op_type = "exp"
56
        self.init_dtype()
57
        self.init_kernel_type()
C
chentianyu03 已提交
58 59
        self.check_eager = True
        self.python_api = paddle.exp
60

61
        np.random.seed(2049)
62 63 64 65 66
        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 已提交
67 68

    def test_check_output(self):
69 70 71 72
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_output(check_eager=check_eager)
Q
qijun 已提交
73 74

    def test_check_grad(self):
75 76
        if self.dtype == np.float16:
            return
77 78 79 80
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
Q
qijun 已提交
81

82
    def init_dtype(self):
83
        self.dtype = np.float64
84

85 86 87
    def init_kernel_type(self):
        pass

Q
qijun 已提交
88

R
ronnywang 已提交
89
class TestExpm1(TestActivation):
90

R
ronnywang 已提交
91 92
    def setUp(self):
        self.op_type = "expm1"
93
        self.python_api = paddle.expm1
R
ronnywang 已提交
94 95 96 97 98 99 100 101 102 103
        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):
104 105 106 107
        self.check_grad(['X'], 'Out', check_eager=True)

    def test_check_output(self):
        self.check_output(check_eager=True)
R
ronnywang 已提交
108 109 110


class TestExpm1API(unittest.TestCase):
111

R
ronnywang 已提交
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 140
    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):
141

R
ronnywang 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        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.


160
class TestParameter(object):
161

162 163
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
W
WuHaobo 已提交
164
            np_x = np.array([0.1])
165
            data = fluid.layers.data(name="X", shape=[1])
W
WuHaobo 已提交
166
            out = eval("paddle.%s(data, name='Y')" % self.op_type)
167 168
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
W
WuHaobo 已提交
169 170
            result, = exe.run(feed={"X": np_x}, fetch_list=[out])
            expected = eval("np.%s(np_x)" % self.op_type)
S
Shang Zhizhou 已提交
171
            self.assertTrue(np.allclose(result, expected))
172 173 174 175 176 177 178

    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)
S
Shang Zhizhou 已提交
179
            self.assertTrue(np.allclose(z, z_expected))
180 181


C
chengduo 已提交
182
class TestSigmoid(TestActivation):
183

Q
qijun 已提交
184 185
    def setUp(self):
        self.op_type = "sigmoid"
186 187
        self.init_dtype()

188
        np.random.seed(1024)
189 190 191 192 193
        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 已提交
194

195 196 197
    def init_dtype(self):
        self.dtype = np.float32

198
    def test_check_grad(self):
199 200 201 202
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.01)

203

204 205 206
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestSigmoidBF16(OpTest):
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
    def setUp(self):
        self.op_type = "sigmoid"
        self.init_dtype()

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

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

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

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

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


M
minghaoBD 已提交
233
class TestSilu(TestActivation):
234

M
minghaoBD 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    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.
291 292 293
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[11, 17],
                                        dtype='int32')
M
minghaoBD 已提交
294 295
            self.assertRaises(TypeError, F.silu, x_int32)
            # support the input dtype is float16
296 297 298
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[11, 17],
                                       dtype='float16')
M
minghaoBD 已提交
299 300 301
            F.silu(x_fp16)


C
chengduo 已提交
302
class TestLogSigmoid(TestActivation):
303

304 305
    def setUp(self):
        self.op_type = "logsigmoid"
306 307
        self.init_dtype()

308
        np.random.seed(2048)
309 310 311
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = np.log(1 / (1 + np.exp(-x)))

312
        self.inputs = {'X': x}
313
        self.outputs = {'Out': out}
314 315

    def test_check_grad(self):
316 317
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
318
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
319 320


321
class TestLogSigmoidAPI(unittest.TestCase):
322
    # test paddle.nn.LogSigmoid, paddle.nn.functional.log_sigmoid
323
    def setUp(self):
324
        np.random.seed(1024)
325
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
J
joejiong 已提交
326
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
327 328 329
            else paddle.CPUPlace()

    def test_static_api(self):
330
        paddle.enable_static()
331
        with paddle.static.program_guard(paddle.static.Program()):
332
            x = paddle.fluid.data('X', [11, 17])
333
            out1 = F.log_sigmoid(x)
334 335 336 337 338 339
            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:
340
            self.assertTrue(np.allclose(out_ref, r))
341 342 343 344

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
345
        out1 = F.log_sigmoid(x)
346 347 348 349
        m = paddle.nn.LogSigmoid()
        out2 = m(x)
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in [out1, out2]:
350
            self.assertTrue(np.allclose(out_ref, r.numpy()))
351 352
        paddle.enable_static()

353
    def test_fluid_api(self):
354
        paddle.enable_static()
355
        with paddle.static.program_guard(paddle.static.Program()):
356
            x = paddle.fluid.data('X', [11, 17])
357 358 359 360 361 362
            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]))

363
    def test_errors(self):
364
        paddle.enable_static()
365 366
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
367
            self.assertRaises(TypeError, F.log_sigmoid, 1)
368
            # The input dtype must be float16, float32, float64.
369 370 371
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[11, 17],
                                        dtype='int32')
372
            self.assertRaises(TypeError, F.log_sigmoid, x_int32)
373
            # support the input dtype is float16
374 375 376
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[11, 17],
                                       dtype='float16')
377
            F.log_sigmoid(x_fp16)
378 379


380
class TestTanh(TestActivation, TestParameter):
381

382 383
    def setUp(self):
        self.op_type = "tanh"
384
        self.init_dtype()
385
        np.random.seed(1024)
386 387 388 389 390
        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}
391 392

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

397 398 399 400 401 402
    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

403

W
WangXi 已提交
404 405 406 407
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
408
        np.random.seed(1024)
W
WangXi 已提交
409
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
J
joejiong 已提交
410
        self.place = paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
W
WangXi 已提交
411
            else paddle.CPUPlace()
412 413 414 415
        self.executed_api()

    def executed_api(self):
        self.tanh = F.tanh
W
WangXi 已提交
416 417

    def test_static_api(self):
418
        paddle.enable_static()
W
WangXi 已提交
419
        with paddle.static.program_guard(paddle.static.Program()):
420
            x = paddle.fluid.data('X', [10, 12], self.dtype)
421
            out1 = self.tanh(x)
W
WangXi 已提交
422 423 424 425 426 427 428 429 430 431
            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 已提交
432
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
433 434 435 436 437 438 439 440 441 442
        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):
443
        paddle.enable_static()
W
WangXi 已提交
444 445 446 447 448 449 450 451 452
        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):
453
        paddle.enable_static()
W
WangXi 已提交
454 455
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
456
            self.assertRaises(TypeError, self.tanh, 1)
W
WangXi 已提交
457
            # The input dtype must be float16, float32.
458 459 460
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
461
            self.assertRaises(TypeError, self.tanh, x_int32)
W
WangXi 已提交
462
            # support the input dtype is float16
463 464 465
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
466 467 468 469 470 471 472
            self.tanh(x_fp16)


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


475
class TestAtan(TestActivation, TestParameter):
476

477 478 479 480
    def setUp(self):
        self.op_type = "atan"
        self.init_dtype()

481
        np.random.seed(1024)
482 483 484 485 486 487 488 489 490
        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
491
        self.check_grad(['X'], 'Out')
492

W
WuHaobo 已提交
493 494 495 496 497 498 499 500 501 502 503
    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)

504 505 506 507 508 509 510 511
    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)

512

513
class TestSinh(TestActivation):
514

515 516 517 518
    def setUp(self):
        self.op_type = "sinh"
        self.init_dtype()

519
        np.random.seed(1024)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
        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")
544 545 546 547
            data_x = fluid.layers.data(name="data_x",
                                       shape=test_data_shape,
                                       append_batch_size=False,
                                       dtype="float32")
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

            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):
573

574 575 576 577 578 579 580 581 582 583 584 585 586
    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):
587

588 589 590 591
    def setUp(self):
        self.op_type = "cosh"
        self.init_dtype()

592
        np.random.seed(1024)
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        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")
617 618 619 620
            data_x = fluid.layers.data(name="data_x",
                                       shape=test_data_shape,
                                       append_batch_size=False,
                                       dtype="float32")
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

            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):
646

647 648 649 650 651 652 653 654 655 656 657 658
    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)


659 660 661 662 663 664
def ref_tanhshrink(x):
    out = x - np.tanh(x)
    return out


class TestTanhshrink(TestActivation):
665

K
Kavya Srinet 已提交
666 667
    def setUp(self):
        self.op_type = "tanh_shrink"
668 669
        self.init_dtype()

670
        np.random.seed(1024)
671 672
        x = np.random.uniform(10, 20, [10, 17]).astype(self.dtype)
        out = ref_tanhshrink(x)
673

674
        self.inputs = {'X': x}
675
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
676 677

    def test_check_grad(self):
678 679
        if self.dtype == np.float16:
            return
680
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
681

682

683 684 685
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
686
        np.random.seed(1024)
687
        self.x_np = np.random.uniform(10, 20, [10, 17]).astype(np.float64)
J
joejiong 已提交
688
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
689 690 691
            else paddle.CPUPlace()

    def test_static_api(self):
692
        paddle.enable_static()
693
        with paddle.static.program_guard(paddle.static.Program()):
694
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
            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):
716
        paddle.enable_static()
717 718 719 720 721 722 723 724 725
        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):
726
        paddle.enable_static()
727 728 729 730
        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.
731 732 733
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
734 735
            self.assertRaises(TypeError, F.tanhshrink, x_int32)
            # support the input dtype is float16
736 737 738
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
739 740 741
            F.tanhshrink(x_fp16)


742 743 744 745 746 747
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
748
class TestHardShrink(TestActivation):
749

750 751
    def setUp(self):
        self.op_type = "hard_shrink"
752 753
        self.init_dtype()

754 755
        self.threshold = 0.5
        self.set_attrs()
756
        np.random.seed(1024)
Z
zhupengyang 已提交
757
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype) * 10
758
        out = ref_hardshrink(x, self.threshold)
759

760
        self.attrs = {'threshold': self.threshold}
761
        self.inputs = {'X': x}
762
        self.outputs = {'Out': out}
763

764 765 766
    def set_attrs(self):
        pass

767
    def test_check_grad(self):
768 769
        if self.dtype == np.float16:
            return
770
        self.check_grad(['X'], 'Out')
771 772


773
class TestHardShrink_threshold_negative(TestHardShrink):
774

775 776 777 778
    def set_attrs(self):
        self.threshold = -0.1


779 780 781
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
782
        np.random.seed(1024)
783
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
784
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
785 786 787
            else paddle.CPUPlace()

    def test_static_api(self):
788
        paddle.enable_static()
789
        with paddle.static.program_guard(paddle.static.Program()):
790
            x = paddle.fluid.data('X', [10, 12])
791 792 793 794 795 796 797 798 799 800 801
            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 已提交
802
        x = paddle.to_tensor(self.x_np)
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
        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):
819
        paddle.enable_static()
820 821 822 823 824 825 826 827
        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)

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


845 846 847 848 849 850 851 852 853 854 855
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):
856
        np.random.seed(1024)
857
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
J
joejiong 已提交
858
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
859 860 861
            else paddle.CPUPlace()

    def test_static_api(self):
862
        paddle.enable_static()
863
        with paddle.static.program_guard(paddle.static.Program()):
864
            x = paddle.fluid.data('X', [10, 12])
865 866 867 868 869 870 871 872 873 874 875
            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 已提交
876
        x = paddle.to_tensor(self.x_np)
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
        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):
893
        paddle.enable_static()
894 895 896 897
        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.
898 899 900
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
901 902
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
903 904 905
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
906 907 908
            F.hardtanh(x_fp16)


909 910 911 912 913 914 915 916
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):
917

918 919
    def setUp(self):
        self.op_type = "softshrink"
920 921
        self.check_eager = True
        self.python_api = paddle.nn.functional.softshrink
922 923
        self.init_dtype()

924
        threshold = 0.8
925

926
        np.random.seed(1023)
927 928 929 930
        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}
931
        self.outputs = {'Out': out}
932 933

    def test_check_grad(self):
934 935
        if self.dtype == np.float16:
            return
936
        self.check_grad(['X'], 'Out', check_eager=True)
937

938

939 940 941 942
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
943
        np.random.seed(1024)
944
        self.x_np = np.random.uniform(0.25, 10, [10, 12]).astype(np.float64)
J
joejiong 已提交
945
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
946 947 948
            else paddle.CPUPlace()

    def test_static_api(self):
949
        paddle.enable_static()
950
        with paddle.static.program_guard(paddle.static.Program()):
951
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
            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):
973
        paddle.enable_static()
974 975 976 977 978 979 980 981
        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)

982
    def test_errors(self):
983
        paddle.enable_static()
984
        with paddle.static.program_guard(paddle.static.Program()):
985
            # The input type must be Variable.
986
            self.assertRaises(TypeError, F.softshrink, 1)
987
            # The input dtype must be float16, float32, float64.
988 989 990
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
991
            self.assertRaises(TypeError, F.softshrink, x_int32)
992
            # The threshold must be no less than zero
993 994 995
            x_fp32 = paddle.fluid.data(name='x_fp32',
                                       shape=[12, 10],
                                       dtype='float32')
996
            self.assertRaises(ValueError, F.softshrink, x_fp32, -1.0)
997
            # support the input dtype is float16
998 999 1000
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
1001
            F.softshrink(x_fp16)
1002 1003


1004
class TestSqrt(TestActivation, TestParameter):
1005

1006 1007
    def setUp(self):
        self.op_type = "sqrt"
1008
        self.python_api = paddle.sqrt
1009 1010
        self.init_dtype()

1011
        np.random.seed(1023)
1012 1013 1014 1015 1016
        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}
1017 1018

    def test_check_grad(self):
1019 1020
        if self.dtype == np.float16:
            return
1021 1022 1023 1024
        self.check_grad(['X'], 'Out', check_eager=True)

    def test_check_output(self):
        self.check_output(check_eager=True)
1025

1026

1027 1028 1029
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestSqrtBF16(OpTest):
1030

1031 1032
    def setUp(self):
        self.op_type = "sqrt"
1033
        self.python_api = paddle.sqrt
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        self.init_dtype()

        np.random.seed(1023)
        x = np.random.uniform(0.1, 1, [11, 17]).astype(np.float32)
        out = np.sqrt(x)

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

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

    def test_check_output(self):
        place = core.CUDAPlace(0)
1050
        self.check_output_with_place(place, check_eager=True)
1051 1052 1053

    def test_check_grad(self):
        place = core.CUDAPlace(0)
1054
        self.check_grad_with_place(place, ['X'], 'Out', check_eager=True)
1055 1056


Z
zhoukunsheng 已提交
1057
class TestRsqrt(TestActivation):
1058

Z
zhoukunsheng 已提交
1059 1060
    def setUp(self):
        self.op_type = "rsqrt"
Z
zyfncg 已提交
1061
        self.python_api = paddle.rsqrt
Z
zhoukunsheng 已提交
1062 1063
        self.init_dtype()

1064
        np.random.seed(1024)
Z
zhupengyang 已提交
1065
        x = np.random.uniform(0.1, 1, [10, 12]).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
1066 1067 1068 1069 1070 1071 1072 1073
        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
1074 1075 1076 1077
        self.check_grad(['X'],
                        'Out',
                        max_relative_error=0.0005,
                        check_eager=True)
Z
zhoukunsheng 已提交
1078 1079


C
chengduo 已提交
1080
class TestAbs(TestActivation):
1081

1082 1083
    def setUp(self):
        self.op_type = "abs"
1084 1085
        self.init_dtype()

1086
        np.random.seed(1024)
1087
        x = np.random.uniform(-1, 1, [4, 25]).astype(self.dtype)
C
chengduo 已提交
1088
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
1089
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
1090
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
1091 1092
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
1093 1094 1095 1096
        out = np.abs(x)

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

    def test_check_grad(self):
1099 1100
        if self.dtype == np.float16:
            return
1101
        self.check_grad(['X'], 'Out', check_eager=False)
1102

1103

C
chengduo 已提交
1104
class TestCeil(TestActivation):
1105

D
dzhwinter 已提交
1106 1107
    def setUp(self):
        self.op_type = "ceil"
1108 1109
        self.check_eager = True
        self.python_api = paddle.ceil
1110 1111
        self.init_dtype()

1112
        np.random.seed(1024)
Z
zhupengyang 已提交
1113
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1114 1115 1116 1117
        out = np.ceil(x)

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

D
dzhwinter 已提交
1119
    # The same reason with TestFloor
C
chengduo 已提交
1120
    def test_check_grad(self):
1121 1122 1123
        pass


C
chengduo 已提交
1124
class TestFloor(TestActivation):
1125

D
dzhwinter 已提交
1126 1127
    def setUp(self):
        self.op_type = "floor"
1128 1129
        self.check_eager = True
        self.python_api = paddle.floor
1130 1131
        self.init_dtype()

1132
        np.random.seed(1024)
Z
zhupengyang 已提交
1133
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1134 1135 1136 1137
        out = np.floor(x)

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

D
dzhwinter 已提交
1139
    # the gradient on floor, ceil, round is undefined.
1140
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
1141 1142
    # The same reason with TestFloor
    def test_check_grad(self):
1143 1144 1145
        pass


C
chengduo 已提交
1146
class TestCos(TestActivation):
1147

C
add cos  
chengduoZH 已提交
1148 1149
    def setUp(self):
        self.op_type = "cos"
1150 1151
        self.init_dtype()

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

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

    def test_check_grad(self):
1160 1161
        if self.dtype == np.float16:
            return
1162
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
1163

1164

J
joejiong 已提交
1165
class TestTan(TestActivation):
1166

J
joejiong 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    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)


1217
class TestAcos(TestActivation):
1218

1219 1220 1221 1222
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()

1223
        np.random.seed(1024)
Z
zhupengyang 已提交
1224
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
1225 1226 1227 1228 1229 1230 1231 1232
        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
1233
        self.check_grad(['X'], 'Out')
1234 1235


1236
class TestSin(TestActivation, TestParameter):
1237

C
add sin  
chengduoZH 已提交
1238 1239
    def setUp(self):
        self.op_type = "sin"
1240 1241
        self.init_dtype()

1242
        np.random.seed(1024)
Z
zhupengyang 已提交
1243
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1244 1245 1246 1247
        out = np.sin(x)

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

    def test_check_grad(self):
1250 1251
        if self.dtype == np.float16:
            return
1252
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
1253 1254


1255
class TestAsin(TestActivation):
1256

1257 1258 1259 1260
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()

1261
        np.random.seed(2048)
Z
zhupengyang 已提交
1262
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
1263 1264 1265 1266 1267 1268 1269 1270
        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
1271
        self.check_grad(['X'], 'Out')
1272 1273


X
xiaoting 已提交
1274
class TestAcosh(TestActivation):
1275

X
xiaoting 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    def setUp(self):
        self.op_type = "acosh"
        self.init_dtype()

        np.random.seed(1024)
        x = np.random.uniform(2, 3, [10, 12]).astype(self.dtype)
        out = np.arccosh(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')


class TestAsinh(TestActivation):
1294

X
xiaoting 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    def setUp(self):
        self.op_type = "asinh"
        self.init_dtype()

        np.random.seed(1024)
        x = np.random.uniform(1, 2, [10, 12]).astype(self.dtype)
        out = np.arcsinh(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')


class TestAtanh(TestActivation):
1313

X
xiaoting 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    def setUp(self):
        self.op_type = "atanh"
        self.init_dtype()

        np.random.seed(400)
        x = np.random.uniform(-0.9, 0.9, [10, 12]).astype(self.dtype)
        out = np.arctanh(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')


C
chengduo 已提交
1331
class TestRound(TestActivation):
1332

D
dzhwinter 已提交
1333 1334
    def setUp(self):
        self.op_type = "round"
1335 1336
        self.check_eager = True
        self.python_api = paddle.round
1337 1338
        self.init_dtype()

1339
        np.random.seed(1024)
Z
zhupengyang 已提交
1340
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1341 1342 1343 1344
        out = np.round(x)

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

C
chengduo 已提交
1346
    def test_check_grad(self):
1347 1348 1349
        pass


C
chengduo 已提交
1350
class TestRelu(TestActivation):
1351

1352
    def setUp(self):
Q
qijun 已提交
1353
        self.op_type = "relu"
K
Kexin Zhao 已提交
1354 1355
        self.init_dtype()

1356
        np.random.seed(1024)
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
        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 已提交
1369 1370

        self.outputs = {'Out': out}
1371 1372

    def test_check_grad(self):
K
Kexin Zhao 已提交
1373 1374
        if self.dtype == np.float16:
            return
1375
        self.check_grad(['X'], 'Out')
A
Adam 已提交
1376 1377


1378 1379 1380
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1381
        np.random.seed(1024)
1382
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
1383
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1384
            else paddle.CPUPlace()
1385 1386 1387 1388
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1389 1390

    def test_static_api(self):
1391
        paddle.enable_static()
1392
        with paddle.static.program_guard(paddle.static.Program()):
1393
            x = paddle.fluid.data('X', [10, 12])
1394
            out1 = self.relu(x)
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
            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()
1407 1408
        out1 = m(x)
        out2 = self.relu(x)
1409 1410 1411 1412 1413
        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()

1414
    def test_errors(self):
1415
        paddle.enable_static()
1416
        with paddle.static.program_guard(paddle.static.Program()):
1417
            # The input type must be Variable.
1418
            self.assertRaises(TypeError, self.relu, 1)
1419
            # The input dtype must be float16, float32, float64.
1420 1421 1422
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[10, 12],
                                        dtype='int32')
1423
            self.assertRaises(TypeError, self.relu, x_int32)
1424
            # support the input dtype is float16
1425 1426 1427
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[10, 12],
                                       dtype='float16')
1428 1429 1430 1431 1432 1433 1434
            self.relu(x_fp16)


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


1437 1438 1439 1440 1441 1442
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1443
class TestLeakyRelu(TestActivation):
1444

1445 1446 1447
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1448 1449 1450
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()
1451
        alpha = self.get_alpha()
A
Adam 已提交
1452

1453
        np.random.seed(1024)
A
Adam 已提交
1454 1455
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        # The same reason with TestAbs
1456 1457
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1458

1459
        self.inputs = {'X': x}
A
Adam 已提交
1460
        self.outputs = {'Out': out}
1461
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1462 1463 1464 1465

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


1469
class TestLeakyReluAlpha1(TestLeakyRelu):
1470

1471 1472 1473 1474 1475
    def get_alpha(self):
        return 2


class TestLeakyReluAlpha2(TestLeakyRelu):
1476

1477 1478 1479 1480 1481
    def get_alpha(self):
        return -0.01


class TestLeakyReluAlpha3(TestLeakyRelu):
1482

1483 1484 1485 1486 1487 1488 1489 1490
    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):
1491
        np.random.seed(1024)
1492
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
1493
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1494 1495 1496
            else paddle.CPUPlace()

    def test_static_api(self):
1497
        paddle.enable_static()
1498
        with paddle.static.program_guard(paddle.static.Program()):
1499
            x = paddle.fluid.data('X', [10, 12])
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
            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 已提交
1511
        x = paddle.to_tensor(self.x_np)
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
        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):
1528
        paddle.enable_static()
1529 1530 1531 1532 1533 1534 1535 1536
        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)

1537
    def test_errors(self):
1538
        paddle.enable_static()
1539
        with paddle.static.program_guard(paddle.static.Program()):
1540
            # The input type must be Variable.
1541
            self.assertRaises(TypeError, F.leaky_relu, 1)
1542
            # The input dtype must be float16, float32, float64.
1543 1544 1545
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
1546 1547
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
1548 1549 1550
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
1551
            F.leaky_relu(x_fp16)
1552 1553


1554 1555
def gelu(x, approximate):
    if approximate:
1556 1557
        y_ref = 0.5 * x * (
            1.0 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
1558 1559 1560 1561 1562 1563
    else:
        y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
    return y_ref.astype(x.dtype)


class TestGeluApproximate(TestActivation):
1564

C
Clementine 已提交
1565 1566 1567
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1568
        approximate = True
1569
        np.random.seed(1024)
1570 1571
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
1572

1573
        self.inputs = {'X': x}
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
        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):
1584

1585 1586 1587 1588
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
        approximate = False
1589
        np.random.seed(2048)
C
Clementine 已提交
1590
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1591
        out = gelu(x, approximate)
C
Clementine 已提交
1592

1593
        self.inputs = {'X': x}
C
Clementine 已提交
1594
        self.outputs = {'Out': out}
1595
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1596 1597 1598 1599

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


1603 1604 1605
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1606
        np.random.seed(1024)
1607
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
J
joejiong 已提交
1608
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1609 1610 1611
            else paddle.CPUPlace()

    def test_static_api(self):
1612
        paddle.enable_static()
1613
        with paddle.static.program_guard(paddle.static.Program()):
1614
            x = paddle.fluid.data('X', [11, 17])
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
            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):
1643
        paddle.enable_static()
1644 1645 1646 1647
        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.
1648 1649 1650
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[11, 17],
                                        dtype='int32')
1651 1652
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
1653 1654 1655
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[11, 17],
                                       dtype='float16')
1656 1657 1658
            F.gelu(x_fp16)


C
chengduo 已提交
1659
class TestBRelu(TestActivation):
1660

1661 1662
    def setUp(self):
        self.op_type = "brelu"
1663 1664
        self.init_dtype()

1665
        np.random.seed(1024)
Z
zhupengyang 已提交
1666
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1667 1668
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
1669 1670
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
1671
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
1672 1673 1674
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
1675 1676 1677

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

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

1685

1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
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 已提交
1697
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
            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()

1714 1715 1716 1717 1718 1719 1720 1721
    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
1722 1723 1724
            x_fp16 = fluid.layers.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
1725 1726 1727
            fluid.layers.brelu(x_fp16)


1728 1729 1730 1731 1732 1733 1734
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 已提交
1735
class TestRelu6(TestActivation):
1736

K
Kavya Srinet 已提交
1737
    def setUp(self):
1738
        self.op_type = "relu6"
1739
        self.init_dtype()
1740
        self.python_api = paddle.nn.functional.relu6
1741

1742
        np.random.seed(1024)
Z
zhupengyang 已提交
1743
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
1744
        x[np.abs(x) < 0.005] = 0.02
1745
        out = ref_relu6(x)
1746

1747 1748
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
1749
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
1750

1751 1752 1753
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1754
        self.check_grad(['X'], 'Out', check_eager=True)
1755 1756


1757 1758 1759
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
1760
        np.random.seed(1024)
1761 1762
        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 已提交
1763
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1764 1765 1766
            else paddle.CPUPlace()

    def test_static_api(self):
1767
        paddle.enable_static()
1768
        with paddle.static.program_guard(paddle.static.Program()):
1769
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
            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):
1791
        paddle.enable_static()
1792 1793 1794 1795 1796 1797 1798 1799
        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)

1800
    def test_errors(self):
1801
        paddle.enable_static()
1802
        with paddle.static.program_guard(paddle.static.Program()):
1803
            # The input type must be Variable.
1804
            self.assertRaises(TypeError, F.relu6, 1)
1805
            # The input dtype must be float16, float32, float64.
1806 1807 1808
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
1809
            self.assertRaises(TypeError, F.relu6, x_int32)
1810
            # support the input dtype is float16
1811 1812 1813
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
1814
            F.relu6(x_fp16)
1815 1816


1817 1818 1819 1820 1821
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 已提交
1822
class TestHardSwish(TestActivation):
1823

H
huangjun12 已提交
1824 1825 1826
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()
1827
        self.python_api = paddle.nn.functional.hardswish
J
jakpiase 已提交
1828 1829
        skip_check_grad_ci(reason="not implemented yet")

1830
        np.random.seed(1024)
Z
zhupengyang 已提交
1831
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
1832 1833 1834 1835 1836 1837
        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
1838
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
1839

1840
        self.inputs = {'X': x}
H
huangjun12 已提交
1841 1842 1843 1844 1845 1846
        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 已提交
1847 1848

        return  # not implemented yet
1849 1850 1851 1852
        self.check_grad(['X'], 'Out', check_eager=True)

    def test_check_output(self):
        self.check_output(check_eager=True)
H
huangjun12 已提交
1853 1854


1855 1856 1857 1858
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 已提交
1859
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1860 1861 1862 1863
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
1864
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
            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()))
1883
        paddle.enable_static()
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901

    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()):
1902
            # The input type must be Variable.
1903
            self.assertRaises(TypeError, F.hardswish, 1)
1904
            # The input dtype must be float16, float32, float64.
1905 1906 1907
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
1908
            self.assertRaises(TypeError, F.hardswish, x_int32)
1909
            # support the input dtype is float16
1910 1911 1912
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
1913
            F.hardswish(x_fp16)
1914

1915 1916 1917 1918 1919
    def test_api_eager_dygraph(self):
        with _test_eager_guard():
            self.test_dygraph_api()
            self.test_errors()

1920

C
chengduo 已提交
1921
class TestSoftRelu(TestActivation):
1922

1923 1924
    def setUp(self):
        self.op_type = "soft_relu"
1925 1926
        self.init_dtype()

1927
        np.random.seed(4096)
1928
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1929
        threshold = 2.0
Q
qijun 已提交
1930 1931
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
1932
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
1933 1934 1935
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
1936 1937 1938 1939 1940
        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}
1941 1942

    def test_check_grad(self):
1943 1944
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1945
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
1946

1947

1948
class TestSoftReluOpError(unittest.TestCase):
1949

1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    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)


1962
def elu(x, alpha):
Z
zhupengyang 已提交
1963
    out_ref = np.where(x > 0, x, alpha * (np.exp(x) - 1))
1964 1965 1966
    return out_ref.astype(x.dtype)


C
chengduo 已提交
1967
class TestELU(TestActivation):
1968

1969 1970
    def setUp(self):
        self.op_type = "elu"
1971 1972
        self.init_dtype()

1973
        np.random.seed(1024)
Z
zhupengyang 已提交
1974
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
Z
zhupengyang 已提交
1975
        alpha = self.get_alpha()
1976
        out = elu(x, alpha)
1977 1978 1979 1980
        # 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}
1981
        self.outputs = {'Out': out}
1982 1983

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

Z
zhupengyang 已提交
1988 1989 1990 1991 1992
    def get_alpha(self):
        return 1.


class TestELUAlpha(TestELU):
1993

Z
zhupengyang 已提交
1994 1995 1996
    def get_alpha(self):
        return -0.2

1997

1998 1999 2000
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
2001
        np.random.seed(1024)
2002
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
J
joejiong 已提交
2003
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2004
            else paddle.CPUPlace()
2005 2006 2007 2008
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
2009 2010

    def test_static_api(self):
2011
        paddle.enable_static()
2012
        with paddle.static.program_guard(paddle.static.Program()):
2013
            x = paddle.fluid.data('X', [10, 12])
2014
            out1 = self.elu(x)
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
            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)
2026 2027
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
2028 2029 2030 2031 2032 2033
        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)

2034 2035
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
2036 2037 2038 2039 2040 2041 2042
        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()

2043
    def test_errors(self):
2044
        paddle.enable_static()
2045 2046
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
2047
            self.assertRaises(TypeError, self.elu, 1)
2048
            # The input dtype must be float16, float32, float64.
2049 2050 2051
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[10, 12],
                                        dtype='int32')
2052
            self.assertRaises(TypeError, self.elu, x_int32)
2053
            # support the input dtype is float16
2054 2055 2056
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[10, 12],
                                       dtype='float16')
2057 2058 2059
            self.elu(x_fp16)


Z
zhupengyang 已提交
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
class TestELUInplaceAPI(TestELUAPI):
    # test paddle.nn.functional.elu_
    def executed_api(self):
        self.elu = F.elu_

    def test_alpha_error(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        self.assertRaises(Exception, F.elu_, x, -0.2)
        paddle.enable_static()


2072 2073 2074 2075 2076 2077
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):
2078

2079 2080 2081 2082
    def setUp(self):
        self.op_type = "celu"
        self.init_dtype()

2083
        self.python_api = paddle.nn.functional.celu
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
        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
2095
        self.check_grad(['X'], 'Out', check_eager=True)
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148


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.
2149 2150 2151
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[10, 12],
                                        dtype='int32')
2152 2153
            self.assertRaises(TypeError, self.celu, x_int32)
            # The alpha must be not equal 0
2154 2155 2156
            x_fp32 = paddle.fluid.data(name='x_fp32',
                                       shape=[10, 12],
                                       dtype='float32')
2157 2158
            self.assertRaises(ZeroDivisionError, F.celu, x_fp32, 0)
            # support the input dtype is float16
2159 2160 2161
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[10, 12],
                                       dtype='float16')
2162 2163
            self.celu(x_fp16)

2164 2165 2166 2167 2168
    def test_api_eager_dygraph(self):
        with _test_eager_guard():
            self.test_dygraph_api()
            self.test_errors()

2169

C
chengduo 已提交
2170
class TestReciprocal(TestActivation):
2171

Q
qijun 已提交
2172 2173
    def setUp(self):
        self.op_type = "reciprocal"
2174
        self.python_api = paddle.reciprocal
2175 2176
        self.init_dtype()

2177
        np.random.seed(1024)
2178 2179 2180 2181 2182
        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 已提交
2183 2184

    def test_check_grad(self):
2185 2186
        if self.dtype == np.float16:
            return
2187 2188 2189 2190
        self.check_grad(['X'], 'Out', max_relative_error=0.01, check_eager=True)

    def test_check_output(self):
        self.check_output(check_eager=True)
Q
qijun 已提交
2191 2192


C
chengduo 已提交
2193
class TestLog(TestActivation):
2194

Q
qijun 已提交
2195 2196
    def setUp(self):
        self.op_type = "log"
2197 2198
        self.check_eager = True
        self.python_api = paddle.log
2199 2200
        self.init_dtype()

2201
        np.random.seed(1024)
2202 2203 2204 2205 2206
        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 已提交
2207 2208

    def test_check_grad(self):
2209 2210
        if self.dtype == np.float16:
            return
2211
        self.check_grad(['X'], 'Out', check_eager=True)
Q
qijun 已提交
2212

2213
    def test_error(self):
2214 2215 2216 2217 2218 2219 2220 2221
        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")
2222 2223 2224 2225

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

2226

J
joejiong 已提交
2227
class TestLog2(TestActivation):
2228

J
joejiong 已提交
2229 2230
    def setUp(self):
        self.op_type = "log2"
2231 2232
        self.check_eager = True
        self.python_api = paddle.log2
J
joejiong 已提交
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
        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
2244
        self.check_grad(['X'], 'Out', check_eager=True)
J
joejiong 已提交
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256

    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")
2257 2258 2259
            data_x = paddle.static.data(name="data_x",
                                        shape=[11, 17],
                                        dtype="float64")
J
joejiong 已提交
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279

            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 已提交
2280
class TestLog10(TestActivation):
2281

J
joejiong 已提交
2282 2283
    def setUp(self):
        self.op_type = "log10"
2284 2285
        self.check_eager = True
        self.python_api = paddle.log10
J
joejiong 已提交
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
        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
2297
        self.check_grad(['X'], 'Out', check_eager=True)
J
joejiong 已提交
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309

    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")
2310 2311 2312
            data_x = paddle.static.data(name="data_x",
                                        shape=[11, 17],
                                        dtype="float64")
J
joejiong 已提交
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332

            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))


2333
class TestLog1p(TestActivation):
2334

2335 2336
    def setUp(self):
        self.op_type = "log1p"
2337 2338
        self.check_eager = True
        self.python_api = paddle.log1p
2339 2340
        self.init_dtype()

2341
        np.random.seed(1024)
2342 2343 2344 2345 2346 2347 2348 2349 2350
        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
2351
        self.check_grad(['X'], 'Out', check_eager=True)
2352 2353 2354 2355

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

            out1 = paddle.log1p(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
2364 2365 2366
            res1 = exe.run(fluid.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
2367
        expected_res = np.log1p(input_x)
2368
        self.assertTrue(np.allclose(res1, expected_res))
2369 2370 2371 2372 2373 2374 2375 2376

        # 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))
2377
        self.assertTrue(np.allclose(np_z, z_expected))
2378 2379


C
chengduo 已提交
2380
class TestSquare(TestActivation):
2381

Q
qijun 已提交
2382 2383
    def setUp(self):
        self.op_type = "square"
2384
        self.python_api = paddle.square
2385 2386
        self.init_dtype()

2387
        np.random.seed(1024)
2388 2389 2390 2391 2392
        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 已提交
2393 2394

    def test_check_grad(self):
2395 2396
        if self.dtype == np.float16:
            return
2397 2398 2399 2400
        self.check_grad(['X'],
                        'Out',
                        max_relative_error=0.007,
                        check_eager=True)
2401 2402 2403

    def test_check_output(self):
        self.check_output(check_eager=True)
Q
qijun 已提交
2404

2405

2406 2407 2408
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestSquareBF16(OpTest):
2409

2410 2411
    def setUp(self):
        self.op_type = "square"
2412
        self.python_api = paddle.square
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
        self.init_dtype()

        np.random.seed(1024)
        x = np.random.uniform(0.1, 1, [11, 17]).astype(np.float32)
        out = np.square(x)

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

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

    def test_check_output(self):
        place = core.CUDAPlace(0)
2429
        self.check_output_with_place(place, check_eager=True)
2430 2431 2432

    def test_check_grad(self):
        place = core.CUDAPlace(0)
2433 2434 2435 2436
        self.check_grad_with_place(place, ['X'],
                                   'Out',
                                   numeric_grad_delta=0.5,
                                   check_eager=True)
2437 2438


C
chengduo 已提交
2439
class TestPow(TestActivation):
2440

2441 2442
    def setUp(self):
        self.op_type = "pow"
2443
        self.python_api = paddle.pow
2444
        self.check_eager = True
2445 2446
        self.init_dtype()

2447
        np.random.seed(1024)
2448 2449 2450 2451
        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) 已提交
2452
        self.attrs = {'factor': 3.0}
2453
        self.outputs = {'Out': out}
2454

2455 2456 2457
    def test_check_output(self):
        self.check_output(check_eager=self.check_eager)

2458
    def test_check_grad(self):
2459 2460
        if self.dtype == np.float16:
            return
2461
        self.check_grad(['X'], 'Out', check_eager=self.check_eager)
2462

2463

2464
class TestPow_factor_tensor(TestActivation):
2465

2466 2467
    def setUp(self):
        self.op_type = "pow"
2468 2469
        self.check_eager = False
        self.python_api = paddle.pow
2470 2471
        self.init_dtype()

2472
        np.random.seed(1024)
2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
        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):
2485
        self.check_output(check_eager=self.check_eager)
2486 2487 2488 2489

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

    def test_api(self):
        input = np.random.uniform(1, 2, [11, 17]).astype("float32")
2494 2495 2496 2497 2498 2499 2500 2501
        x = fluid.layers.data(name="x",
                              shape=[11, 17],
                              append_batch_size=False,
                              dtype="float32")
        res = fluid.layers.data(name="res",
                                shape=[11, 17],
                                append_batch_size=False,
                                dtype="float32")
2502 2503 2504 2505 2506

        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)
2507 2508 2509
        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)
2510 2511

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
2512
        res_1, res_2, res, res_6 = exe.run(
2513 2514
            fluid.default_main_program(),
            feed={"x": input},
W
WuHaobo 已提交
2515
            fetch_list=[out_1, out_2, res, out_6])
2516

2517 2518 2519
        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))
2520

2521
    def test_error(self):
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
        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")
2538 2539 2540 2541 2542 2543 2544 2545

        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)

2546

2547 2548 2549 2550 2551
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
2552
class TestSTanh(TestActivation):
2553

2554 2555 2556 2557 2558 2559
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

2560 2561
    def setUp(self):
        self.op_type = "stanh"
2562
        self.init_dtype()
2563 2564
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
2565

2566
        np.random.seed(1024)
2567
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
2568 2569
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
2570

2571
        self.inputs = {'X': x}
2572
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
2573
        self.outputs = {'Out': out}
2574

Q
qijun 已提交
2575
    def test_check_grad(self):
2576 2577
        if self.dtype == np.float16:
            return
2578
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
2579

2580

2581
class TestSTanhScaleA(TestSTanh):
2582

2583 2584 2585 2586 2587
    def get_scale_a(self):
        return 2.0


class TestSTanhScaleB(TestSTanh):
2588

2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
    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)

2639
    def test_errors(self):
2640 2641
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2642
            # The input type must be Variable.
2643
            self.assertRaises(TypeError, paddle.stanh, 1)
2644
            # The input dtype must be float16, float32, float64.
2645 2646 2647
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
2648
            self.assertRaises(TypeError, paddle.stanh, x_int32)
2649
            # support the input dtype is float16
2650 2651 2652
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
2653 2654 2655 2656
            paddle.stanh(x_fp16)


class TestSTanhAPIScaleA(TestSTanhAPI):
2657

2658 2659 2660 2661 2662
    def get_scale_a(self):
        return 2.0


class TestSTanhAPIScaleB(TestSTanhAPI):
2663

2664 2665
    def get_scale_b(self):
        return 0.5
2666 2667


2668 2669 2670 2671 2672 2673 2674
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 已提交
2675
class TestSoftplus(TestActivation):
2676

K
kexinzhao 已提交
2677 2678
    def setUp(self):
        self.op_type = "softplus"
2679 2680
        self.init_dtype()

2681 2682
        beta = 2
        threshold = 15
2683

2684
        np.random.seed(1024)
2685 2686 2687 2688
        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}
2689
        self.outputs = {'Out': out}
K
kexinzhao 已提交
2690 2691

    def test_check_grad(self):
2692 2693
        if self.dtype == np.float16:
            return
2694
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
2695

2696

2697 2698 2699
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestSoftplusBF16(OpTest):
2700

2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
    def setUp(self):
        self.op_type = "softplus"
        self.init_dtype()

        beta = 2
        threshold = 15

        np.random.seed(1024)
        x = np.random.uniform(-1, 1, [10, 12]).astype(np.float32)
        out = ref_softplus(x, beta, threshold)
        self.inputs = {'X': convert_float_to_uint16(x)}
        self.attrs = {'beta': beta, "threshold": threshold}
        self.outputs = {'Out': convert_float_to_uint16(out)}

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

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

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


2727 2728 2729 2730 2731
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
2732
        np.random.seed(1024)
2733
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2734
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2735 2736 2737
            else paddle.CPUPlace()

    def test_static_api(self):
2738
        paddle.enable_static()
2739
        with paddle.static.program_guard(paddle.static.Program()):
2740
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
            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):
2762
        paddle.enable_static()
2763 2764 2765 2766 2767 2768 2769 2770 2771
        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):
2772
        paddle.enable_static()
2773 2774 2775 2776
        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.
2777 2778 2779
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
2780 2781
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
2782 2783 2784
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
2785 2786 2787 2788 2789 2790 2791 2792
            F.softplus(x_fp16)


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


C
chengduo 已提交
2793
class TestSoftsign(TestActivation):
2794

2795 2796
    def setUp(self):
        self.op_type = "softsign"
2797 2798
        self.init_dtype()

2799
        np.random.seed(1024)
2800 2801 2802
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softsign(x)
        self.inputs = {'X': x}
2803
        self.outputs = {'Out': out}
2804 2805

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


2811 2812 2813
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
2814
        np.random.seed(1024)
2815
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2816
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2817 2818 2819
            else paddle.CPUPlace()

    def test_static_api(self):
2820
        paddle.enable_static()
2821
        with paddle.static.program_guard(paddle.static.Program()):
2822
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843
            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):
2844
        paddle.enable_static()
2845 2846 2847 2848 2849 2850 2851 2852 2853
        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):
2854
        paddle.enable_static()
2855 2856 2857 2858
        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.
2859 2860 2861
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
2862 2863
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
2864 2865 2866
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
2867 2868 2869
            F.softsign(x_fp16)


2870 2871 2872 2873 2874
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
2875
class TestThresholdedRelu(TestActivation):
2876

2877 2878
    def setUp(self):
        self.op_type = "thresholded_relu"
2879 2880
        self.init_dtype()

2881
        threshold = 15
2882

2883 2884 2885 2886 2887 2888
        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}
2889
        self.outputs = {'Out': out}
2890 2891

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


2897 2898 2899 2900 2901 2902 2903
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 已提交
2904
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2905 2906 2907 2908 2909
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2910
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
            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)

2941
    def test_errors(self):
2942 2943
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2944
            # The input type must be Variable.
2945
            self.assertRaises(TypeError, F.thresholded_relu, 1)
2946
            # The input dtype must be float16, float32, float64.
2947 2948 2949
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
2950
            self.assertRaises(TypeError, F.thresholded_relu, x_int32)
2951
            # support the input dtype is float16
2952 2953 2954
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
2955
            F.thresholded_relu(x_fp16)
2956 2957


2958 2959 2960 2961
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 已提交
2962
class TestHardSigmoid(TestActivation):
2963

2964 2965
    def setUp(self):
        self.op_type = "hard_sigmoid"
2966 2967 2968 2969
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
2970

2971 2972 2973
        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 已提交
2974

2975
        # Same reason as TestAbs
2976 2977 2978
        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
2979

2980
        out = ref_hardsigmoid(x, self.slope, self.offset)
2981

2982 2983
        self.attrs = {'slope': self.slope, 'offset': self.offset}
        self.inputs = {'X': x}
2984
        self.outputs = {'Out': out}
2985

2986 2987
    def set_attrs(self):
        pass
2988

2989

2990
class TestHardSigmoidFP32(TestHardSigmoid):
2991

2992 2993 2994 2995 2996
    def set_attrs(self):
        self.dtype = 'float32'


class TestHardSigmoidSlopeOffset(TestHardSigmoid):
2997

2998 2999 3000 3001 3002 3003 3004 3005 3006
    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 已提交
3007
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
3008 3009 3010 3011
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
3012
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
            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()))
3031
        paddle.enable_static()
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049

    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()):
3050
            # The input type must be Variable.
3051
            self.assertRaises(TypeError, F.hardsigmoid, 1)
3052
            # The input dtype must be float16, float32, float64.
3053 3054 3055
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
3056
            self.assertRaises(TypeError, F.hardsigmoid, x_int32)
3057
            # support the input dtype is float16
3058 3059 3060
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
3061
            F.hardsigmoid(x_fp16)
3062 3063


3064 3065 3066 3067 3068
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
3069
class TestSwish(TestActivation):
3070

A
Abhinav Arora 已提交
3071 3072
    def setUp(self):
        self.op_type = "swish"
3073
        self.python_api = paddle.nn.functional.swish
3074
        self.init_dtype()
3075
        self.check_eager = True
3076

3077
        np.random.seed(1024)
3078 3079 3080
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_swish(x)
        self.inputs = {'X': x}
H
hong19860320 已提交
3081
        self.attrs = {'beta': 1.0}
3082
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
3083 3084

    def test_check_grad(self):
3085 3086
        if self.dtype == np.float16:
            return
3087 3088 3089 3090
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
3091

A
Abhinav Arora 已提交
3092

3093 3094 3095 3096 3097
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 已提交
3098
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
3099 3100 3101 3102 3103
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
3104
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
            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()

3125 3126 3127 3128
    def test_dygraph_final_state_api(self):
        with _test_eager_guard():
            self.test_dygraph_api()

3129 3130 3131 3132 3133 3134 3135 3136 3137
    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)
3138

3139
    def test_errors(self):
3140 3141
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3142
            # The input type must be Variable.
3143
            self.assertRaises(TypeError, F.swish, 1)
3144
            # The input dtype must be float16, float32, float64.
3145 3146 3147
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
3148
            self.assertRaises(TypeError, F.swish, x_int32)
3149
            # support the input dtype is float16
3150 3151 3152
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
3153
            F.swish(x_fp16)
3154 3155


3156 3157 3158 3159 3160 3161 3162
def ref_mish(x, threshold=20.):
    softplus = np.select([x <= threshold, x > threshold],
                         [np.log(1 + np.exp(x)), x])
    return x * np.tanh(softplus)


class TestMish(TestActivation):
3163

3164 3165
    def setUp(self):
        self.op_type = "mish"
3166
        self.python_api = paddle.fluid.layers.nn.mish
3167 3168 3169 3170 3171 3172 3173 3174
        self.init_dtype()

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

3175 3176 3177
    def test_check_output(self):
        self.check_output(check_eager=True)

3178 3179 3180
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
3181
        self.check_grad(['X'], 'Out', check_eager=True)
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231


class TestMishAPI(unittest.TestCase):
    # test paddle.nn.Mish, paddle.nn.functional.mish
    def setUp(self):
        np.random.seed(1024)
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
        self.place=paddle.CUDAPlace(0) if paddle.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.static.data('X', self.x_np.shape, self.x_np.dtype)
            out1 = F.mish(x)
            mish = paddle.nn.Mish()
            out2 = mish(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_mish(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.mish(x)
        mish = paddle.nn.Mish()
        out2 = mish(x)
        out_ref = ref_mish(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.mish(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_mish(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.mish, 1)
            # The input dtype must be float16, float32, float64.
3232 3233 3234
            x_int32 = paddle.fluid.data(name='x_int32',
                                        shape=[12, 10],
                                        dtype='int32')
3235 3236
            self.assertRaises(TypeError, F.mish, x_int32)
            # support the input dtype is float16
3237 3238 3239
            x_fp16 = paddle.fluid.data(name='x_fp16',
                                       shape=[12, 10],
                                       dtype='float16')
3240 3241 3242
            F.mish(x_fp16)


3243 3244
#------------------ Test Error Activation----------------------
def create_test_error_class(op_type):
3245

3246
    class TestOpErrors(unittest.TestCase):
3247

3248 3249 3250 3251
        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.
3252 3253 3254 3255 3256 3257
                in1 = fluid.layers.data(name='input2',
                                        shape=[12, 10],
                                        dtype="int32")
                in2 = fluid.layers.data(name='input3',
                                        shape=[12, 10],
                                        dtype="int64")
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
                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 已提交
3278
create_test_error_class('tan')
X
xiaoting 已提交
3279 3280 3281
create_test_error_class('acosh')
create_test_error_class('asinh')
create_test_error_class('atanh')
3282 3283


3284 3285
#------------------ Test Cudnn Activation----------------------
def create_test_act_cudnn_class(parent, atol=1e-3, grad_atol=1e-3):
3286

3287 3288 3289
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActCudnn(parent):
3290

3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
        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 已提交
3305 3306 3307 3308 3309
#------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(parent,
                               atol=1e-3,
                               grad_check=True,
                               grad_atol=0.80):
3310

J
joejiong 已提交
3311
    @unittest.skipIf(not paddle.is_compiled_with_cuda(),
C
chengduo 已提交
3312 3313
                     "core is not compiled with CUDA")
    class TestActFp16(parent):
3314

C
chengduo 已提交
3315 3316
        def init_dtype(self):
            self.dtype = np.float16
3317

C
chengduo 已提交
3318
        def test_check_output(self):
3319
            place = core.CUDAPlace(0)
C
chengduo 已提交
3320 3321 3322
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
3323

C
chengduo 已提交
3324 3325 3326 3327
        def test_check_grad(self):
            place = core.CUDAPlace(0)
            support_fp16 = core.is_float16_supported(place)
            if support_fp16 and grad_check:
3328 3329 3330
                self.check_grad_with_place(place, ['X'],
                                           'Out',
                                           max_relative_error=grad_atol)
C
chengduo 已提交
3331 3332 3333 3334 3335 3336 3337

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


create_test_act_fp16_class(TestActivation)
R
ronnywang 已提交
3338
create_test_act_fp16_class(TestExpm1)
C
chengduo 已提交
3339
create_test_act_fp16_class(TestSigmoid)
M
minghaoBD 已提交
3340
create_test_act_fp16_class(TestSilu)
C
chengduo 已提交
3341 3342
create_test_act_fp16_class(TestLogSigmoid)
create_test_act_fp16_class(TestTanh)
3343
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
3344
create_test_act_fp16_class(TestHardShrink)
3345
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
3346 3347 3348 3349 3350
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 已提交
3351
create_test_act_fp16_class(TestTan, grad_atol=0.85)
3352
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
3353
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
3354
create_test_act_fp16_class(TestSin)
3355
create_test_act_fp16_class(TestSinh)
3356 3357
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
X
xiaoting 已提交
3358 3359 3360
create_test_act_fp16_class(TestAcosh, grad_atol=0.85)
create_test_act_fp16_class(TestAsinh, grad_atol=0.85)
create_test_act_fp16_class(TestAtanh, grad_atol=0.85)
C
chengduo 已提交
3361 3362
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
3363
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
3364 3365
create_test_act_fp16_class(TestBRelu)
create_test_act_fp16_class(TestRelu6)
3366
create_test_act_fp16_class(TestSoftRelu, grad_atol=0.85)
C
chengduo 已提交
3367
create_test_act_fp16_class(TestELU)
3368
create_test_act_fp16_class(TestCELU)
C
chengduo 已提交
3369 3370
create_test_act_fp16_class(TestReciprocal)
create_test_act_fp16_class(TestLog)
3371 3372 3373 3374
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 已提交
3375
create_test_act_fp16_class(TestLog10, atol=5e-2)
3376
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
3377 3378
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
3379
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
3380 3381 3382 3383 3384
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)
3385
create_test_act_fp16_class(TestSwish, grad_atol=0.85)
H
huangjun12 已提交
3386
create_test_act_fp16_class(TestHardSwish)
3387
create_test_act_fp16_class(TestMish, grad_atol=0.9)
A
Abhinav Arora 已提交
3388

3389 3390 3391 3392 3393

def create_test_act_bf16_class(parent,
                               atol=1e-2,
                               grad_check=True,
                               grad_atol=0.80):
3394

3395 3396 3397
    @unittest.skipIf(not paddle.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActBF16(parent):
3398

3399 3400 3401 3402 3403 3404 3405 3406 3407
        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)
3408 3409 3410
            self.check_grad_with_place(place, ['X'],
                                       'Out',
                                       max_relative_error=grad_atol)
3411 3412 3413 3414 3415 3416 3417 3418

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


create_test_act_bf16_class(TestRelu)

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