test_activation_op.py 115.0 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.

Q
qijun 已提交
15
import unittest
J
joejiong 已提交
16

Q
qijun 已提交
17
import numpy as np
18
from op_test import OpTest, convert_float_to_uint16
19 20
from scipy.special import erf, expit

21
import paddle
J
joejiong 已提交
22 23
import paddle.fluid as fluid
import paddle.fluid.core as core
24
import paddle.nn.functional as F
25
from paddle.fluid import Program, program_guard
Q
qijun 已提交
26

27 28
paddle.enable_static()

Q
qijun 已提交
29

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

G
GGBond8488 已提交
42 43
            in3 = paddle.static.data(
                name='input3', shape=[-1, 12, 10], dtype="float16"
44
            )
45
            paddle.sqrt(x=in3)
Z
Zhaolong Xing 已提交
46 47


C
chengduo 已提交
48
class TestActivation(OpTest):
Q
qijun 已提交
49 50
    def setUp(self):
        self.op_type = "exp"
51
        self.init_dtype()
52
        self.init_shape()
53
        self.init_kernel_type()
C
chentianyu03 已提交
54 55
        self.check_eager = True
        self.python_api = paddle.exp
56

57
        np.random.seed(2049)
58
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
59 60 61 62
        out = np.exp(x)

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

    def test_check_output(self):
65 66 67 68
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_output(check_eager=check_eager)
Q
qijun 已提交
69 70

    def test_check_grad(self):
71 72
        if self.dtype == np.float16:
            return
73 74 75 76
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
Q
qijun 已提交
77

78
    def init_dtype(self):
79
        self.dtype = np.float64
80

81 82 83
    def init_shape(self):
        self.shape = [11, 17]

84 85 86
    def init_kernel_type(self):
        pass

Q
qijun 已提交
87

88 89 90 91 92
class TestActivation_ZeroDim(TestActivation):
    def init_shape(self):
        self.shape = []


93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
class TestExpPrimFp32(OpTest):
    def setUp(self):
        self.op_type = "exp"
        self.prim_op_type = "prim"
        self.init_dtype()
        self.init_shape()
        self.python_api = paddle.exp

        np.random.seed(2049)
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
        out = np.exp(x)

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

    def test_check_output(self):
        self.check_output()

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

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

    def init_shape(self):
        self.shape = [12, 17]

    def skip_cinn(self):
        self.enable_cinn = False

    def set_only_prim(self):
        pass


class TestExpPrimFp64(TestExpPrimFp32):
    def init_dtype(self):
        self.dtype = np.float64


class TestExpPrimFp16(TestExpPrimFp32):
    def init_dtype(self):
        self.dtype = np.float16

    def set_only_prim(self):
        self.only_prim = True

    def test_check_output(self):
        self.check_output()

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

    def skip_cinn(self):
        self.enable_cinn = False


class TestExpPrim_ZeroDim(TestExpPrimFp32):
    def init_shape(self):
        self.shape = []

    def skip_cinn(self):
        self.enable_cinn = False


R
ronnywang 已提交
159 160 161
class TestExpm1(TestActivation):
    def setUp(self):
        self.op_type = "expm1"
162
        self.python_api = paddle.expm1
R
ronnywang 已提交
163
        self.init_dtype()
164
        self.init_shape()
R
ronnywang 已提交
165 166

        np.random.seed(2049)
167
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
R
ronnywang 已提交
168 169 170 171 172 173
        out = np.expm1(x)

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

    def test_check_grad(self):
174 175 176 177
        self.check_grad(['X'], 'Out', check_eager=True)

    def test_check_output(self):
        self.check_output(check_eager=True)
R
ronnywang 已提交
178 179


180 181 182 183 184
class TestExpm1_ZeroDim(TestExpm1):
    def init_shape(self):
        self.shape = []


R
ronnywang 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
class TestExpm1API(unittest.TestCase):
    def init_dtype(self):
        self.dtype = 'float64'
        self.shape = [11, 17]

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

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

    def test_static_api(self):
        paddle.enable_static()

        def run(place):
            with paddle.static.program_guard(paddle.static.Program()):
                X = paddle.fluid.data('X', self.shape, dtype=self.dtype)
                out = paddle.expm1(X)
                exe = paddle.static.Executor(place)
                res = exe.run(feed={'X': self.x})
            for r in res:
209
                np.testing.assert_allclose(self.out_ref, r, rtol=1e-05)
R
ronnywang 已提交
210 211 212 213 214 215 216 217 218

        for place in self.place:
            run(place)

    def test_dygraph_api(self):
        def run(place):
            paddle.disable_static(place)
            X = paddle.to_tensor(self.x)
            out = paddle.expm1(X)
219
            np.testing.assert_allclose(self.out_ref, out.numpy(), rtol=1e-05)
R
ronnywang 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232
            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.


233
class TestParameter:
234 235
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
236 237
            if paddle.fluid.framework.in_dygraph_mode():
                paddle.enable_static()
G
GGBond8488 已提交
238 239
            np_x = np.array([0.1]).astype('float32').reshape((-1, 1))
            data = paddle.static.data(name="X", shape=[-1, 1], dtype="float32")
W
WuHaobo 已提交
240
            out = eval("paddle.%s(data, name='Y')" % self.op_type)
241 242
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
243
            (result,) = exe.run(feed={"X": np_x}, fetch_list=[out])
W
WuHaobo 已提交
244
            expected = eval("np.%s(np_x)" % self.op_type)
245
            np.testing.assert_allclose(result, expected, rtol=1e-05)
246 247 248 249 250 251 252

    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)
253
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
254 255


C
chengduo 已提交
256
class TestSigmoid(TestActivation):
Q
qijun 已提交
257 258
    def setUp(self):
        self.op_type = "sigmoid"
259
        self.init_dtype()
260
        self.init_shape()
261

262
        np.random.seed(1024)
263
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
264 265 266 267
        out = 1 / (1 + np.exp(-x))

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

269 270 271
    def init_dtype(self):
        self.dtype = np.float32

272
    def test_check_grad(self):
273 274 275 276
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.01)

277

278 279 280 281 282
class TestSigmoid_ZeroDim(TestSigmoid):
    def init_shape(self):
        self.shape = []


283 284 285
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
286 287 288 289
class TestSigmoidBF16(OpTest):
    def setUp(self):
        self.op_type = "sigmoid"
        self.init_dtype()
290
        self.init_shape()
291 292

        np.random.seed(1024)
293
        x = np.random.uniform(-1, 1, self.shape).astype(np.float32)
294 295 296 297 298 299 300 301 302 303
        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

304 305 306
    def init_shape(self):
        self.shape = [11, 17]

307 308 309 310 311 312 313 314 315
    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')


316 317 318 319 320 321 322 323
'''
class TestSigmoidBF16_ZeroDim(TestSigmoidBF16):

    def init_shape(self):
        self.shape = []
'''


M
minghaoBD 已提交
324 325 326
class TestSilu(TestActivation):
    def setUp(self):
        self.op_type = "silu"
Z
zxcd 已提交
327 328 329
        self.prim_op_type = "comp"
        self.enable_cinn = False
        self.python_api = paddle.nn.functional.silu
M
minghaoBD 已提交
330
        self.init_dtype()
331
        self.init_shape()
M
minghaoBD 已提交
332 333

        np.random.seed(1024)
334
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
M
minghaoBD 已提交
335 336 337 338 339 340 341 342 343 344 345
        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
Z
zxcd 已提交
346
        self.check_grad(['X'], 'Out', check_prim=True)
M
minghaoBD 已提交
347 348


349 350 351 352 353
class TestSilu_ZeroDim(TestSilu):
    def init_shape(self):
        self.shape = []


Z
zxcd 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
class TestSiluFP16(TestActivation):
    def setUp(self):
        self.op_type = "silu"
        self.prim_op_type = "comp"
        self.enable_cinn = False
        self.only_prim = True
        self.python_api = paddle.nn.functional.silu
        self.init_dtype()
        self.init_shape()

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

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

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

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

    def test_check_output(self):
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_output(check_eager=check_eager, check_prim=True)


M
minghaoBD 已提交
384 385 386 387
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')
388 389 390
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
M
minghaoBD 已提交
391
            else paddle.CPUPlace()
392
        )
M
minghaoBD 已提交
393 394 395 396 397 398 399 400 401 402 403 404

    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:
405
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
M
minghaoBD 已提交
406 407 408 409 410 411 412 413 414

    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]:
415
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
M
minghaoBD 已提交
416 417 418 419 420 421 422
        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.
423 424 425
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32'
            )
M
minghaoBD 已提交
426 427
            self.assertRaises(TypeError, F.silu, x_int32)
            # support the input dtype is float16
428 429 430
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16'
            )
M
minghaoBD 已提交
431 432 433
            F.silu(x_fp16)


C
chengduo 已提交
434
class TestLogSigmoid(TestActivation):
435 436
    def setUp(self):
        self.op_type = "logsigmoid"
437
        self.init_dtype()
438
        self.init_shape()
439

440
        np.random.seed(2048)
441
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
442 443
        out = np.log(1 / (1 + np.exp(-x)))

444
        self.inputs = {'X': x}
445
        self.outputs = {'Out': out}
446 447

    def test_check_grad(self):
448 449
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
450
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
451 452


453 454 455 456 457
class TestLogSigmoid_ZeroDim(TestLogSigmoid):
    def init_shape(self):
        self.shape = []


458
class TestLogSigmoidAPI(unittest.TestCase):
459
    # test paddle.nn.LogSigmoid, paddle.nn.functional.log_sigmoid
460
    def setUp(self):
461
        np.random.seed(1024)
462
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
463 464 465
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
466
            else paddle.CPUPlace()
467
        )
468 469

    def test_static_api(self):
470
        paddle.enable_static()
471
        with paddle.static.program_guard(paddle.static.Program()):
472
            x = paddle.fluid.data('X', [11, 17])
473
            out1 = F.log_sigmoid(x)
474 475 476 477 478 479
            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:
480
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
481 482 483 484

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
485
        out1 = F.log_sigmoid(x)
486 487 488 489
        m = paddle.nn.LogSigmoid()
        out2 = m(x)
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in [out1, out2]:
490
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
491 492 493
        paddle.enable_static()

    def test_errors(self):
494
        paddle.enable_static()
495 496
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
497
            self.assertRaises(TypeError, F.log_sigmoid, 1)
498
            # The input dtype must be float16, float32, float64.
499 500 501
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32'
            )
502
            self.assertRaises(TypeError, F.log_sigmoid, x_int32)
503
            # support the input dtype is float16
504 505 506
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16'
            )
507
            F.log_sigmoid(x_fp16)
508 509


510
class TestTanh(TestActivation, TestParameter):
511 512
    def setUp(self):
        self.op_type = "tanh"
513
        self.init_dtype()
514 515
        self.init_shape()

516
        np.random.seed(1024)
517
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
518 519 520 521
        out = np.tanh(x)

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

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

528
    def init_dtype(self):
529
        # TODO If dtype is float64, the output (Out) has diff at CPUPlace
530 531 532 533
        # when using and not using inplace. Therefore, set dtype as float32
        # for now.
        self.dtype = np.float32

534

535 536 537 538 539
class TestTanh_ZeroDim(TestTanh):
    def init_shape(self):
        self.shape = []


W
WangXi 已提交
540 541 542 543
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
544
        np.random.seed(1024)
W
WangXi 已提交
545
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
546 547 548
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
W
WangXi 已提交
549
            else paddle.CPUPlace()
550
        )
551 552 553 554
        self.executed_api()

    def executed_api(self):
        self.tanh = F.tanh
W
WangXi 已提交
555 556

    def test_static_api(self):
557
        paddle.enable_static()
W
WangXi 已提交
558
        with paddle.static.program_guard(paddle.static.Program()):
559
            x = paddle.fluid.data('X', [10, 12], self.dtype)
560
            out1 = self.tanh(x)
W
WangXi 已提交
561 562 563 564 565 566
            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:
567
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
W
WangXi 已提交
568 569 570

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
571
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
572 573 574 575 576 577
        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]:
578
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
W
WangXi 已提交
579 580 581
        paddle.enable_static()

    def test_errors(self):
582
        paddle.enable_static()
W
WangXi 已提交
583 584
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
585
            self.assertRaises(TypeError, self.tanh, 1)
W
WangXi 已提交
586
            # The input dtype must be float16, float32.
587 588 589
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
590
            self.assertRaises(TypeError, self.tanh, x_int32)
W
WangXi 已提交
591
            # support the input dtype is float16
592 593 594
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
595 596 597 598 599 600 601
            self.tanh(x_fp16)


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


604
class TestAtan(TestActivation, TestParameter):
605 606 607
    def setUp(self):
        self.op_type = "atan"
        self.init_dtype()
608
        self.init_shape()
609

610
        np.random.seed(1024)
611
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
612 613 614 615 616 617 618 619
        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
620
        self.check_grad(['X'], 'Out')
621

W
WuHaobo 已提交
622 623
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
G
GGBond8488 已提交
624 625
            np_x = np.array([0.1]).astype('float32').reshape((-1, 1))
            data = paddle.static.data(name="X", shape=[-1, 1], dtype="float32")
W
WuHaobo 已提交
626 627 628
            out = paddle.atan(data, name='Y')
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
629
            (result,) = exe.run(feed={"X": np_x}, fetch_list=[out])
W
WuHaobo 已提交
630 631 632
            expected = np.arctan(np_x)
            self.assertEqual(result, expected)

633 634 635 636 637 638 639 640
    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)

641

642 643 644 645 646
class TestAtan_ZeroDim(TestTanh):
    def init_shape(self):
        self.shape = []


647 648 649 650
class TestSinh(TestActivation):
    def setUp(self):
        self.op_type = "sinh"
        self.init_dtype()
651
        self.init_shape()
652

653
        np.random.seed(1024)
654
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
655 656 657 658 659 660 661 662 663 664
        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')

665 666 667 668 669 670 671

class TestSinh_ZeroDim(TestSinh):
    def init_shape(self):
        self.shape = []


class TestSinhAPI(unittest.TestCase):
672 673 674 675
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
676
            z = paddle.sinh(x).numpy()
677
            z_expected = np.sinh(np_x)
678
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
679 680 681 682

    def test_api(self):
        test_data_shape = [11, 17]
        with fluid.program_guard(fluid.Program(), fluid.Program()):
683 684 685
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
G
GGBond8488 已提交
686
            data_x = paddle.static.data(
687 688 689 690
                name="data_x",
                shape=test_data_shape,
                dtype="float32",
            )
691

692
            pd_sinh_out = paddle.sinh(data_x)
693 694
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
695 696 697 698 699
            (np_sinh_res,) = exe.run(
                fluid.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[pd_sinh_out],
            )
700 701

        expected_res = np.sinh(input_x)
702
        np.testing.assert_allclose(np_sinh_res, expected_res, rtol=1e-05)
703 704 705 706

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
707 708 709
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
710 711
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
712
            loss = paddle.sinh(var)
713 714 715 716 717 718 719 720 721
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


class TestSinhOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
722
            self.assertRaises(TypeError, paddle.sinh, 1)
723 724
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
725
            self.assertRaises(TypeError, paddle.sinh, x_int32)
726 727
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
728
            paddle.sinh(x_fp16)
729 730 731 732 733 734


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

737
        np.random.seed(1024)
738
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
739 740 741 742 743 744 745 746 747 748
        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')

749 750 751 752 753 754 755

class TestCosh_ZeroDim(TestCosh):
    def init_shape(self):
        self.shape = []


class TestCoshAPI(unittest.TestCase):
756 757 758 759
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
760
            z = paddle.cosh(x).numpy()
761
            z_expected = np.cosh(np_x)
762
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
763 764 765 766

    def test_api(self):
        test_data_shape = [11, 17]
        with fluid.program_guard(fluid.Program(), fluid.Program()):
767 768 769
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
G
GGBond8488 已提交
770
            data_x = paddle.static.data(
771 772 773 774
                name="data_x",
                shape=test_data_shape,
                dtype="float32",
            )
775 776 777 778

            pd_cosh_out = paddle.cosh(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
779 780 781 782 783
            (np_cosh_res,) = exe.run(
                fluid.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[pd_cosh_out],
            )
784 785

        expected_res = np.cosh(input_x)
786
        np.testing.assert_allclose(np_cosh_res, expected_res, rtol=1e-05)
787 788 789 790

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
791 792 793
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
794 795
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
796
            loss = paddle.cosh(var)
797 798 799 800 801 802 803 804 805
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


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


815 816 817 818 819 820
def ref_tanhshrink(x):
    out = x - np.tanh(x)
    return out


class TestTanhshrink(TestActivation):
K
Kavya Srinet 已提交
821 822
    def setUp(self):
        self.op_type = "tanh_shrink"
823
        self.init_dtype()
824
        self.init_shape()
825

826
        np.random.seed(1024)
827
        x = np.random.uniform(10, 20, self.shape).astype(self.dtype)
828
        out = ref_tanhshrink(x)
829

830
        self.inputs = {'X': x}
831
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
832 833

    def test_check_grad(self):
834 835
        if self.dtype == np.float16:
            return
836
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
837

838

839 840 841 842 843
class TestTanhshrink_ZeroDim(TestTanhshrink):
    def init_shape(self):
        self.shape = []


844 845 846
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
847
        np.random.seed(1024)
848
        self.x_np = np.random.uniform(10, 20, [10, 17]).astype(np.float64)
849 850 851
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
852
            else paddle.CPUPlace()
853
        )
854 855

    def test_static_api(self):
856
        paddle.enable_static()
857
        with paddle.static.program_guard(paddle.static.Program()):
858
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
859 860 861 862 863 864 865
            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:
866
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
867 868 869 870 871 872 873 874 875

    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]:
876
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
877 878 879
        paddle.enable_static()

    def test_errors(self):
880
        paddle.enable_static()
881 882 883 884
        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.
885 886 887
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
888 889
            self.assertRaises(TypeError, F.tanhshrink, x_int32)
            # support the input dtype is float16
890 891 892
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
893 894 895
            F.tanhshrink(x_fp16)


896 897 898 899 900 901
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
902
class TestHardShrink(TestActivation):
903 904
    def setUp(self):
        self.op_type = "hard_shrink"
905
        self.init_dtype()
906
        self.init_shape()
907

908 909
        self.threshold = 0.5
        self.set_attrs()
910
        np.random.seed(1024)
911
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype) * 10
912
        out = ref_hardshrink(x, self.threshold)
913

914
        self.attrs = {'threshold': self.threshold}
915
        self.inputs = {'X': x}
916
        self.outputs = {'Out': out}
917

918 919 920
    def init_shape(self):
        self.shape = [10, 12]

921 922 923
    def set_attrs(self):
        pass

924
    def test_check_grad(self):
925 926
        if self.dtype == np.float16:
            return
927
        self.check_grad(['X'], 'Out')
928 929


930 931 932 933 934
class TestHardShrink_threshold_negative(TestHardShrink):
    def set_attrs(self):
        self.threshold = -0.1


935 936 937 938 939 940 941 942
'''
class TestHardShrink_ZeroDim(TestHardShrink):

    def init_shape(self):
        self.shape = []
'''


943 944 945
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
946
        np.random.seed(1024)
947
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
948 949 950
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
951
            else paddle.CPUPlace()
952
        )
953 954

    def test_static_api(self):
955
        paddle.enable_static()
956
        with paddle.static.program_guard(paddle.static.Program()):
957
            x = paddle.fluid.data('X', [10, 12])
958 959 960 961 962 963 964
            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:
965
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
966 967 968

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
969
        x = paddle.to_tensor(self.x_np)
970 971 972 973 974
        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]:
975
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
976 977 978 979 980 981

        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]:
982
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
983 984
        paddle.enable_static()

985
    def test_errors(self):
986
        paddle.enable_static()
987
        with paddle.static.program_guard(paddle.static.Program()):
988
            # The input type must be Variable.
989
            self.assertRaises(TypeError, F.hardshrink, 1)
990
            # The input dtype must be float16, float32, float64.
991 992 993
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
994
            self.assertRaises(TypeError, F.hardshrink, x_int32)
995
            # support the input dtype is float16
996 997 998
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
999
            F.hardshrink(x_fp16)
1000 1001


1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
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):
1013
        np.random.seed(1024)
1014
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
1015 1016 1017
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1018
            else paddle.CPUPlace()
1019
        )
1020 1021

    def test_static_api(self):
1022
        paddle.enable_static()
1023
        with paddle.static.program_guard(paddle.static.Program()):
1024
            x = paddle.fluid.data('X', [10, 12])
1025 1026 1027 1028 1029 1030 1031
            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:
1032
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1033 1034 1035

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
1036
        x = paddle.to_tensor(self.x_np)
1037 1038 1039 1040 1041
        out1 = F.hardtanh(x)
        m = paddle.nn.Hardtanh()
        out2 = m(x)
        out_ref = ref_hardtanh(self.x_np)
        for r in [out1, out2]:
1042
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1043 1044 1045 1046 1047 1048

        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]:
1049
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1050 1051 1052
        paddle.enable_static()

    def test_errors(self):
1053
        paddle.enable_static()
1054 1055 1056 1057
        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.
1058 1059 1060
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
1061 1062
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
1063 1064 1065
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
1066 1067 1068
            F.hardtanh(x_fp16)


1069 1070 1071
def ref_softshrink(x, threshold=0.5):
    out = np.copy(x)
    out = (out < -threshold) * (out + threshold) + (out > threshold) * (
1072 1073
        out - threshold
    )
1074 1075 1076 1077
    return out


class TestSoftshrink(TestActivation):
1078 1079
    def setUp(self):
        self.op_type = "softshrink"
1080 1081
        self.check_eager = True
        self.python_api = paddle.nn.functional.softshrink
1082
        self.init_dtype()
1083
        self.init_shape()
1084

1085
        threshold = 0.8
1086

1087
        np.random.seed(1023)
1088
        x = np.random.uniform(0.25, 10, self.shape).astype(self.dtype)
1089 1090 1091
        out = ref_softshrink(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"lambda": threshold}
1092
        self.outputs = {'Out': out}
1093 1094

    def test_check_grad(self):
1095 1096
        if self.dtype == np.float16:
            return
1097
        self.check_grad(['X'], 'Out', check_eager=True)
1098

1099

1100 1101 1102 1103 1104
class TestSoftshrink_ZeroDim(TestSoftshrink):
    def init_shape(self):
        self.shape = []


1105 1106 1107 1108
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
1109
        np.random.seed(1024)
1110
        self.x_np = np.random.uniform(0.25, 10, [10, 12]).astype(np.float64)
1111 1112 1113
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1114
            else paddle.CPUPlace()
1115
        )
1116 1117

    def test_static_api(self):
1118
        paddle.enable_static()
1119
        with paddle.static.program_guard(paddle.static.Program()):
1120
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1121 1122 1123 1124 1125 1126 1127
            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:
1128
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1129 1130 1131 1132 1133 1134 1135 1136 1137

    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]:
1138
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1139 1140
        paddle.enable_static()

1141
    def test_errors(self):
1142
        paddle.enable_static()
1143
        with paddle.static.program_guard(paddle.static.Program()):
1144
            # The input type must be Variable.
1145
            self.assertRaises(TypeError, F.softshrink, 1)
1146
            # The input dtype must be float16, float32, float64.
1147 1148 1149
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
1150
            self.assertRaises(TypeError, F.softshrink, x_int32)
1151
            # The threshold must be no less than zero
1152 1153 1154
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[12, 10], dtype='float32'
            )
1155
            self.assertRaises(ValueError, F.softshrink, x_fp32, -1.0)
1156
            # support the input dtype is float16
1157 1158 1159
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
1160
            F.softshrink(x_fp16)
1161 1162


1163
class TestSqrt(TestActivation, TestParameter):
1164 1165
    def setUp(self):
        self.op_type = "sqrt"
1166
        self.prim_op_type = "prim"
1167
        self.python_api = paddle.sqrt
1168
        self.init_dtype()
1169
        self.init_shape()
1170

1171
        np.random.seed(1023)
1172
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
1173 1174 1175 1176
        out = np.sqrt(x)

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

1179
    # TODO(wanghao107) add prim test
1180
    def test_check_grad(self):
1181 1182
        if self.dtype == np.float16:
            return
1183 1184 1185 1186
        self.check_grad(['X'], 'Out', check_eager=True)

    def test_check_output(self):
        self.check_output(check_eager=True)
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
class TestSqrtPrimFp32(TestActivation):
    def setUp(self):
        self.op_type = "sqrt"
        self.prim_op_type = "prim"
        self.python_api = paddle.sqrt
        self.init_dtype()
        self.init_shape()
        np.random.seed(1023)
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
        out = np.sqrt(x)

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

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

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

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


1216 1217 1218 1219 1220
class TestSqrt_ZeroDim(TestSqrt):
    def init_shape(self):
        self.shape = []


1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
class TestSqrtPrim_ZeroDim(TestSqrt):
    def init_shape(self):
        self.shape = []

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

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


1234 1235 1236
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
1237 1238 1239
class TestSqrtBF16(OpTest):
    def setUp(self):
        self.op_type = "sqrt"
1240
        self.prim_op_type = "prim"
1241
        self.python_api = paddle.sqrt
1242
        self.init_dtype()
1243
        self.init_shape()
1244 1245

        np.random.seed(1023)
1246
        x = np.random.uniform(0.1, 1, self.shape).astype(np.float32)
1247 1248 1249 1250 1251 1252
        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)}
1253 1254
        # TODO(wanghao107): add prim test
        self.enable_cinn = False
1255 1256 1257 1258

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

1259 1260 1261
    def init_shape(self):
        self.shape = [11, 17]

1262 1263
    def test_check_output(self):
        place = core.CUDAPlace(0)
1264
        self.check_output_with_place(place, check_eager=True)
1265 1266 1267

    def test_check_grad(self):
        place = core.CUDAPlace(0)
1268
        self.check_grad_with_place(place, ['X'], 'Out', check_eager=True)
1269 1270


Z
zhoukunsheng 已提交
1271 1272 1273
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
Z
zyfncg 已提交
1274
        self.python_api = paddle.rsqrt
Z
zhoukunsheng 已提交
1275
        self.init_dtype()
1276
        self.init_shape()
Z
zhoukunsheng 已提交
1277

1278
        np.random.seed(1024)
1279
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
1280 1281 1282 1283 1284
        out = 1.0 / np.sqrt(x)

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

1285 1286 1287
    def init_shape(self):
        self.shape = [10, 12]

Z
zhoukunsheng 已提交
1288 1289 1290
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1291 1292 1293
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.0005, check_eager=True
        )
Z
zhoukunsheng 已提交
1294 1295


1296 1297 1298 1299 1300 1301 1302 1303
'''
class TestRsqrt_ZeroDim(TestRsqrt):

    def init_shape(self):
        self.shape = []
'''


C
chengduo 已提交
1304
class TestAbs(TestActivation):
1305 1306
    def setUp(self):
        self.op_type = "abs"
1307
        self.init_dtype()
1308
        self.init_shape()
1309

1310
        np.random.seed(1024)
1311
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
C
chengduo 已提交
1312
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
1313
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
1314
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
1315 1316
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
1317 1318 1319 1320
        out = np.abs(x)

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

1322 1323 1324
    def init_shape(self):
        self.shape = [4, 25]

1325
    def test_check_grad(self):
1326 1327
        if self.dtype == np.float16:
            return
1328
        self.check_grad(['X'], 'Out', check_eager=False)
1329

1330

1331 1332 1333 1334 1335
class TestAbs_ZeroDim(TestAbs):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1336
class TestCeil(TestActivation):
D
dzhwinter 已提交
1337 1338
    def setUp(self):
        self.op_type = "ceil"
1339 1340
        self.check_eager = True
        self.python_api = paddle.ceil
1341
        self.init_dtype()
1342
        self.init_shape()
1343

1344
        np.random.seed(1024)
1345
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1346 1347 1348 1349
        out = np.ceil(x)

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

1351 1352 1353
    def init_shape(self):
        self.shape = [10, 12]

D
dzhwinter 已提交
1354
    # The same reason with TestFloor
C
chengduo 已提交
1355
    def test_check_grad(self):
1356 1357 1358
        pass


1359 1360 1361 1362 1363
class TestCeil_ZeroDim(TestCeil):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1364
class TestFloor(TestActivation):
D
dzhwinter 已提交
1365 1366
    def setUp(self):
        self.op_type = "floor"
1367 1368
        self.check_eager = True
        self.python_api = paddle.floor
1369
        self.init_dtype()
1370
        self.init_shape()
1371

1372
        np.random.seed(1024)
1373
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1374 1375 1376 1377
        out = np.floor(x)

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

1379 1380 1381
    def init_shape(self):
        self.shape = [10, 12]

D
dzhwinter 已提交
1382
    # the gradient on floor, ceil, round is undefined.
1383
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
1384 1385
    # The same reason with TestFloor
    def test_check_grad(self):
1386 1387 1388
        pass


1389 1390 1391 1392 1393
class TestFloor_ZeroDim(TestFloor):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1394
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
1395 1396
    def setUp(self):
        self.op_type = "cos"
1397
        self.init_dtype()
1398
        self.init_shape()
1399

1400
        np.random.seed(1024)
1401
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1402 1403 1404 1405
        out = np.cos(x)

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

1407 1408 1409
    def init_shape(self):
        self.shape = [10, 12]

C
add sin  
chengduoZH 已提交
1410
    def test_check_grad(self):
1411 1412
        if self.dtype == np.float16:
            return
1413
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
1414

1415

1416 1417 1418 1419 1420
class TestCos_ZeroDim(TestCos):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
1421 1422 1423 1424 1425
class TestTan(TestActivation):
    def setUp(self):
        np.random.seed(1024)
        self.op_type = "tan"
        self.init_dtype()
1426 1427
        self.init_shape()

J
joejiong 已提交
1428
        self.dtype = 'float32'
1429
        self.x_np = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1430 1431 1432
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
J
joejiong 已提交
1433
            else paddle.CPUPlace()
1434
        )
J
joejiong 已提交
1435 1436 1437 1438 1439 1440

        out = np.tan(self.x_np)

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

1441 1442 1443
    def init_shape(self):
        self.shape = [10, 12]

J
joejiong 已提交
1444 1445 1446 1447 1448
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

class TestTan_ZeroDim(TestTan):
    def init_shape(self):
        self.shape = []


class TestTanAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(1024)
        self.dtype = 'float32'
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1460 1461 1462
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1463
            else paddle.CPUPlace()
1464
        )
1465

J
joejiong 已提交
1466 1467 1468 1469 1470
    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)
1471
        np.testing.assert_allclose(out_ref, out_test.numpy(), rtol=1e-05)
J
joejiong 已提交
1472 1473 1474 1475 1476
        paddle.enable_static()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
1477
            x = paddle.static.data('X', [11, 17], self.dtype)
J
joejiong 已提交
1478 1479 1480 1481
            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)
1482
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
J
joejiong 已提交
1483 1484 1485 1486

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
1487 1488 1489
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
J
joejiong 已提交
1490 1491 1492 1493 1494 1495 1496 1497
            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)


1498 1499 1500 1501
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()
1502
        self.init_shape()
1503

1504
        np.random.seed(1024)
1505
        x = np.random.uniform(-0.95, 0.95, self.shape).astype(self.dtype)
1506 1507 1508 1509 1510
        out = np.arccos(x)

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

1511 1512 1513
    def init_shape(self):
        self.shape = [10, 12]

1514 1515 1516
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1517
        self.check_grad(['X'], 'Out')
1518 1519


1520 1521 1522 1523 1524
class TestAcos_ZeroDim(TestAcos):
    def init_shape(self):
        self.shape = []


1525
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
1526 1527
    def setUp(self):
        self.op_type = "sin"
1528
        self.init_dtype()
1529
        self.init_shape()
1530

1531
        np.random.seed(1024)
1532
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1533 1534 1535 1536
        out = np.sin(x)

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

1538 1539 1540
    def init_shape(self):
        self.shape = [10, 12]

C
add cos  
chengduoZH 已提交
1541
    def test_check_grad(self):
1542 1543
        if self.dtype == np.float16:
            return
1544
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
1545 1546


1547 1548 1549 1550 1551
class TestSin_ZeroDim(TestSin):
    def init_shape(self):
        self.shape = []


1552 1553 1554 1555
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()
1556
        self.init_shape()
1557

1558
        np.random.seed(2048)
1559
        x = np.random.uniform(-0.95, 0.95, self.shape).astype(self.dtype)
1560 1561 1562 1563 1564
        out = np.arcsin(x)

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

1565 1566 1567
    def init_shape(self):
        self.shape = [10, 12]

1568 1569 1570
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1571
        self.check_grad(['X'], 'Out')
1572 1573


1574 1575 1576 1577 1578
class TestAsin_ZeroDim(TestAsin):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1579 1580 1581 1582
class TestAcosh(TestActivation):
    def setUp(self):
        self.op_type = "acosh"
        self.init_dtype()
1583
        self.init_shape()
X
xiaoting 已提交
1584 1585

        np.random.seed(1024)
1586
        x = np.random.uniform(2, 3, self.shape).astype(self.dtype)
X
xiaoting 已提交
1587 1588 1589 1590 1591
        out = np.arccosh(x)

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

1592 1593 1594
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1595 1596 1597 1598 1599 1600
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1601 1602 1603 1604 1605
class TestAcosh_ZeroDim(TestAcosh):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1606 1607 1608 1609
class TestAsinh(TestActivation):
    def setUp(self):
        self.op_type = "asinh"
        self.init_dtype()
1610
        self.init_shape()
X
xiaoting 已提交
1611 1612

        np.random.seed(1024)
1613
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
X
xiaoting 已提交
1614 1615 1616 1617 1618
        out = np.arcsinh(x)

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

1619 1620 1621
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1622 1623 1624 1625 1626 1627
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1628 1629 1630 1631 1632
class TestAsinh_ZeroDim(TestAsinh):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1633 1634 1635 1636
class TestAtanh(TestActivation):
    def setUp(self):
        self.op_type = "atanh"
        self.init_dtype()
1637
        self.init_shape()
X
xiaoting 已提交
1638 1639

        np.random.seed(400)
1640
        x = np.random.uniform(-0.9, 0.9, self.shape).astype(self.dtype)
X
xiaoting 已提交
1641 1642 1643 1644 1645
        out = np.arctanh(x)

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

1646 1647 1648
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1649 1650 1651 1652 1653 1654
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1655 1656 1657 1658 1659
class TestAtanh_ZeroDim(TestAtanh):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1660
class TestRound(TestActivation):
D
dzhwinter 已提交
1661 1662
    def setUp(self):
        self.op_type = "round"
1663 1664
        self.check_eager = True
        self.python_api = paddle.round
1665
        self.init_dtype()
1666
        self.init_shape()
1667

1668
        np.random.seed(1024)
1669
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1670 1671 1672 1673
        out = np.round(x)

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

1675 1676 1677
    def init_shape(self):
        self.shape = [10, 12]

C
chengduo 已提交
1678
    def test_check_grad(self):
1679 1680 1681
        pass


1682 1683 1684 1685 1686
class TestRound_ZeroDim(TestRound):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1687
class TestRelu(TestActivation):
1688
    def setUp(self):
Q
qijun 已提交
1689
        self.op_type = "relu"
K
Kexin Zhao 已提交
1690
        self.init_dtype()
1691
        self.init_shape()
K
Kexin Zhao 已提交
1692

1693
        np.random.seed(1024)
1694
        if self.dtype == np.uint16:
1695
            x = np.random.uniform(-1, 1, self.shape).astype(np.float32)
1696 1697 1698 1699 1700
            # 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:
1701
            x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1702 1703 1704 1705
            # 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 已提交
1706 1707

        self.outputs = {'Out': out}
1708 1709

    def test_check_grad(self):
K
Kexin Zhao 已提交
1710 1711
        if self.dtype == np.float16:
            return
1712
        self.check_grad(['X'], 'Out')
A
Adam 已提交
1713 1714


1715 1716 1717 1718 1719
class TestRelu_ZeroDim(TestRelu):
    def init_shape(self):
        self.shape = []


1720 1721 1722
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1723
        np.random.seed(1024)
1724
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
1725 1726 1727
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1728
            else paddle.CPUPlace()
1729
        )
1730 1731 1732 1733
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1734 1735

    def test_static_api(self):
1736
        paddle.enable_static()
1737
        with paddle.static.program_guard(paddle.static.Program()):
1738
            x = paddle.fluid.data('X', [10, 12])
1739
            out1 = self.relu(x)
1740 1741 1742 1743 1744 1745
            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:
1746
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1747 1748 1749 1750 1751

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.ReLU()
1752 1753
        out1 = m(x)
        out2 = self.relu(x)
1754 1755
        out_ref = np.maximum(self.x_np, 0)
        for r in [out1, out2]:
1756
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1757 1758
        paddle.enable_static()

1759
    def test_errors(self):
1760
        paddle.enable_static()
1761
        with paddle.static.program_guard(paddle.static.Program()):
1762
            # The input type must be Variable.
1763
            self.assertRaises(TypeError, self.relu, 1)
1764
            # The input dtype must be float16, float32, float64.
1765 1766 1767
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32'
            )
1768
            self.assertRaises(TypeError, self.relu, x_int32)
1769
            # support the input dtype is float16
1770 1771 1772
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16'
            )
1773 1774 1775 1776 1777 1778 1779
            self.relu(x_fp16)


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


1782 1783 1784 1785 1786 1787
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1788
class TestLeakyRelu(TestActivation):
1789 1790 1791
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1792 1793 1794
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()
1795
        self.init_shape()
1796
        alpha = self.get_alpha()
A
Adam 已提交
1797

1798
        np.random.seed(1024)
1799
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
A
Adam 已提交
1800
        # The same reason with TestAbs
1801 1802
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1803

1804
        self.inputs = {'X': x}
A
Adam 已提交
1805
        self.outputs = {'Out': out}
1806
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1807 1808 1809 1810

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


1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
class TestLeakyReluAlpha1(TestLeakyRelu):
    def get_alpha(self):
        return 2


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


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


1829 1830 1831 1832 1833
class TestLeakyRelu_ZeroDim(TestLeakyRelu):
    def init_shape(self):
        self.shape = []


1834 1835 1836
class TestLeakyReluAPI(unittest.TestCase):
    # test paddle.nn.LeakyReLU, paddle.nn.functional.leaky_relu,
    def setUp(self):
1837
        np.random.seed(1024)
1838
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
1839 1840 1841
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1842
            else paddle.CPUPlace()
1843
        )
1844 1845

    def test_static_api(self):
1846
        paddle.enable_static()
1847
        with paddle.static.program_guard(paddle.static.Program()):
1848
            x = paddle.fluid.data('X', [10, 12])
1849 1850 1851 1852 1853 1854 1855
            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:
1856
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1857 1858 1859

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
1860
        x = paddle.to_tensor(self.x_np)
1861 1862 1863 1864 1865
        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]:
1866
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1867 1868 1869 1870 1871 1872

        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]:
1873
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1874 1875
        paddle.enable_static()

1876
    def test_errors(self):
1877
        paddle.enable_static()
1878
        with paddle.static.program_guard(paddle.static.Program()):
1879
            # The input type must be Variable.
1880
            self.assertRaises(TypeError, F.leaky_relu, 1)
1881
            # The input dtype must be float16, float32, float64.
1882 1883 1884
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
1885 1886
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
1887 1888 1889
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
1890
            F.leaky_relu(x_fp16)
1891 1892


1893 1894
def gelu(x, approximate):
    if approximate:
1895 1896 1897 1898 1899 1900 1901 1902
        y_ref = (
            0.5
            * x
            * (
                1.0
                + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))
            )
        )
1903 1904 1905 1906 1907 1908
    else:
        y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
    return y_ref.astype(x.dtype)


class TestGeluApproximate(TestActivation):
C
Clementine 已提交
1909 1910 1911
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1912
        self.init_shape()
1913
        approximate = True
1914
        np.random.seed(1024)
1915
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1916
        out = gelu(x, approximate)
C
Clementine 已提交
1917

1918
        self.inputs = {'X': x}
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
        self.outputs = {'Out': out}
        self.attrs = {"approximate": approximate}

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


class TestGelu(TestActivation):
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1932
        self.init_shape()
1933
        approximate = False
1934
        np.random.seed(2048)
1935
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1936
        out = gelu(x, approximate)
C
Clementine 已提交
1937

1938
        self.inputs = {'X': x}
C
Clementine 已提交
1939
        self.outputs = {'Out': out}
1940
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1941 1942 1943 1944

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


1948 1949 1950 1951 1952
class TestGelu_ZeroDim(TestGelu):
    def init_shape(self):
        self.shape = []


1953 1954 1955
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1956
        np.random.seed(1024)
1957
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
1958 1959 1960
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1961
            else paddle.CPUPlace()
1962
        )
1963 1964

    def test_static_api(self):
1965
        paddle.enable_static()
1966
        with paddle.static.program_guard(paddle.static.Program()):
1967
            x = paddle.fluid.data('X', [11, 17])
1968 1969 1970 1971 1972 1973 1974
            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:
1975
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1976 1977 1978 1979 1980 1981 1982 1983 1984

    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]:
1985
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1986 1987 1988 1989 1990 1991

        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]:
1992
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1993 1994 1995
        paddle.enable_static()

    def test_errors(self):
1996
        paddle.enable_static()
1997 1998 1999 2000
        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.
2001 2002 2003
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32'
            )
2004 2005
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
2006 2007 2008
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16'
            )
2009 2010 2011
            F.gelu(x_fp16)


C
chengduo 已提交
2012
class TestBRelu(TestActivation):
2013 2014
    def setUp(self):
        self.op_type = "brelu"
2015 2016
        self.init_dtype()

2017
        np.random.seed(1024)
Z
zhupengyang 已提交
2018
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
2019 2020
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
2021 2022
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
2023
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
2024 2025 2026
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
2027 2028 2029

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

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

2037

2038 2039 2040 2041 2042 2043 2044
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 已提交
2045
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
2046
    def setUp(self):
2047
        self.op_type = "relu6"
2048
        self.init_dtype()
2049
        self.init_shape()
2050
        self.python_api = paddle.nn.functional.relu6
2051

2052
        np.random.seed(1024)
2053
        x = np.random.uniform(-1, 10, self.shape).astype(self.dtype)
2054
        x[np.abs(x) < 0.005] = 0.02
2055
        out = ref_relu6(x)
2056

2057 2058
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
2059
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
2060

2061 2062 2063
    def init_shape(self):
        self.shape = [10, 12]

2064 2065 2066
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
2067
        self.check_grad(['X'], 'Out', check_eager=True)
2068 2069


2070 2071 2072 2073 2074
class TestRelu6_ZeroDim(TestRelu6):
    def init_shape(self):
        self.shape = []


2075 2076 2077
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
2078
        np.random.seed(1024)
2079 2080
        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
2081 2082 2083
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2084
            else paddle.CPUPlace()
2085
        )
2086 2087

    def test_static_api(self):
2088
        paddle.enable_static()
2089
        with paddle.static.program_guard(paddle.static.Program()):
2090
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2091 2092 2093 2094 2095 2096 2097
            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:
2098
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2099 2100 2101 2102 2103 2104 2105 2106 2107

    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]:
2108
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2109 2110 2111
        paddle.enable_static()

    def test_fluid_api(self):
2112
        paddle.enable_static()
2113 2114
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
2115
            out = paddle.nn.functional.relu6(x)
2116 2117 2118
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_relu6(self.x_np)
2119
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2120

2121
    def test_errors(self):
2122
        paddle.enable_static()
2123
        with paddle.static.program_guard(paddle.static.Program()):
2124
            # The input type must be Variable.
2125
            self.assertRaises(TypeError, F.relu6, 1)
2126
            # The input dtype must be float16, float32, float64.
2127 2128 2129
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
2130
            self.assertRaises(TypeError, F.relu6, x_int32)
2131
            # support the input dtype is float16
2132 2133 2134
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
2135
            F.relu6(x_fp16)
2136 2137


2138
def ref_hardswish(x, threshold=6.0, scale=6.0, offset=3.0):
Z
Zhang Ting 已提交
2139 2140 2141 2142
    x_dtype = x.dtype
    if x_dtype == 'float16':
        x_dtype = 'float16'
        x = x.astype('float32')
2143 2144 2145
    return (
        x * np.minimum(np.maximum(x + offset, 0.0), threshold) / scale
    ).astype(x_dtype)
2146 2147


H
huangjun12 已提交
2148 2149 2150 2151
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()
2152
        self.init_shape()
2153
        self.python_api = paddle.nn.functional.hardswish
J
jakpiase 已提交
2154

2155
        np.random.seed(1024)
2156
        x = np.random.uniform(-6, 6, self.shape).astype(self.dtype)
H
huangjun12 已提交
2157 2158 2159
        threshold = 6.0
        scale = 6.0
        offset = 3.0
2160
        # the same with TestAbs
H
huangjun12 已提交
2161 2162
        x[np.abs(x + offset) < 0.005] = 0.02
        x[np.abs(x - threshold + offset) < 0.005] = threshold - offset + 0.02
2163
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
2164

2165
        self.inputs = {'X': x}
H
huangjun12 已提交
2166 2167 2168
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
        self.outputs = {'Out': out}

2169 2170 2171
    def init_shape(self):
        self.shape = [10, 12]

H
huangjun12 已提交
2172
    def test_check_grad(self):
2173 2174 2175 2176
        self.check_grad(['X'], 'Out', check_eager=True)

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


2179 2180 2181 2182 2183
class TestHardSwish_ZeroDim(TestHardSwish):
    def init_shape(self):
        self.shape = []


2184 2185 2186 2187
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)
2188 2189 2190
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2191
            else paddle.CPUPlace()
2192
        )
2193 2194 2195

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
2196
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2197 2198 2199 2200 2201 2202 2203
            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:
2204
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2205 2206 2207

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
2208
        x = paddle.to_tensor([11648.0, 11448.0])
2209 2210 2211
        out1 = F.hardswish(x)
        m = paddle.nn.Hardswish()
        out2 = m(x)
2212
        out_ref = [11648.0, 11448.0]
2213
        for r in [out1, out2]:
2214
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2215
        paddle.enable_static()
2216 2217 2218 2219

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
2220
            out = paddle.nn.functional.hardswish(x)
2221 2222 2223
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardswish(self.x_np)
2224
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2225 2226 2227

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
2228
        out = paddle.nn.functional.hardswish(x)
2229
        np.testing.assert_allclose(out_ref, out.numpy(), rtol=1e-05)
2230 2231 2232 2233
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
2234
            # The input type must be Variable.
2235
            self.assertRaises(TypeError, F.hardswish, 1)
2236
            # The input dtype must be float16, float32, float64.
2237 2238 2239
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
2240
            self.assertRaises(TypeError, F.hardswish, x_int32)
2241
            # support the input dtype is float16
2242 2243 2244
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
2245
            F.hardswish(x_fp16)
2246 2247


C
chengduo 已提交
2248
class TestSoftRelu(TestActivation):
2249 2250
    def setUp(self):
        self.op_type = "soft_relu"
2251 2252
        self.init_dtype()

2253
        np.random.seed(4096)
2254
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
2255
        threshold = 2.0
Q
qijun 已提交
2256 2257
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
2258
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
2259 2260 2261
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
2262 2263 2264 2265 2266
        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}
2267 2268

    def test_check_grad(self):
2269 2270
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
2271
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
2272

2273

2274
def elu(x, alpha):
Z
zhupengyang 已提交
2275
    out_ref = np.where(x > 0, x, alpha * (np.exp(x) - 1))
2276 2277 2278
    return out_ref.astype(x.dtype)


C
chengduo 已提交
2279
class TestELU(TestActivation):
2280 2281
    def setUp(self):
        self.op_type = "elu"
2282
        self.init_dtype()
2283
        self.init_shape()
2284

2285
        np.random.seed(1024)
2286
        x = np.random.uniform(-3, 3, self.shape).astype(self.dtype)
Z
zhupengyang 已提交
2287
        alpha = self.get_alpha()
2288
        out = elu(x, alpha)
2289 2290 2291 2292
        # 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}
2293
        self.outputs = {'Out': out}
2294

2295 2296 2297
    def init_shape(self):
        self.shape = [10, 12]

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

Z
zhupengyang 已提交
2303
    def get_alpha(self):
2304
        return 1.0
Z
zhupengyang 已提交
2305 2306 2307 2308 2309 2310


class TestELUAlpha(TestELU):
    def get_alpha(self):
        return -0.2

2311

2312 2313 2314 2315 2316
class TestELU_ZeroDim(TestELU):
    def init_shape(self):
        self.shape = []


2317 2318 2319
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
2320
        np.random.seed(1024)
2321
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
2322 2323 2324
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2325
            else paddle.CPUPlace()
2326
        )
2327 2328 2329 2330
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
2331 2332

    def test_static_api(self):
2333
        paddle.enable_static()
2334
        with paddle.static.program_guard(paddle.static.Program()):
2335
            x = paddle.fluid.data('X', [10, 12])
2336
            out1 = self.elu(x)
2337 2338 2339 2340 2341 2342
            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:
2343
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2344 2345 2346 2347

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
2348 2349
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
2350 2351 2352 2353
        m = paddle.nn.ELU()
        out2 = m(x)
        out_ref = elu(self.x_np, 1.0)
        for r in [out1, out2]:
2354
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2355

2356 2357
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
2358 2359 2360 2361
        m = paddle.nn.ELU(0.2)
        out2 = m(x)
        out_ref = elu(self.x_np, 0.2)
        for r in [out1, out2]:
2362
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2363 2364
        paddle.enable_static()

2365
    def test_errors(self):
2366
        paddle.enable_static()
2367 2368
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
2369
            self.assertRaises(TypeError, self.elu, 1)
2370
            # The input dtype must be float16, float32, float64.
2371 2372 2373
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32'
            )
2374
            self.assertRaises(TypeError, self.elu, x_int32)
2375
            # support the input dtype is float16
2376 2377 2378
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16'
            )
2379 2380 2381
            self.elu(x_fp16)


Z
zhupengyang 已提交
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
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()


2394 2395 2396 2397 2398 2399 2400 2401 2402
def celu(x, alpha):
    out_ref = np.maximum(0, x) + np.minimum(0, alpha * (np.exp(x / alpha) - 1))
    return out_ref.astype(x.dtype)


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

2405
        self.python_api = paddle.nn.functional.celu
2406
        np.random.seed(1024)
2407
        x = np.random.uniform(-3, 3, self.shape).astype(self.dtype)
2408 2409 2410 2411 2412 2413
        alpha = 1.5
        out = celu(x, alpha)
        self.inputs = {'X': x}
        self.attrs = {'alpha': alpha}
        self.outputs = {'Out': out}

2414 2415 2416
    def init_shape(self):
        self.shape = [10, 12]

2417 2418 2419
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
2420
        self.check_grad(['X'], 'Out', check_eager=True)
2421 2422


2423 2424 2425 2426 2427
class TestCELU_ZeroDim(TestCELU):
    def init_shape(self):
        self.shape = []


2428 2429 2430 2431 2432
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')
2433 2434 2435
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2436
            else paddle.CPUPlace()
2437
        )
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
        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:
2454
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464

    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]:
2465
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2466 2467 2468 2469 2470 2471 2472

        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]:
2473
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2474 2475 2476 2477 2478 2479 2480 2481
        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.
2482 2483 2484
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32'
            )
2485 2486
            self.assertRaises(TypeError, self.celu, x_int32)
            # The alpha must be not equal 0
2487 2488 2489
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[10, 12], dtype='float32'
            )
2490 2491
            self.assertRaises(ZeroDivisionError, F.celu, x_fp32, 0)
            # support the input dtype is float16
2492 2493 2494
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16'
            )
2495 2496 2497
            self.celu(x_fp16)


C
chengduo 已提交
2498
class TestReciprocal(TestActivation):
Q
qijun 已提交
2499 2500
    def setUp(self):
        self.op_type = "reciprocal"
2501
        self.python_api = paddle.reciprocal
2502
        self.init_dtype()
2503
        self.init_shape()
2504

2505
        np.random.seed(1024)
2506
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
2507 2508 2509 2510
        out = np.reciprocal(x)

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

    def test_check_grad(self):
2513 2514
        if self.dtype == np.float16:
            return
2515 2516 2517 2518
        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 已提交
2519 2520


2521 2522 2523 2524 2525
class TestReciprocal_ZeroDim(TestReciprocal):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
2526
class TestLog(TestActivation):
Q
qijun 已提交
2527 2528
    def setUp(self):
        self.op_type = "log"
2529 2530
        self.check_eager = True
        self.python_api = paddle.log
2531
        self.init_dtype()
2532
        self.init_shape()
2533

2534
        np.random.seed(1024)
2535
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2536 2537 2538 2539
        out = np.log(x)

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

    def test_check_grad(self):
2542 2543
        if self.dtype == np.float16:
            return
2544
        self.check_grad(['X'], 'Out', check_eager=True)
Q
qijun 已提交
2545

2546
    def test_error(self):
G
GGBond8488 已提交
2547 2548
        in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
        in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")
2549

2550 2551
        self.assertRaises(TypeError, paddle.log, in1)
        self.assertRaises(TypeError, paddle.log, in2)
2552

2553

2554 2555 2556 2557 2558
class TestLog_ZeroDim(TestLog):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
2559 2560 2561
class TestLog2(TestActivation):
    def setUp(self):
        self.op_type = "log2"
2562 2563
        self.check_eager = True
        self.python_api = paddle.log2
J
joejiong 已提交
2564
        self.init_dtype()
2565
        self.init_shape()
J
joejiong 已提交
2566

2567
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
J
joejiong 已提交
2568 2569 2570 2571 2572 2573 2574 2575
        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
2576
        self.check_grad(['X'], 'Out', check_eager=True)
J
joejiong 已提交
2577 2578 2579 2580 2581 2582 2583 2584 2585

    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):
2586 2587 2588
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
J
joejiong 已提交
2589
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
2590 2591 2592
            data_x = paddle.static.data(
                name="data_x", shape=[11, 17], dtype="float64"
            )
J
joejiong 已提交
2593 2594 2595 2596

            out1 = paddle.log2(data_x)
            exe = paddle.static.Executor(place=fluid.CPUPlace())
            exe.run(paddle.static.default_startup_program())
2597 2598 2599 2600 2601
            (res1,) = exe.run(
                paddle.static.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[out1],
            )
J
joejiong 已提交
2602
        expected_res = np.log2(input_x)
2603
        np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
J
joejiong 已提交
2604 2605 2606 2607 2608 2609 2610 2611

        # 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))
2612
        np.testing.assert_allclose(np_z, z_expected, rtol=1e-05)
J
joejiong 已提交
2613 2614


2615 2616 2617 2618 2619
class TestLog2_ZeroDim(TestLog2):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
2620 2621 2622
class TestLog10(TestActivation):
    def setUp(self):
        self.op_type = "log10"
2623 2624
        self.check_eager = True
        self.python_api = paddle.log10
J
joejiong 已提交
2625
        self.init_dtype()
2626
        self.init_shape()
J
joejiong 已提交
2627

2628
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
J
joejiong 已提交
2629 2630 2631 2632 2633 2634 2635 2636
        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
2637
        self.check_grad(['X'], 'Out', check_eager=True)
J
joejiong 已提交
2638

2639 2640 2641 2642 2643 2644 2645

class TestLog10_ZeroDim(TestLog10):
    def init_shape(self):
        self.shape = []


class TestLog10API(unittest.TestCase):
J
joejiong 已提交
2646 2647 2648 2649 2650 2651 2652 2653
    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):
2654 2655 2656
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
J
joejiong 已提交
2657
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
2658 2659 2660
            data_x = paddle.static.data(
                name="data_x", shape=[11, 17], dtype="float64"
            )
J
joejiong 已提交
2661 2662 2663 2664

            out1 = paddle.log10(data_x)
            exe = paddle.static.Executor(place=paddle.CPUPlace())
            exe.run(paddle.static.default_startup_program())
2665 2666 2667 2668 2669
            (res1,) = exe.run(
                paddle.static.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[out1],
            )
J
joejiong 已提交
2670
        expected_res = np.log10(input_x)
2671
        np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
J
joejiong 已提交
2672 2673 2674 2675 2676 2677 2678 2679

        # 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))
2680
        np.testing.assert_allclose(np_z, z_expected, rtol=1e-05)
J
joejiong 已提交
2681 2682


2683 2684 2685
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
2686 2687
        self.check_eager = True
        self.python_api = paddle.log1p
2688
        self.init_dtype()
2689
        self.init_shape()
2690

2691
        np.random.seed(1024)
2692
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2693 2694 2695 2696 2697 2698 2699 2700
        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
2701
        self.check_grad(['X'], 'Out', check_eager=True)
2702

2703 2704 2705 2706 2707 2708 2709

class TestLog1p_ZeroDim(TestLog1p):
    def init_shape(self):
        self.shape = []


class TestLog1pAPI(unittest.TestCase):
2710 2711 2712
    def test_api(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
G
GGBond8488 已提交
2713
            data_x = paddle.static.data(
2714 2715 2716 2717
                name="data_x",
                shape=[11, 17],
                dtype="float64",
            )
2718 2719 2720 2721

            out1 = paddle.log1p(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
2722 2723 2724 2725 2726
            (res1,) = exe.run(
                fluid.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[out1],
            )
2727
        expected_res = np.log1p(input_x)
2728
        np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
2729 2730 2731 2732 2733 2734 2735 2736

        # 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))
2737
        np.testing.assert_allclose(np_z, z_expected, rtol=1e-05)
2738 2739


C
chengduo 已提交
2740
class TestSquare(TestActivation):
Q
qijun 已提交
2741 2742
    def setUp(self):
        self.op_type = "square"
2743
        self.python_api = paddle.square
2744
        self.init_dtype()
2745
        self.init_shape()
2746

2747
        np.random.seed(1024)
2748
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2749 2750 2751 2752
        out = np.square(x)

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

    def test_check_grad(self):
2755 2756
        if self.dtype == np.float16:
            return
2757 2758 2759
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.007, check_eager=True
        )
2760 2761 2762

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

2764

2765 2766 2767 2768 2769
class TestSquare_ZeroDim(TestSquare):
    def init_shape(self):
        self.shape = []


2770 2771 2772
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
2773 2774 2775
class TestSquareBF16(OpTest):
    def setUp(self):
        self.op_type = "square"
2776
        self.python_api = paddle.square
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
        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)
2793
        self.check_output_with_place(place, check_eager=True)
2794 2795 2796

    def test_check_grad(self):
        place = core.CUDAPlace(0)
2797 2798 2799
        self.check_grad_with_place(
            place, ['X'], 'Out', numeric_grad_delta=0.5, check_eager=True
        )
2800 2801


C
chengduo 已提交
2802
class TestPow(TestActivation):
2803 2804
    def setUp(self):
        self.op_type = "pow"
2805
        self.python_api = paddle.pow
2806
        self.check_eager = True
2807
        self.init_dtype()
2808
        self.init_shape()
2809

2810
        np.random.seed(1024)
2811
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
2812 2813 2814
        out = np.power(x, 3)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
Y
Yang Yang(Tony) 已提交
2815
        self.attrs = {'factor': 3.0}
2816
        self.outputs = {'Out': out}
2817

2818 2819 2820
    def test_check_output(self):
        self.check_output(check_eager=self.check_eager)

2821
    def test_check_grad(self):
2822 2823
        if self.dtype == np.float16:
            return
2824
        self.check_grad(['X'], 'Out', check_eager=self.check_eager)
2825

2826

2827 2828 2829 2830 2831
class TestPow_ZeroDim(TestPow):
    def init_shape(self):
        self.shape = []


2832 2833 2834
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
2835 2836
        self.check_eager = False
        self.python_api = paddle.pow
2837 2838
        self.init_dtype()

2839
        np.random.seed(1024)
2840 2841 2842 2843 2844
        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),
2845
            'FactorTensor': np.array([3.0]).astype("float32"),
2846 2847 2848 2849 2850 2851
        }

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

    def test_check_output(self):
2852
        self.check_output(check_eager=self.check_eager)
2853 2854 2855 2856

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

    def test_api(self):
        input = np.random.uniform(1, 2, [11, 17]).astype("float32")
G
GGBond8488 已提交
2861 2862
        x = paddle.static.data(name="x", shape=[11, 17], dtype="float32")
        res = paddle.static.data(name="res", shape=[11, 17], dtype="float32")
2863 2864 2865

        factor_1 = 2.0
        factor_2 = fluid.layers.fill_constant([1], "float32", 3.0)
2866 2867
        out_1 = paddle.pow(x, factor_1)
        out_2 = paddle.pow(x, factor_2)
2868 2869 2870
        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)
2871 2872

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
2873
        res_1, res_2, res, res_6 = exe.run(
2874 2875
            fluid.default_main_program(),
            feed={"x": input},
2876 2877
            fetch_list=[out_1, out_2, res, out_6],
        )
2878

2879 2880 2881
        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))
2882 2883


2884 2885 2886 2887 2888
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
2889
class TestSTanh(TestActivation):
2890 2891 2892 2893 2894 2895
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

2896 2897
    def setUp(self):
        self.op_type = "stanh"
2898
        self.init_dtype()
2899 2900
        self.init_shape()

2901 2902
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
2903

2904
        np.random.seed(1024)
2905
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2906 2907
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
2908

2909
        self.inputs = {'X': x}
2910
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
2911
        self.outputs = {'Out': out}
2912

Q
qijun 已提交
2913
    def test_check_grad(self):
2914 2915
        if self.dtype == np.float16:
            return
2916
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
2917

2918

2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
class TestSTanhScaleA(TestSTanh):
    def get_scale_a(self):
        return 2.0


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


2929 2930 2931 2932 2933
class TestSTanh_ZeroDim(TestSTanh):
    def init_shape(self):
        self.shape = []


2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
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()
2947 2948 2949
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
2950
            else paddle.CPUPlace()
2951
        )
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961

    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:
2962
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2963 2964 2965 2966 2967 2968 2969

    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]:
2970
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2971 2972 2973 2974 2975 2976
        paddle.enable_static()

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
2977
            out = paddle.stanh(x, self.scale_a, self.scale_b)
2978 2979 2980
            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)
2981
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2982

2983
    def test_errors(self):
2984 2985
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2986
            # The input type must be Variable.
2987
            self.assertRaises(TypeError, paddle.stanh, 1)
2988
            # The input dtype must be float16, float32, float64.
2989 2990 2991
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
2992
            self.assertRaises(TypeError, paddle.stanh, x_int32)
2993
            # support the input dtype is float16
2994 2995 2996
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
            paddle.stanh(x_fp16)


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


class TestSTanhAPIScaleB(TestSTanhAPI):
    def get_scale_b(self):
        return 0.5
3008 3009


3010 3011
def ref_softplus(x, beta=1, threshold=20):
    x_beta = beta * x
3012 3013 3014 3015
    out = np.select(
        [x_beta <= threshold, x_beta > threshold],
        [np.log(1 + np.exp(x_beta)) / beta, x],
    )
3016 3017 3018
    return out


C
chengduo 已提交
3019
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
3020 3021
    def setUp(self):
        self.op_type = "softplus"
W
Wang Bojun 已提交
3022
        self.python_api = paddle.nn.functional.softplus
3023
        self.init_dtype()
3024
        self.init_shape()
3025

3026 3027
        beta = 2
        threshold = 15
3028

3029
        np.random.seed(1024)
3030
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3031 3032 3033
        out = ref_softplus(x, beta, threshold)
        self.inputs = {'X': x}
        self.attrs = {'beta': beta, "threshold": threshold}
3034
        self.outputs = {'Out': out}
K
kexinzhao 已提交
3035

W
Wang Bojun 已提交
3036 3037
        self.check_eager = True

3038 3039 3040
    def init_shape(self):
        self.shape = [10, 12]

K
kexinzhao 已提交
3041
    def test_check_grad(self):
3042 3043
        if self.dtype == np.float16:
            return
W
Wang Bojun 已提交
3044 3045 3046
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
K
kexinzhao 已提交
3047

3048

3049 3050 3051 3052 3053
class TestSoftplus_ZeroDim(TestSoftplus):
    def init_shape(self):
        self.shape = []


3054 3055 3056
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083
class TestSoftplusBF16(OpTest):
    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)


3084 3085 3086 3087 3088
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
3089
        np.random.seed(1024)
3090
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
3091 3092 3093
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3094
            else paddle.CPUPlace()
3095
        )
3096 3097

    def test_static_api(self):
3098
        paddle.enable_static()
3099
        with paddle.static.program_guard(paddle.static.Program()):
3100
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
3101 3102 3103 3104 3105 3106 3107
            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:
3108
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3109 3110 3111 3112 3113 3114 3115 3116 3117

    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]:
3118
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3119 3120 3121
        paddle.enable_static()

    def test_errors(self):
3122
        paddle.enable_static()
3123 3124 3125 3126
        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.
3127 3128 3129
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3130 3131
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
3132 3133 3134
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3135 3136 3137 3138 3139 3140 3141 3142
            F.softplus(x_fp16)


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


C
chengduo 已提交
3143
class TestSoftsign(TestActivation):
3144 3145
    def setUp(self):
        self.op_type = "softsign"
3146
        self.init_dtype()
3147 3148
        self.init_shape()

3149
        self.python_api = paddle.nn.functional.softsign
3150

3151
        np.random.seed(1024)
3152
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3153 3154
        out = ref_softsign(x)
        self.inputs = {'X': x}
3155
        self.outputs = {'Out': out}
3156

3157 3158 3159
    def init_shape(self):
        self.shape = [10, 12]

3160
    def test_check_grad(self):
3161 3162
        if self.dtype == np.float16:
            return
3163
        self.check_grad(['X'], 'Out', check_eager=True)
3164 3165


3166 3167 3168 3169 3170
class TestSoftsign_ZeroDim(TestSoftsign):
    def init_shape(self):
        self.shape = []


3171 3172 3173
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
3174
        np.random.seed(1024)
3175
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
3176 3177 3178
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3179
            else paddle.CPUPlace()
3180
        )
3181 3182

    def test_static_api(self):
3183
        paddle.enable_static()
3184
        with paddle.static.program_guard(paddle.static.Program()):
3185
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
3186 3187 3188 3189 3190 3191 3192
            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:
3193
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3194 3195 3196 3197 3198 3199 3200 3201 3202

    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]:
3203
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3204 3205 3206
        paddle.enable_static()

    def test_errors(self):
3207
        paddle.enable_static()
3208 3209 3210 3211
        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.
3212 3213 3214
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3215 3216
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
3217 3218 3219
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3220 3221 3222
            F.softsign(x_fp16)


3223 3224 3225 3226 3227
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
3228
class TestThresholdedRelu(TestActivation):
3229 3230
    def setUp(self):
        self.op_type = "thresholded_relu"
3231
        self.init_dtype()
3232
        self.init_shape()
3233

3234
        threshold = 15
3235

3236
        np.random.seed(1024)
3237
        x = np.random.uniform(-20, 20, self.shape).astype(self.dtype)
3238 3239 3240 3241
        x[np.abs(x) < 0.005] = 0.02
        out = ref_thresholded_relu(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"threshold": threshold}
3242
        self.outputs = {'Out': out}
3243

3244 3245 3246
    def init_shape(self):
        self.shape = [10, 12]

3247
    def test_check_grad(self):
3248 3249
        if self.dtype == np.float16:
            return
3250
        self.check_grad(['X'], 'Out')
3251 3252


3253 3254 3255 3256 3257
class TestThresholdedRelu_ZeroDim(TestThresholdedRelu):
    def init_shape(self):
        self.shape = []


3258 3259 3260 3261 3262 3263 3264
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
3265 3266 3267
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3268
            else paddle.CPUPlace()
3269
        )
3270 3271 3272 3273

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3274
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
3275 3276 3277 3278 3279 3280 3281
            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:
3282
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3283 3284 3285 3286 3287 3288 3289 3290 3291

    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]:
3292
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3293 3294
        paddle.enable_static()

3295
    def test_errors(self):
3296 3297
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3298
            # The input type must be Variable.
3299
            self.assertRaises(TypeError, F.thresholded_relu, 1)
3300
            # The input dtype must be float16, float32, float64.
3301 3302 3303
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3304
            self.assertRaises(TypeError, F.thresholded_relu, x_int32)
3305
            # support the input dtype is float16
3306 3307 3308
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3309
            F.thresholded_relu(x_fp16)
3310 3311


3312
def ref_hardsigmoid(x, slope=0.166666666666667, offset=0.5):
3313
    return np.maximum(np.minimum(x * slope + offset, 1.0), 0.0).astype(x.dtype)
3314 3315


C
chengduo 已提交
3316
class TestHardSigmoid(TestActivation):
3317 3318
    def setUp(self):
        self.op_type = "hard_sigmoid"
3319 3320 3321 3322
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
3323
        self.init_shape()
3324

3325
        x = np.random.uniform(-5, 5, self.shape).astype(self.dtype)
3326
        lower_threshold = -self.offset / self.slope
3327
        upper_threshold = (1.0 - self.offset) / self.slope
Z
zhupengyang 已提交
3328

3329
        # Same reason as TestAbs
3330 3331 3332
        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
3333

3334
        out = ref_hardsigmoid(x, self.slope, self.offset)
3335

3336 3337
        self.attrs = {'slope': self.slope, 'offset': self.offset}
        self.inputs = {'X': x}
3338
        self.outputs = {'Out': out}
3339

3340 3341 3342
    def init_shape(self):
        self.shape = [10, 12]

3343 3344
    def set_attrs(self):
        pass
3345

3346

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
class TestHardSigmoidFP32(TestHardSigmoid):
    def set_attrs(self):
        self.dtype = 'float32'


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


3358 3359 3360 3361 3362
class TestHardSigmoid_ZeroDim(TestHardSigmoid):
    def init_shape(self):
        self.shape = []


3363 3364 3365 3366
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)
3367 3368 3369
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3370
            else paddle.CPUPlace()
3371
        )
3372 3373 3374

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
3375
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
3376 3377 3378 3379 3380 3381 3382
            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:
3383
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3384 3385 3386 3387 3388 3389 3390 3391 3392

    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]:
3393
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3394
        paddle.enable_static()
3395 3396 3397 3398

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
3399
            out = paddle.nn.functional.hardsigmoid(x, slope=0.2)
3400 3401 3402
            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)
3403
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3404 3405 3406

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
3407
        out = paddle.nn.functional.hardsigmoid(x, slope=0.2)
3408
        np.testing.assert_allclose(out_ref, out.numpy(), rtol=1e-05)
3409 3410 3411 3412
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
3413
            # The input type must be Variable.
3414
            self.assertRaises(TypeError, F.hardsigmoid, 1)
3415
            # The input dtype must be float16, float32, float64.
3416 3417 3418
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3419
            self.assertRaises(TypeError, F.hardsigmoid, x_int32)
3420
            # support the input dtype is float16
3421 3422 3423
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3424
            F.hardsigmoid(x_fp16)
3425 3426


3427 3428 3429 3430 3431
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
3432
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
3433 3434
    def setUp(self):
        self.op_type = "swish"
3435
        self.python_api = paddle.nn.functional.swish
3436
        self.init_dtype()
3437 3438
        self.init_shape()

3439
        self.check_eager = True
3440

3441
        np.random.seed(1024)
3442
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3443 3444
        out = ref_swish(x)
        self.inputs = {'X': x}
H
hong19860320 已提交
3445
        self.attrs = {'beta': 1.0}
3446
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
3447

3448 3449 3450
    def init_shape(self):
        self.shape = [10, 12]

A
Abhinav Arora 已提交
3451
    def test_check_grad(self):
3452 3453
        if self.dtype == np.float16:
            return
3454 3455 3456 3457
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
3458

A
Abhinav Arora 已提交
3459

3460 3461 3462 3463 3464
class TestSwish_ZeroDim(TestSwish):
    def init_shape(self):
        self.shape = []


3465 3466 3467 3468 3469
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)
3470 3471 3472
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3473
            else paddle.CPUPlace()
3474
        )
3475 3476 3477 3478

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
3479
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
3480 3481 3482 3483 3484 3485 3486
            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:
3487
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3488

3489
    def test_dygraph_api(self):
3490 3491 3492 3493 3494 3495 3496
        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]:
3497
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3498 3499 3500 3501 3502 3503
        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)
3504
            out = paddle.nn.functional.swish(x)
3505 3506 3507
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_swish(self.x_np)
3508
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3509

3510
    def test_errors(self):
3511 3512
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3513
            # The input type must be Variable.
3514
            self.assertRaises(TypeError, F.swish, 1)
3515
            # The input dtype must be float16, float32, float64.
3516 3517 3518
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3519
            self.assertRaises(TypeError, F.swish, x_int32)
3520
            # support the input dtype is float16
3521 3522 3523
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3524
            F.swish(x_fp16)
3525 3526


3527 3528 3529 3530
def ref_mish(x, threshold=20.0):
    softplus = np.select(
        [x <= threshold, x > threshold], [np.log(1 + np.exp(x)), x]
    )
3531 3532 3533 3534 3535 3536
    return x * np.tanh(softplus)


class TestMish(TestActivation):
    def setUp(self):
        self.op_type = "mish"
3537
        self.python_api = paddle.nn.functional.mish
3538
        self.init_dtype()
3539
        self.init_shape()
3540 3541

        np.random.seed(1024)
3542
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3543 3544 3545 3546
        out = ref_mish(x)
        self.inputs = {'X': x}
        self.outputs = {'Out': out}

3547 3548 3549
    def init_shape(self):
        self.shape = [10, 12]

3550 3551 3552
    def test_check_output(self):
        self.check_output(check_eager=True)

3553 3554 3555
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
3556
        self.check_grad(['X'], 'Out', check_eager=True)
3557 3558


3559 3560 3561 3562 3563
class TestMish_ZeroDim(TestMish):
    def init_shape(self):
        self.shape = []


3564 3565 3566 3567 3568
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)
3569 3570 3571
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3572
            else paddle.CPUPlace()
3573
        )
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585

    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:
3586
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3587 3588 3589 3590 3591 3592 3593 3594 3595

    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]:
3596
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3597 3598 3599 3600 3601 3602
        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)
3603
            out = paddle.nn.functional.mish(x)
3604 3605 3606
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_mish(self.x_np)
3607
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3608 3609 3610 3611 3612 3613 3614

    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.
3615 3616 3617
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3618 3619
            self.assertRaises(TypeError, F.mish, x_int32)
            # support the input dtype is float16
3620 3621 3622
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3623 3624 3625
            F.mish(x_fp16)


3626
# ------------------ Test Cudnn Activation----------------------
3627
def create_test_act_cudnn_class(parent, atol=1e-3, grad_atol=1e-3):
3628 3629 3630
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
    class TestActCudnn(parent):
        def init_kernel_type(self):
            self.attrs = {"use_cudnn": True}

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


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


3646 3647 3648 3649 3650 3651 3652
# ------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(
    parent, atol=1e-3, grad_check=True, grad_atol=0.80
):
    @unittest.skipIf(
        not paddle.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
C
chengduo 已提交
3653 3654 3655
    class TestActFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16
3656

C
chengduo 已提交
3657
        def test_check_output(self):
3658
            place = core.CUDAPlace(0)
C
chengduo 已提交
3659 3660 3661
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
3662

C
chengduo 已提交
3663 3664 3665 3666
        def test_check_grad(self):
            place = core.CUDAPlace(0)
            support_fp16 = core.is_float16_supported(place)
            if support_fp16 and grad_check:
3667 3668 3669
                self.check_grad_with_place(
                    place, ['X'], 'Out', max_relative_error=grad_atol
                )
C
chengduo 已提交
3670 3671 3672 3673 3674 3675 3676

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


create_test_act_fp16_class(TestActivation)
R
ronnywang 已提交
3677
create_test_act_fp16_class(TestExpm1)
C
chengduo 已提交
3678
create_test_act_fp16_class(TestSigmoid)
M
minghaoBD 已提交
3679
create_test_act_fp16_class(TestSilu)
Z
zxcd 已提交
3680
create_test_act_fp16_class(TestSiluFP16)
C
chengduo 已提交
3681 3682
create_test_act_fp16_class(TestLogSigmoid)
create_test_act_fp16_class(TestTanh)
3683
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
3684
create_test_act_fp16_class(TestHardShrink)
3685
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
3686 3687 3688 3689 3690
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 已提交
3691
create_test_act_fp16_class(TestTan, grad_atol=0.85)
3692
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
3693
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
3694
create_test_act_fp16_class(TestSin)
3695
create_test_act_fp16_class(TestSinh)
3696 3697
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
X
xiaoting 已提交
3698 3699 3700
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 已提交
3701 3702
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
3703
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
3704 3705
create_test_act_fp16_class(TestBRelu)
create_test_act_fp16_class(TestRelu6)
3706
create_test_act_fp16_class(TestSoftRelu, grad_atol=0.85)
C
chengduo 已提交
3707
create_test_act_fp16_class(TestELU)
3708
create_test_act_fp16_class(TestCELU)
C
chengduo 已提交
3709 3710
create_test_act_fp16_class(TestReciprocal)
create_test_act_fp16_class(TestLog)
3711 3712 3713 3714
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 已提交
3715
create_test_act_fp16_class(TestLog10, atol=5e-2)
3716
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
3717 3718
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
3719
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
3720 3721 3722 3723 3724
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)
3725
create_test_act_fp16_class(TestSwish, grad_atol=0.85)
H
huangjun12 已提交
3726
create_test_act_fp16_class(TestHardSwish)
3727
create_test_act_fp16_class(TestMish, grad_atol=0.9)
A
Abhinav Arora 已提交
3728

3729

3730 3731 3732 3733 3734 3735
def create_test_act_bf16_class(
    parent, atol=1e-2, grad_check=True, grad_atol=0.80
):
    @unittest.skipIf(
        not paddle.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
    class TestActBF16(parent):
        def init_dtype(self):
            self.dtype = np.uint16

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

        def test_check_grad(self):
            place = core.CUDAPlace(0)
3746 3747 3748
            self.check_grad_with_place(
                place, ['X'], 'Out', max_relative_error=grad_atol
            )
3749 3750 3751 3752 3753 3754 3755

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


create_test_act_bf16_class(TestRelu)
3756
create_test_act_bf16_class(TestAbs)
3757

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