test_activation_op.py 114.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 327
class TestSilu(TestActivation):
    def setUp(self):
        self.op_type = "silu"
        self.init_dtype()
328
        self.init_shape()
M
minghaoBD 已提交
329 330

        np.random.seed(1024)
331
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
M
minghaoBD 已提交
332 333 334 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
        self.check_grad(['X'], 'Out')


346 347 348 349 350
class TestSilu_ZeroDim(TestSilu):
    def init_shape(self):
        self.shape = []


M
minghaoBD 已提交
351 352 353 354
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')
355 356 357
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
M
minghaoBD 已提交
358
            else paddle.CPUPlace()
359
        )
M
minghaoBD 已提交
360 361 362 363 364 365 366 367 368 369 370 371

    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:
372
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
M
minghaoBD 已提交
373 374 375 376 377 378 379 380 381

    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]:
382
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
M
minghaoBD 已提交
383 384 385 386 387 388 389
        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.
390 391 392
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32'
            )
M
minghaoBD 已提交
393 394
            self.assertRaises(TypeError, F.silu, x_int32)
            # support the input dtype is float16
395 396 397
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16'
            )
M
minghaoBD 已提交
398 399 400
            F.silu(x_fp16)


C
chengduo 已提交
401
class TestLogSigmoid(TestActivation):
402 403
    def setUp(self):
        self.op_type = "logsigmoid"
404
        self.init_dtype()
405
        self.init_shape()
406

407
        np.random.seed(2048)
408
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
409 410
        out = np.log(1 / (1 + np.exp(-x)))

411
        self.inputs = {'X': x}
412
        self.outputs = {'Out': out}
413 414

    def test_check_grad(self):
415 416
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
417
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
418 419


420 421 422 423 424
class TestLogSigmoid_ZeroDim(TestLogSigmoid):
    def init_shape(self):
        self.shape = []


425
class TestLogSigmoidAPI(unittest.TestCase):
426
    # test paddle.nn.LogSigmoid, paddle.nn.functional.log_sigmoid
427
    def setUp(self):
428
        np.random.seed(1024)
429
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
430 431 432
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
433
            else paddle.CPUPlace()
434
        )
435 436

    def test_static_api(self):
437
        paddle.enable_static()
438
        with paddle.static.program_guard(paddle.static.Program()):
439
            x = paddle.fluid.data('X', [11, 17])
440
            out1 = F.log_sigmoid(x)
441 442 443 444 445 446
            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:
447
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
448 449 450 451

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
452
        out1 = F.log_sigmoid(x)
453 454 455 456
        m = paddle.nn.LogSigmoid()
        out2 = m(x)
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in [out1, out2]:
457
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
458 459 460
        paddle.enable_static()

    def test_errors(self):
461
        paddle.enable_static()
462 463
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
464
            self.assertRaises(TypeError, F.log_sigmoid, 1)
465
            # The input dtype must be float16, float32, float64.
466 467 468
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32'
            )
469
            self.assertRaises(TypeError, F.log_sigmoid, x_int32)
470
            # support the input dtype is float16
471 472 473
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16'
            )
474
            F.log_sigmoid(x_fp16)
475 476


477
class TestTanh(TestActivation, TestParameter):
478 479
    def setUp(self):
        self.op_type = "tanh"
480
        self.init_dtype()
481 482
        self.init_shape()

483
        np.random.seed(1024)
484
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
485 486 487 488
        out = np.tanh(x)

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

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

495
    def init_dtype(self):
496
        # TODO If dtype is float64, the output (Out) has diff at CPUPlace
497 498 499 500
        # when using and not using inplace. Therefore, set dtype as float32
        # for now.
        self.dtype = np.float32

501

502 503 504 505 506
class TestTanh_ZeroDim(TestTanh):
    def init_shape(self):
        self.shape = []


W
WangXi 已提交
507 508 509 510
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
511
        np.random.seed(1024)
W
WangXi 已提交
512
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
513 514 515
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
W
WangXi 已提交
516
            else paddle.CPUPlace()
517
        )
518 519 520 521
        self.executed_api()

    def executed_api(self):
        self.tanh = F.tanh
W
WangXi 已提交
522 523

    def test_static_api(self):
524
        paddle.enable_static()
W
WangXi 已提交
525
        with paddle.static.program_guard(paddle.static.Program()):
526
            x = paddle.fluid.data('X', [10, 12], self.dtype)
527
            out1 = self.tanh(x)
W
WangXi 已提交
528 529 530 531 532 533
            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:
534
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
W
WangXi 已提交
535 536 537

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
538
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
539 540 541 542 543 544
        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]:
545
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
W
WangXi 已提交
546 547 548
        paddle.enable_static()

    def test_errors(self):
549
        paddle.enable_static()
W
WangXi 已提交
550 551
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
552
            self.assertRaises(TypeError, self.tanh, 1)
W
WangXi 已提交
553
            # The input dtype must be float16, float32.
554 555 556
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
557
            self.assertRaises(TypeError, self.tanh, x_int32)
W
WangXi 已提交
558
            # support the input dtype is float16
559 560 561
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
562 563 564 565 566 567 568
            self.tanh(x_fp16)


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


571
class TestAtan(TestActivation, TestParameter):
572 573 574
    def setUp(self):
        self.op_type = "atan"
        self.init_dtype()
575
        self.init_shape()
576

577
        np.random.seed(1024)
578
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
579 580 581 582 583 584 585 586
        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
587
        self.check_grad(['X'], 'Out')
588

W
WuHaobo 已提交
589 590
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
G
GGBond8488 已提交
591 592
            np_x = np.array([0.1]).astype('float32').reshape((-1, 1))
            data = paddle.static.data(name="X", shape=[-1, 1], dtype="float32")
W
WuHaobo 已提交
593 594 595
            out = paddle.atan(data, name='Y')
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
596
            (result,) = exe.run(feed={"X": np_x}, fetch_list=[out])
W
WuHaobo 已提交
597 598 599
            expected = np.arctan(np_x)
            self.assertEqual(result, expected)

600 601 602 603 604 605 606 607
    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)

608

609 610 611 612 613
class TestAtan_ZeroDim(TestTanh):
    def init_shape(self):
        self.shape = []


614 615 616 617
class TestSinh(TestActivation):
    def setUp(self):
        self.op_type = "sinh"
        self.init_dtype()
618
        self.init_shape()
619

620
        np.random.seed(1024)
621
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
622 623 624 625 626 627 628 629 630 631
        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')

632 633 634 635 636 637 638

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


class TestSinhAPI(unittest.TestCase):
639 640 641 642
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
643
            z = paddle.sinh(x).numpy()
644
            z_expected = np.sinh(np_x)
645
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
646 647 648 649

    def test_api(self):
        test_data_shape = [11, 17]
        with fluid.program_guard(fluid.Program(), fluid.Program()):
650 651 652
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
G
GGBond8488 已提交
653
            data_x = paddle.static.data(
654 655 656 657
                name="data_x",
                shape=test_data_shape,
                dtype="float32",
            )
658

659
            pd_sinh_out = paddle.sinh(data_x)
660 661
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
662 663 664 665 666
            (np_sinh_res,) = exe.run(
                fluid.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[pd_sinh_out],
            )
667 668

        expected_res = np.sinh(input_x)
669
        np.testing.assert_allclose(np_sinh_res, expected_res, rtol=1e-05)
670 671 672 673

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
674 675 676
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
677 678
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
679
            loss = paddle.sinh(var)
680 681 682 683 684 685 686 687 688
            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.
689
            self.assertRaises(TypeError, paddle.sinh, 1)
690 691
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
692
            self.assertRaises(TypeError, paddle.sinh, x_int32)
693 694
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
695
            paddle.sinh(x_fp16)
696 697 698 699 700 701


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

704
        np.random.seed(1024)
705
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
706 707 708 709 710 711 712 713 714 715
        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')

716 717 718 719 720 721 722

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


class TestCoshAPI(unittest.TestCase):
723 724 725 726
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
727
            z = paddle.cosh(x).numpy()
728
            z_expected = np.cosh(np_x)
729
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
730 731 732 733

    def test_api(self):
        test_data_shape = [11, 17]
        with fluid.program_guard(fluid.Program(), fluid.Program()):
734 735 736
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
G
GGBond8488 已提交
737
            data_x = paddle.static.data(
738 739 740 741
                name="data_x",
                shape=test_data_shape,
                dtype="float32",
            )
742 743 744 745

            pd_cosh_out = paddle.cosh(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
746 747 748 749 750
            (np_cosh_res,) = exe.run(
                fluid.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[pd_cosh_out],
            )
751 752

        expected_res = np.cosh(input_x)
753
        np.testing.assert_allclose(np_cosh_res, expected_res, rtol=1e-05)
754 755 756 757

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
758 759 760
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
761 762
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
763
            loss = paddle.cosh(var)
764 765 766 767 768 769 770 771 772
            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.
773
            self.assertRaises(TypeError, paddle.cosh, 1)
774 775
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
776
            self.assertRaises(TypeError, paddle.cosh, x_int32)
777 778
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
779
            paddle.cosh(x_fp16)
780 781


782 783 784 785 786 787
def ref_tanhshrink(x):
    out = x - np.tanh(x)
    return out


class TestTanhshrink(TestActivation):
K
Kavya Srinet 已提交
788 789
    def setUp(self):
        self.op_type = "tanh_shrink"
790
        self.init_dtype()
791
        self.init_shape()
792

793
        np.random.seed(1024)
794
        x = np.random.uniform(10, 20, self.shape).astype(self.dtype)
795
        out = ref_tanhshrink(x)
796

797
        self.inputs = {'X': x}
798
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
799 800

    def test_check_grad(self):
801 802
        if self.dtype == np.float16:
            return
803
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
804

805

806 807 808 809 810
class TestTanhshrink_ZeroDim(TestTanhshrink):
    def init_shape(self):
        self.shape = []


811 812 813
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
814
        np.random.seed(1024)
815
        self.x_np = np.random.uniform(10, 20, [10, 17]).astype(np.float64)
816 817 818
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
819
            else paddle.CPUPlace()
820
        )
821 822

    def test_static_api(self):
823
        paddle.enable_static()
824
        with paddle.static.program_guard(paddle.static.Program()):
825
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
826 827 828 829 830 831 832
            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:
833
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
834 835 836 837 838 839 840 841 842

    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]:
843
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
844 845 846
        paddle.enable_static()

    def test_errors(self):
847
        paddle.enable_static()
848 849 850 851
        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.
852 853 854
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
855 856
            self.assertRaises(TypeError, F.tanhshrink, x_int32)
            # support the input dtype is float16
857 858 859
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
860 861 862
            F.tanhshrink(x_fp16)


863 864 865 866 867 868
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
869
class TestHardShrink(TestActivation):
870 871
    def setUp(self):
        self.op_type = "hard_shrink"
872
        self.init_dtype()
873
        self.init_shape()
874

875 876
        self.threshold = 0.5
        self.set_attrs()
877
        np.random.seed(1024)
878
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype) * 10
879
        out = ref_hardshrink(x, self.threshold)
880

881
        self.attrs = {'threshold': self.threshold}
882
        self.inputs = {'X': x}
883
        self.outputs = {'Out': out}
884

885 886 887
    def init_shape(self):
        self.shape = [10, 12]

888 889 890
    def set_attrs(self):
        pass

891
    def test_check_grad(self):
892 893
        if self.dtype == np.float16:
            return
894
        self.check_grad(['X'], 'Out')
895 896


897 898 899 900 901
class TestHardShrink_threshold_negative(TestHardShrink):
    def set_attrs(self):
        self.threshold = -0.1


902 903 904 905 906 907 908 909
'''
class TestHardShrink_ZeroDim(TestHardShrink):

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


910 911 912
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
913
        np.random.seed(1024)
914
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
915 916 917
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
918
            else paddle.CPUPlace()
919
        )
920 921

    def test_static_api(self):
922
        paddle.enable_static()
923
        with paddle.static.program_guard(paddle.static.Program()):
924
            x = paddle.fluid.data('X', [10, 12])
925 926 927 928 929 930 931
            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:
932
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
933 934 935

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
936
        x = paddle.to_tensor(self.x_np)
937 938 939 940 941
        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]:
942
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
943 944 945 946 947 948

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

952
    def test_errors(self):
953
        paddle.enable_static()
954
        with paddle.static.program_guard(paddle.static.Program()):
955
            # The input type must be Variable.
956
            self.assertRaises(TypeError, F.hardshrink, 1)
957
            # The input dtype must be float16, float32, float64.
958 959 960
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
961
            self.assertRaises(TypeError, F.hardshrink, x_int32)
962
            # support the input dtype is float16
963 964 965
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
966
            F.hardshrink(x_fp16)
967 968


969 970 971 972 973 974 975 976 977 978 979
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):
980
        np.random.seed(1024)
981
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
982 983 984
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
985
            else paddle.CPUPlace()
986
        )
987 988

    def test_static_api(self):
989
        paddle.enable_static()
990
        with paddle.static.program_guard(paddle.static.Program()):
991
            x = paddle.fluid.data('X', [10, 12])
992 993 994 995 996 997 998
            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:
999
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1000 1001 1002

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
1003
        x = paddle.to_tensor(self.x_np)
1004 1005 1006 1007 1008
        out1 = F.hardtanh(x)
        m = paddle.nn.Hardtanh()
        out2 = m(x)
        out_ref = ref_hardtanh(self.x_np)
        for r in [out1, out2]:
1009
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1010 1011 1012 1013 1014 1015

        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]:
1016
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1017 1018 1019
        paddle.enable_static()

    def test_errors(self):
1020
        paddle.enable_static()
1021 1022 1023 1024
        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.
1025 1026 1027
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
1028 1029
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
1030 1031 1032
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
1033 1034 1035
            F.hardtanh(x_fp16)


1036 1037 1038
def ref_softshrink(x, threshold=0.5):
    out = np.copy(x)
    out = (out < -threshold) * (out + threshold) + (out > threshold) * (
1039 1040
        out - threshold
    )
1041 1042 1043 1044
    return out


class TestSoftshrink(TestActivation):
1045 1046
    def setUp(self):
        self.op_type = "softshrink"
1047 1048
        self.check_eager = True
        self.python_api = paddle.nn.functional.softshrink
1049
        self.init_dtype()
1050
        self.init_shape()
1051

1052
        threshold = 0.8
1053

1054
        np.random.seed(1023)
1055
        x = np.random.uniform(0.25, 10, self.shape).astype(self.dtype)
1056 1057 1058
        out = ref_softshrink(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"lambda": threshold}
1059
        self.outputs = {'Out': out}
1060 1061

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

1066

1067 1068 1069 1070 1071
class TestSoftshrink_ZeroDim(TestSoftshrink):
    def init_shape(self):
        self.shape = []


1072 1073 1074 1075
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
1076
        np.random.seed(1024)
1077
        self.x_np = np.random.uniform(0.25, 10, [10, 12]).astype(np.float64)
1078 1079 1080
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1081
            else paddle.CPUPlace()
1082
        )
1083 1084

    def test_static_api(self):
1085
        paddle.enable_static()
1086
        with paddle.static.program_guard(paddle.static.Program()):
1087
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1088 1089 1090 1091 1092 1093 1094
            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:
1095
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1096 1097 1098 1099 1100 1101 1102 1103 1104

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

1108
    def test_errors(self):
1109
        paddle.enable_static()
1110
        with paddle.static.program_guard(paddle.static.Program()):
1111
            # The input type must be Variable.
1112
            self.assertRaises(TypeError, F.softshrink, 1)
1113
            # The input dtype must be float16, float32, float64.
1114 1115 1116
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
1117
            self.assertRaises(TypeError, F.softshrink, x_int32)
1118
            # The threshold must be no less than zero
1119 1120 1121
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[12, 10], dtype='float32'
            )
1122
            self.assertRaises(ValueError, F.softshrink, x_fp32, -1.0)
1123
            # support the input dtype is float16
1124 1125 1126
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
1127
            F.softshrink(x_fp16)
1128 1129


1130
class TestSqrt(TestActivation, TestParameter):
1131 1132
    def setUp(self):
        self.op_type = "sqrt"
1133
        self.prim_op_type = "prim"
1134
        self.python_api = paddle.sqrt
1135
        self.init_dtype()
1136
        self.init_shape()
1137

1138
        np.random.seed(1023)
1139
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
1140 1141 1142 1143
        out = np.sqrt(x)

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

1146
    # TODO(wanghao107) add prim test
1147
    def test_check_grad(self):
1148 1149
        if self.dtype == np.float16:
            return
1150 1151 1152 1153
        self.check_grad(['X'], 'Out', check_eager=True)

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

1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
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


1183 1184 1185 1186 1187
class TestSqrt_ZeroDim(TestSqrt):
    def init_shape(self):
        self.shape = []


1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
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)


1201 1202 1203
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
1204 1205 1206
class TestSqrtBF16(OpTest):
    def setUp(self):
        self.op_type = "sqrt"
1207
        self.prim_op_type = "prim"
1208
        self.python_api = paddle.sqrt
1209
        self.init_dtype()
1210
        self.init_shape()
1211 1212

        np.random.seed(1023)
1213
        x = np.random.uniform(0.1, 1, self.shape).astype(np.float32)
1214 1215 1216 1217 1218 1219
        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)}
1220 1221
        # TODO(wanghao107): add prim test
        self.enable_cinn = False
1222 1223 1224 1225

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

1226 1227 1228
    def init_shape(self):
        self.shape = [11, 17]

1229 1230
    def test_check_output(self):
        place = core.CUDAPlace(0)
1231
        self.check_output_with_place(place, check_eager=True)
1232 1233 1234

    def test_check_grad(self):
        place = core.CUDAPlace(0)
1235
        self.check_grad_with_place(place, ['X'], 'Out', check_eager=True)
1236 1237


Z
zhoukunsheng 已提交
1238 1239 1240
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
Z
zyfncg 已提交
1241
        self.python_api = paddle.rsqrt
Z
zhoukunsheng 已提交
1242
        self.init_dtype()
1243
        self.init_shape()
Z
zhoukunsheng 已提交
1244

1245
        np.random.seed(1024)
1246
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
1247 1248 1249 1250 1251
        out = 1.0 / np.sqrt(x)

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

1252 1253 1254
    def init_shape(self):
        self.shape = [10, 12]

Z
zhoukunsheng 已提交
1255 1256 1257
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1258 1259 1260
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.0005, check_eager=True
        )
Z
zhoukunsheng 已提交
1261 1262


1263 1264 1265 1266 1267 1268 1269 1270
'''
class TestRsqrt_ZeroDim(TestRsqrt):

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


C
chengduo 已提交
1271
class TestAbs(TestActivation):
1272 1273
    def setUp(self):
        self.op_type = "abs"
1274
        self.init_dtype()
1275
        self.init_shape()
1276

1277
        np.random.seed(1024)
1278
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
C
chengduo 已提交
1279
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
1280
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
1281
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
1282 1283
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
1284 1285 1286 1287
        out = np.abs(x)

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

1289 1290 1291
    def init_shape(self):
        self.shape = [4, 25]

1292
    def test_check_grad(self):
1293 1294
        if self.dtype == np.float16:
            return
1295
        self.check_grad(['X'], 'Out', check_eager=False)
1296

1297

1298 1299 1300 1301 1302
class TestAbs_ZeroDim(TestAbs):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1303
class TestCeil(TestActivation):
D
dzhwinter 已提交
1304 1305
    def setUp(self):
        self.op_type = "ceil"
1306 1307
        self.check_eager = True
        self.python_api = paddle.ceil
1308
        self.init_dtype()
1309
        self.init_shape()
1310

1311
        np.random.seed(1024)
1312
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1313 1314 1315 1316
        out = np.ceil(x)

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

1318 1319 1320
    def init_shape(self):
        self.shape = [10, 12]

D
dzhwinter 已提交
1321
    # The same reason with TestFloor
C
chengduo 已提交
1322
    def test_check_grad(self):
1323 1324 1325
        pass


1326 1327 1328 1329 1330
class TestCeil_ZeroDim(TestCeil):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1331
class TestFloor(TestActivation):
D
dzhwinter 已提交
1332 1333
    def setUp(self):
        self.op_type = "floor"
1334 1335
        self.check_eager = True
        self.python_api = paddle.floor
1336
        self.init_dtype()
1337
        self.init_shape()
1338

1339
        np.random.seed(1024)
1340
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1341 1342 1343 1344
        out = np.floor(x)

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

1346 1347 1348
    def init_shape(self):
        self.shape = [10, 12]

D
dzhwinter 已提交
1349
    # the gradient on floor, ceil, round is undefined.
1350
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
1351 1352
    # The same reason with TestFloor
    def test_check_grad(self):
1353 1354 1355
        pass


1356 1357 1358 1359 1360
class TestFloor_ZeroDim(TestFloor):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1361
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
1362 1363
    def setUp(self):
        self.op_type = "cos"
1364
        self.init_dtype()
1365
        self.init_shape()
1366

1367
        np.random.seed(1024)
1368
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1369 1370 1371 1372
        out = np.cos(x)

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

1374 1375 1376
    def init_shape(self):
        self.shape = [10, 12]

C
add sin  
chengduoZH 已提交
1377
    def test_check_grad(self):
1378 1379
        if self.dtype == np.float16:
            return
1380
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
1381

1382

1383 1384 1385 1386 1387
class TestCos_ZeroDim(TestCos):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
1388 1389 1390 1391 1392
class TestTan(TestActivation):
    def setUp(self):
        np.random.seed(1024)
        self.op_type = "tan"
        self.init_dtype()
1393 1394
        self.init_shape()

J
joejiong 已提交
1395
        self.dtype = 'float32'
1396
        self.x_np = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1397 1398 1399
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
J
joejiong 已提交
1400
            else paddle.CPUPlace()
1401
        )
J
joejiong 已提交
1402 1403 1404 1405 1406 1407

        out = np.tan(self.x_np)

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

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

J
joejiong 已提交
1411 1412 1413 1414 1415
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

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)
1427 1428 1429
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1430
            else paddle.CPUPlace()
1431
        )
1432

J
joejiong 已提交
1433 1434 1435 1436 1437
    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)
1438
        np.testing.assert_allclose(out_ref, out_test.numpy(), rtol=1e-05)
J
joejiong 已提交
1439 1440 1441 1442 1443
        paddle.enable_static()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
1444
            x = paddle.static.data('X', [11, 17], self.dtype)
J
joejiong 已提交
1445 1446 1447 1448
            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)
1449
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
J
joejiong 已提交
1450 1451 1452 1453

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
1454 1455 1456
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
J
joejiong 已提交
1457 1458 1459 1460 1461 1462 1463 1464
            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)


1465 1466 1467 1468
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()
1469
        self.init_shape()
1470

1471
        np.random.seed(1024)
1472
        x = np.random.uniform(-0.95, 0.95, self.shape).astype(self.dtype)
1473 1474 1475 1476 1477
        out = np.arccos(x)

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

1478 1479 1480
    def init_shape(self):
        self.shape = [10, 12]

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


1487 1488 1489 1490 1491
class TestAcos_ZeroDim(TestAcos):
    def init_shape(self):
        self.shape = []


1492
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
1493 1494
    def setUp(self):
        self.op_type = "sin"
1495
        self.init_dtype()
1496
        self.init_shape()
1497

1498
        np.random.seed(1024)
1499
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1500 1501 1502 1503
        out = np.sin(x)

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

1505 1506 1507
    def init_shape(self):
        self.shape = [10, 12]

C
add cos  
chengduoZH 已提交
1508
    def test_check_grad(self):
1509 1510
        if self.dtype == np.float16:
            return
1511
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
1512 1513


1514 1515 1516 1517 1518
class TestSin_ZeroDim(TestSin):
    def init_shape(self):
        self.shape = []


1519 1520 1521 1522
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()
1523
        self.init_shape()
1524

1525
        np.random.seed(2048)
1526
        x = np.random.uniform(-0.95, 0.95, self.shape).astype(self.dtype)
1527 1528 1529 1530 1531
        out = np.arcsin(x)

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

1532 1533 1534
    def init_shape(self):
        self.shape = [10, 12]

1535 1536 1537
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1538
        self.check_grad(['X'], 'Out')
1539 1540


1541 1542 1543 1544 1545
class TestAsin_ZeroDim(TestAsin):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1546 1547 1548 1549
class TestAcosh(TestActivation):
    def setUp(self):
        self.op_type = "acosh"
        self.init_dtype()
1550
        self.init_shape()
X
xiaoting 已提交
1551 1552

        np.random.seed(1024)
1553
        x = np.random.uniform(2, 3, self.shape).astype(self.dtype)
X
xiaoting 已提交
1554 1555 1556 1557 1558
        out = np.arccosh(x)

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

1559 1560 1561
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1562 1563 1564 1565 1566 1567
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1568 1569 1570 1571 1572
class TestAcosh_ZeroDim(TestAcosh):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1573 1574 1575 1576
class TestAsinh(TestActivation):
    def setUp(self):
        self.op_type = "asinh"
        self.init_dtype()
1577
        self.init_shape()
X
xiaoting 已提交
1578 1579

        np.random.seed(1024)
1580
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
X
xiaoting 已提交
1581 1582 1583 1584 1585
        out = np.arcsinh(x)

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

1586 1587 1588
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1589 1590 1591 1592 1593 1594
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1595 1596 1597 1598 1599
class TestAsinh_ZeroDim(TestAsinh):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1600 1601 1602 1603
class TestAtanh(TestActivation):
    def setUp(self):
        self.op_type = "atanh"
        self.init_dtype()
1604
        self.init_shape()
X
xiaoting 已提交
1605 1606

        np.random.seed(400)
1607
        x = np.random.uniform(-0.9, 0.9, self.shape).astype(self.dtype)
X
xiaoting 已提交
1608 1609 1610 1611 1612
        out = np.arctanh(x)

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

1613 1614 1615
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1616 1617 1618 1619 1620 1621
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1622 1623 1624 1625 1626
class TestAtanh_ZeroDim(TestAtanh):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1627
class TestRound(TestActivation):
D
dzhwinter 已提交
1628 1629
    def setUp(self):
        self.op_type = "round"
1630 1631
        self.check_eager = True
        self.python_api = paddle.round
1632
        self.init_dtype()
1633
        self.init_shape()
1634

1635
        np.random.seed(1024)
1636
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1637 1638 1639 1640
        out = np.round(x)

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

1642 1643 1644
    def init_shape(self):
        self.shape = [10, 12]

C
chengduo 已提交
1645
    def test_check_grad(self):
1646 1647 1648
        pass


1649 1650 1651 1652 1653
class TestRound_ZeroDim(TestRound):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1654
class TestRelu(TestActivation):
1655
    def setUp(self):
Q
qijun 已提交
1656
        self.op_type = "relu"
K
Kexin Zhao 已提交
1657
        self.init_dtype()
1658
        self.init_shape()
K
Kexin Zhao 已提交
1659

1660
        np.random.seed(1024)
1661
        if self.dtype == np.uint16:
1662
            x = np.random.uniform(-1, 1, self.shape).astype(np.float32)
1663 1664 1665 1666 1667
            # 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:
1668
            x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1669 1670 1671 1672
            # 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 已提交
1673 1674

        self.outputs = {'Out': out}
1675 1676

    def test_check_grad(self):
K
Kexin Zhao 已提交
1677 1678
        if self.dtype == np.float16:
            return
1679
        self.check_grad(['X'], 'Out')
A
Adam 已提交
1680 1681


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


1687 1688 1689
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1690
        np.random.seed(1024)
1691
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
1692 1693 1694
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1695
            else paddle.CPUPlace()
1696
        )
1697 1698 1699 1700
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1701 1702

    def test_static_api(self):
1703
        paddle.enable_static()
1704
        with paddle.static.program_guard(paddle.static.Program()):
1705
            x = paddle.fluid.data('X', [10, 12])
1706
            out1 = self.relu(x)
1707 1708 1709 1710 1711 1712
            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:
1713
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1714 1715 1716 1717 1718

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.ReLU()
1719 1720
        out1 = m(x)
        out2 = self.relu(x)
1721 1722
        out_ref = np.maximum(self.x_np, 0)
        for r in [out1, out2]:
1723
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1724 1725
        paddle.enable_static()

1726
    def test_errors(self):
1727
        paddle.enable_static()
1728
        with paddle.static.program_guard(paddle.static.Program()):
1729
            # The input type must be Variable.
1730
            self.assertRaises(TypeError, self.relu, 1)
1731
            # The input dtype must be float16, float32, float64.
1732 1733 1734
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32'
            )
1735
            self.assertRaises(TypeError, self.relu, x_int32)
1736
            # support the input dtype is float16
1737 1738 1739
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16'
            )
1740 1741 1742 1743 1744 1745 1746
            self.relu(x_fp16)


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


1749 1750 1751 1752 1753 1754
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1755
class TestLeakyRelu(TestActivation):
1756 1757 1758
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1759 1760 1761
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()
1762
        self.init_shape()
1763
        alpha = self.get_alpha()
A
Adam 已提交
1764

1765
        np.random.seed(1024)
1766
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
A
Adam 已提交
1767
        # The same reason with TestAbs
1768 1769
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1770

1771
        self.inputs = {'X': x}
A
Adam 已提交
1772
        self.outputs = {'Out': out}
1773
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1774 1775 1776 1777

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


1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
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


1796 1797 1798 1799 1800
class TestLeakyRelu_ZeroDim(TestLeakyRelu):
    def init_shape(self):
        self.shape = []


1801 1802 1803
class TestLeakyReluAPI(unittest.TestCase):
    # test paddle.nn.LeakyReLU, paddle.nn.functional.leaky_relu,
    def setUp(self):
1804
        np.random.seed(1024)
1805
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
1806 1807 1808
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1809
            else paddle.CPUPlace()
1810
        )
1811 1812

    def test_static_api(self):
1813
        paddle.enable_static()
1814
        with paddle.static.program_guard(paddle.static.Program()):
1815
            x = paddle.fluid.data('X', [10, 12])
1816 1817 1818 1819 1820 1821 1822
            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:
1823
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1824 1825 1826

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
1827
        x = paddle.to_tensor(self.x_np)
1828 1829 1830 1831 1832
        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]:
1833
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1834 1835 1836 1837 1838 1839

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

1843
    def test_errors(self):
1844
        paddle.enable_static()
1845
        with paddle.static.program_guard(paddle.static.Program()):
1846
            # The input type must be Variable.
1847
            self.assertRaises(TypeError, F.leaky_relu, 1)
1848
            # The input dtype must be float16, float32, float64.
1849 1850 1851
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
1852 1853
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
1854 1855 1856
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
1857
            F.leaky_relu(x_fp16)
1858 1859


1860 1861
def gelu(x, approximate):
    if approximate:
1862 1863 1864 1865 1866 1867 1868 1869
        y_ref = (
            0.5
            * x
            * (
                1.0
                + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))
            )
        )
1870 1871 1872 1873 1874 1875
    else:
        y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
    return y_ref.astype(x.dtype)


class TestGeluApproximate(TestActivation):
C
Clementine 已提交
1876 1877 1878
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1879
        self.init_shape()
1880
        approximate = True
1881
        np.random.seed(1024)
1882
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1883
        out = gelu(x, approximate)
C
Clementine 已提交
1884

1885
        self.inputs = {'X': x}
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
        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()
1899
        self.init_shape()
1900
        approximate = False
1901
        np.random.seed(2048)
1902
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1903
        out = gelu(x, approximate)
C
Clementine 已提交
1904

1905
        self.inputs = {'X': x}
C
Clementine 已提交
1906
        self.outputs = {'Out': out}
1907
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1908 1909 1910 1911

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


1915 1916 1917 1918 1919
class TestGelu_ZeroDim(TestGelu):
    def init_shape(self):
        self.shape = []


1920 1921 1922
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1923
        np.random.seed(1024)
1924
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
1925 1926 1927
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1928
            else paddle.CPUPlace()
1929
        )
1930 1931

    def test_static_api(self):
1932
        paddle.enable_static()
1933
        with paddle.static.program_guard(paddle.static.Program()):
1934
            x = paddle.fluid.data('X', [11, 17])
1935 1936 1937 1938 1939 1940 1941
            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:
1942
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1943 1944 1945 1946 1947 1948 1949 1950 1951

    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]:
1952
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1953 1954 1955 1956 1957 1958

        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]:
1959
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1960 1961 1962
        paddle.enable_static()

    def test_errors(self):
1963
        paddle.enable_static()
1964 1965 1966 1967
        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.
1968 1969 1970
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32'
            )
1971 1972
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
1973 1974 1975
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16'
            )
1976 1977 1978
            F.gelu(x_fp16)


C
chengduo 已提交
1979
class TestBRelu(TestActivation):
1980 1981
    def setUp(self):
        self.op_type = "brelu"
1982 1983
        self.init_dtype()

1984
        np.random.seed(1024)
Z
zhupengyang 已提交
1985
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1986 1987
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
1988 1989
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
1990
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
1991 1992 1993
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
1994 1995 1996

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

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

2004

2005 2006 2007 2008 2009 2010 2011
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 已提交
2012
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
2013
    def setUp(self):
2014
        self.op_type = "relu6"
2015
        self.init_dtype()
2016
        self.init_shape()
2017
        self.python_api = paddle.nn.functional.relu6
2018

2019
        np.random.seed(1024)
2020
        x = np.random.uniform(-1, 10, self.shape).astype(self.dtype)
2021
        x[np.abs(x) < 0.005] = 0.02
2022
        out = ref_relu6(x)
2023

2024 2025
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
2026
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
2027

2028 2029 2030
    def init_shape(self):
        self.shape = [10, 12]

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


2037 2038 2039 2040 2041
class TestRelu6_ZeroDim(TestRelu6):
    def init_shape(self):
        self.shape = []


2042 2043 2044
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
2045
        np.random.seed(1024)
2046 2047
        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
2048 2049 2050
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2051
            else paddle.CPUPlace()
2052
        )
2053 2054

    def test_static_api(self):
2055
        paddle.enable_static()
2056
        with paddle.static.program_guard(paddle.static.Program()):
2057
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2058 2059 2060 2061 2062 2063 2064
            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:
2065
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2066 2067 2068 2069 2070 2071 2072 2073 2074

    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]:
2075
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2076 2077 2078
        paddle.enable_static()

    def test_fluid_api(self):
2079
        paddle.enable_static()
2080 2081
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
2082
            out = paddle.nn.functional.relu6(x)
2083 2084 2085
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_relu6(self.x_np)
2086
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2087

2088
    def test_errors(self):
2089
        paddle.enable_static()
2090
        with paddle.static.program_guard(paddle.static.Program()):
2091
            # The input type must be Variable.
2092
            self.assertRaises(TypeError, F.relu6, 1)
2093
            # The input dtype must be float16, float32, float64.
2094 2095 2096
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
2097
            self.assertRaises(TypeError, F.relu6, x_int32)
2098
            # support the input dtype is float16
2099 2100 2101
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
2102
            F.relu6(x_fp16)
2103 2104


2105
def ref_hardswish(x, threshold=6.0, scale=6.0, offset=3.0):
Z
Zhang Ting 已提交
2106 2107 2108 2109
    x_dtype = x.dtype
    if x_dtype == 'float16':
        x_dtype = 'float16'
        x = x.astype('float32')
2110 2111 2112
    return (
        x * np.minimum(np.maximum(x + offset, 0.0), threshold) / scale
    ).astype(x_dtype)
2113 2114


H
huangjun12 已提交
2115 2116 2117 2118
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()
2119
        self.init_shape()
2120
        self.python_api = paddle.nn.functional.hardswish
J
jakpiase 已提交
2121

2122
        np.random.seed(1024)
2123
        x = np.random.uniform(-6, 6, self.shape).astype(self.dtype)
H
huangjun12 已提交
2124 2125 2126
        threshold = 6.0
        scale = 6.0
        offset = 3.0
2127
        # the same with TestAbs
H
huangjun12 已提交
2128 2129
        x[np.abs(x + offset) < 0.005] = 0.02
        x[np.abs(x - threshold + offset) < 0.005] = threshold - offset + 0.02
2130
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
2131

2132
        self.inputs = {'X': x}
H
huangjun12 已提交
2133 2134 2135
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
        self.outputs = {'Out': out}

2136 2137 2138
    def init_shape(self):
        self.shape = [10, 12]

H
huangjun12 已提交
2139
    def test_check_grad(self):
2140 2141 2142 2143
        self.check_grad(['X'], 'Out', check_eager=True)

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


2146 2147 2148 2149 2150
class TestHardSwish_ZeroDim(TestHardSwish):
    def init_shape(self):
        self.shape = []


2151 2152 2153 2154
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)
2155 2156 2157
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2158
            else paddle.CPUPlace()
2159
        )
2160 2161 2162

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
2163
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2164 2165 2166 2167 2168 2169 2170
            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:
2171
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2172 2173 2174

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
2175
        x = paddle.to_tensor([11648.0, 11448.0])
2176 2177 2178
        out1 = F.hardswish(x)
        m = paddle.nn.Hardswish()
        out2 = m(x)
2179
        out_ref = [11648.0, 11448.0]
2180
        for r in [out1, out2]:
2181
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2182
        paddle.enable_static()
2183 2184 2185 2186

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
2187
            out = paddle.nn.functional.hardswish(x)
2188 2189 2190
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardswish(self.x_np)
2191
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2192 2193 2194

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
2195
        out = paddle.nn.functional.hardswish(x)
2196
        np.testing.assert_allclose(out_ref, out.numpy(), rtol=1e-05)
2197 2198 2199 2200
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
2201
            # The input type must be Variable.
2202
            self.assertRaises(TypeError, F.hardswish, 1)
2203
            # The input dtype must be float16, float32, float64.
2204 2205 2206
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
2207
            self.assertRaises(TypeError, F.hardswish, x_int32)
2208
            # support the input dtype is float16
2209 2210 2211
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
2212
            F.hardswish(x_fp16)
2213 2214


C
chengduo 已提交
2215
class TestSoftRelu(TestActivation):
2216 2217
    def setUp(self):
        self.op_type = "soft_relu"
2218 2219
        self.init_dtype()

2220
        np.random.seed(4096)
2221
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
2222
        threshold = 2.0
Q
qijun 已提交
2223 2224
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
2225
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
2226 2227 2228
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
2229 2230 2231 2232 2233
        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}
2234 2235

    def test_check_grad(self):
2236 2237
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
2238
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
2239

2240

2241
def elu(x, alpha):
Z
zhupengyang 已提交
2242
    out_ref = np.where(x > 0, x, alpha * (np.exp(x) - 1))
2243 2244 2245
    return out_ref.astype(x.dtype)


C
chengduo 已提交
2246
class TestELU(TestActivation):
2247 2248
    def setUp(self):
        self.op_type = "elu"
2249
        self.init_dtype()
2250
        self.init_shape()
2251

2252
        np.random.seed(1024)
2253
        x = np.random.uniform(-3, 3, self.shape).astype(self.dtype)
Z
zhupengyang 已提交
2254
        alpha = self.get_alpha()
2255
        out = elu(x, alpha)
2256 2257 2258 2259
        # 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}
2260
        self.outputs = {'Out': out}
2261

2262 2263 2264
    def init_shape(self):
        self.shape = [10, 12]

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

Z
zhupengyang 已提交
2270
    def get_alpha(self):
2271
        return 1.0
Z
zhupengyang 已提交
2272 2273 2274 2275 2276 2277


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

2278

2279 2280 2281 2282 2283
class TestELU_ZeroDim(TestELU):
    def init_shape(self):
        self.shape = []


2284 2285 2286
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
2287
        np.random.seed(1024)
2288
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
2289 2290 2291
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2292
            else paddle.CPUPlace()
2293
        )
2294 2295 2296 2297
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
2298 2299

    def test_static_api(self):
2300
        paddle.enable_static()
2301
        with paddle.static.program_guard(paddle.static.Program()):
2302
            x = paddle.fluid.data('X', [10, 12])
2303
            out1 = self.elu(x)
2304 2305 2306 2307 2308 2309
            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:
2310
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2311 2312 2313 2314

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
2315 2316
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
2317 2318 2319 2320
        m = paddle.nn.ELU()
        out2 = m(x)
        out_ref = elu(self.x_np, 1.0)
        for r in [out1, out2]:
2321
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2322

2323 2324
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
2325 2326 2327 2328
        m = paddle.nn.ELU(0.2)
        out2 = m(x)
        out_ref = elu(self.x_np, 0.2)
        for r in [out1, out2]:
2329
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2330 2331
        paddle.enable_static()

2332
    def test_errors(self):
2333
        paddle.enable_static()
2334 2335
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
2336
            self.assertRaises(TypeError, self.elu, 1)
2337
            # The input dtype must be float16, float32, float64.
2338 2339 2340
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32'
            )
2341
            self.assertRaises(TypeError, self.elu, x_int32)
2342
            # support the input dtype is float16
2343 2344 2345
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16'
            )
2346 2347 2348
            self.elu(x_fp16)


Z
zhupengyang 已提交
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
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()


2361 2362 2363 2364 2365 2366 2367 2368 2369
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()
2370
        self.init_shape()
2371

2372
        self.python_api = paddle.nn.functional.celu
2373
        np.random.seed(1024)
2374
        x = np.random.uniform(-3, 3, self.shape).astype(self.dtype)
2375 2376 2377 2378 2379 2380
        alpha = 1.5
        out = celu(x, alpha)
        self.inputs = {'X': x}
        self.attrs = {'alpha': alpha}
        self.outputs = {'Out': out}

2381 2382 2383
    def init_shape(self):
        self.shape = [10, 12]

2384 2385 2386
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
2387
        self.check_grad(['X'], 'Out', check_eager=True)
2388 2389


2390 2391 2392 2393 2394
class TestCELU_ZeroDim(TestCELU):
    def init_shape(self):
        self.shape = []


2395 2396 2397 2398 2399
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')
2400 2401 2402
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2403
            else paddle.CPUPlace()
2404
        )
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
        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:
2421
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431

    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]:
2432
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2433 2434 2435 2436 2437 2438 2439

        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]:
2440
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2441 2442 2443 2444 2445 2446 2447 2448
        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.
2449 2450 2451
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32'
            )
2452 2453
            self.assertRaises(TypeError, self.celu, x_int32)
            # The alpha must be not equal 0
2454 2455 2456
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[10, 12], dtype='float32'
            )
2457 2458
            self.assertRaises(ZeroDivisionError, F.celu, x_fp32, 0)
            # support the input dtype is float16
2459 2460 2461
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16'
            )
2462 2463 2464
            self.celu(x_fp16)


C
chengduo 已提交
2465
class TestReciprocal(TestActivation):
Q
qijun 已提交
2466 2467
    def setUp(self):
        self.op_type = "reciprocal"
2468
        self.python_api = paddle.reciprocal
2469
        self.init_dtype()
2470
        self.init_shape()
2471

2472
        np.random.seed(1024)
2473
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
2474 2475 2476 2477
        out = np.reciprocal(x)

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

    def test_check_grad(self):
2480 2481
        if self.dtype == np.float16:
            return
2482 2483 2484 2485
        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 已提交
2486 2487


2488 2489 2490 2491 2492
class TestReciprocal_ZeroDim(TestReciprocal):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
2493
class TestLog(TestActivation):
Q
qijun 已提交
2494 2495
    def setUp(self):
        self.op_type = "log"
2496 2497
        self.check_eager = True
        self.python_api = paddle.log
2498
        self.init_dtype()
2499
        self.init_shape()
2500

2501
        np.random.seed(1024)
2502
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2503 2504 2505 2506
        out = np.log(x)

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

    def test_check_grad(self):
2509 2510
        if self.dtype == np.float16:
            return
2511
        self.check_grad(['X'], 'Out', check_eager=True)
Q
qijun 已提交
2512

2513
    def test_error(self):
G
GGBond8488 已提交
2514 2515
        in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
        in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")
2516

2517 2518
        self.assertRaises(TypeError, paddle.log, in1)
        self.assertRaises(TypeError, paddle.log, in2)
2519

2520

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


J
joejiong 已提交
2526 2527 2528
class TestLog2(TestActivation):
    def setUp(self):
        self.op_type = "log2"
2529 2530
        self.check_eager = True
        self.python_api = paddle.log2
J
joejiong 已提交
2531
        self.init_dtype()
2532
        self.init_shape()
J
joejiong 已提交
2533

2534
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
J
joejiong 已提交
2535 2536 2537 2538 2539 2540 2541 2542
        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
2543
        self.check_grad(['X'], 'Out', check_eager=True)
J
joejiong 已提交
2544 2545 2546 2547 2548 2549 2550 2551 2552

    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):
2553 2554 2555
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
J
joejiong 已提交
2556
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
2557 2558 2559
            data_x = paddle.static.data(
                name="data_x", shape=[11, 17], dtype="float64"
            )
J
joejiong 已提交
2560 2561 2562 2563

            out1 = paddle.log2(data_x)
            exe = paddle.static.Executor(place=fluid.CPUPlace())
            exe.run(paddle.static.default_startup_program())
2564 2565 2566 2567 2568
            (res1,) = exe.run(
                paddle.static.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[out1],
            )
J
joejiong 已提交
2569
        expected_res = np.log2(input_x)
2570
        np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
J
joejiong 已提交
2571 2572 2573 2574 2575 2576 2577 2578

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


2582 2583 2584 2585 2586
class TestLog2_ZeroDim(TestLog2):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
2587 2588 2589
class TestLog10(TestActivation):
    def setUp(self):
        self.op_type = "log10"
2590 2591
        self.check_eager = True
        self.python_api = paddle.log10
J
joejiong 已提交
2592
        self.init_dtype()
2593
        self.init_shape()
J
joejiong 已提交
2594

2595
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
J
joejiong 已提交
2596 2597 2598 2599 2600 2601 2602 2603
        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
2604
        self.check_grad(['X'], 'Out', check_eager=True)
J
joejiong 已提交
2605

2606 2607 2608 2609 2610 2611 2612

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


class TestLog10API(unittest.TestCase):
J
joejiong 已提交
2613 2614 2615 2616 2617 2618 2619 2620
    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):
2621 2622 2623
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
J
joejiong 已提交
2624
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
2625 2626 2627
            data_x = paddle.static.data(
                name="data_x", shape=[11, 17], dtype="float64"
            )
J
joejiong 已提交
2628 2629 2630 2631

            out1 = paddle.log10(data_x)
            exe = paddle.static.Executor(place=paddle.CPUPlace())
            exe.run(paddle.static.default_startup_program())
2632 2633 2634 2635 2636
            (res1,) = exe.run(
                paddle.static.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[out1],
            )
J
joejiong 已提交
2637
        expected_res = np.log10(input_x)
2638
        np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
J
joejiong 已提交
2639 2640 2641 2642 2643 2644 2645 2646

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


2650 2651 2652
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
2653 2654
        self.check_eager = True
        self.python_api = paddle.log1p
2655
        self.init_dtype()
2656
        self.init_shape()
2657

2658
        np.random.seed(1024)
2659
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2660 2661 2662 2663 2664 2665 2666 2667
        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
2668
        self.check_grad(['X'], 'Out', check_eager=True)
2669

2670 2671 2672 2673 2674 2675 2676

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


class TestLog1pAPI(unittest.TestCase):
2677 2678 2679
    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 已提交
2680
            data_x = paddle.static.data(
2681 2682 2683 2684
                name="data_x",
                shape=[11, 17],
                dtype="float64",
            )
2685 2686 2687 2688

            out1 = paddle.log1p(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
2689 2690 2691 2692 2693
            (res1,) = exe.run(
                fluid.default_main_program(),
                feed={"data_x": input_x},
                fetch_list=[out1],
            )
2694
        expected_res = np.log1p(input_x)
2695
        np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
2696 2697 2698 2699 2700 2701 2702 2703

        # 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))
2704
        np.testing.assert_allclose(np_z, z_expected, rtol=1e-05)
2705 2706


C
chengduo 已提交
2707
class TestSquare(TestActivation):
Q
qijun 已提交
2708 2709
    def setUp(self):
        self.op_type = "square"
2710
        self.python_api = paddle.square
2711
        self.init_dtype()
2712
        self.init_shape()
2713

2714
        np.random.seed(1024)
2715
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2716 2717 2718 2719
        out = np.square(x)

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

    def test_check_grad(self):
2722 2723
        if self.dtype == np.float16:
            return
2724 2725 2726
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.007, check_eager=True
        )
2727 2728 2729

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

2731

2732 2733 2734 2735 2736
class TestSquare_ZeroDim(TestSquare):
    def init_shape(self):
        self.shape = []


2737 2738 2739
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
2740 2741 2742
class TestSquareBF16(OpTest):
    def setUp(self):
        self.op_type = "square"
2743
        self.python_api = paddle.square
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
        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)
2760
        self.check_output_with_place(place, check_eager=True)
2761 2762 2763

    def test_check_grad(self):
        place = core.CUDAPlace(0)
2764 2765 2766
        self.check_grad_with_place(
            place, ['X'], 'Out', numeric_grad_delta=0.5, check_eager=True
        )
2767 2768


C
chengduo 已提交
2769
class TestPow(TestActivation):
2770 2771
    def setUp(self):
        self.op_type = "pow"
2772
        self.python_api = paddle.pow
2773
        self.check_eager = True
2774
        self.init_dtype()
2775
        self.init_shape()
2776

2777
        np.random.seed(1024)
2778
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
2779 2780 2781
        out = np.power(x, 3)

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

2785 2786 2787
    def test_check_output(self):
        self.check_output(check_eager=self.check_eager)

2788
    def test_check_grad(self):
2789 2790
        if self.dtype == np.float16:
            return
2791
        self.check_grad(['X'], 'Out', check_eager=self.check_eager)
2792

2793

2794 2795 2796 2797 2798
class TestPow_ZeroDim(TestPow):
    def init_shape(self):
        self.shape = []


2799 2800 2801
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
2802 2803
        self.check_eager = False
        self.python_api = paddle.pow
2804 2805
        self.init_dtype()

2806
        np.random.seed(1024)
2807 2808 2809 2810 2811
        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),
2812
            'FactorTensor': np.array([3.0]).astype("float32"),
2813 2814 2815 2816 2817 2818
        }

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

    def test_check_output(self):
2819
        self.check_output(check_eager=self.check_eager)
2820 2821 2822 2823

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

    def test_api(self):
        input = np.random.uniform(1, 2, [11, 17]).astype("float32")
G
GGBond8488 已提交
2828 2829
        x = paddle.static.data(name="x", shape=[11, 17], dtype="float32")
        res = paddle.static.data(name="res", shape=[11, 17], dtype="float32")
2830 2831 2832

        factor_1 = 2.0
        factor_2 = fluid.layers.fill_constant([1], "float32", 3.0)
2833 2834
        out_1 = paddle.pow(x, factor_1)
        out_2 = paddle.pow(x, factor_2)
2835 2836 2837
        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)
2838 2839

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
2840
        res_1, res_2, res, res_6 = exe.run(
2841 2842
            fluid.default_main_program(),
            feed={"x": input},
2843 2844
            fetch_list=[out_1, out_2, res, out_6],
        )
2845

2846 2847 2848
        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))
2849 2850


2851 2852 2853 2854 2855
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
2856
class TestSTanh(TestActivation):
2857 2858 2859 2860 2861 2862
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

2863 2864
    def setUp(self):
        self.op_type = "stanh"
2865
        self.init_dtype()
2866 2867
        self.init_shape()

2868 2869
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
2870

2871
        np.random.seed(1024)
2872
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2873 2874
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
2875

2876
        self.inputs = {'X': x}
2877
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
2878
        self.outputs = {'Out': out}
2879

Q
qijun 已提交
2880
    def test_check_grad(self):
2881 2882
        if self.dtype == np.float16:
            return
2883
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
2884

2885

2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
class TestSTanhScaleA(TestSTanh):
    def get_scale_a(self):
        return 2.0


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


2896 2897 2898 2899 2900
class TestSTanh_ZeroDim(TestSTanh):
    def init_shape(self):
        self.shape = []


2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
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()
2914 2915 2916
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
2917
            else paddle.CPUPlace()
2918
        )
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928

    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:
2929
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2930 2931 2932 2933 2934 2935 2936

    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]:
2937
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2938 2939 2940 2941 2942 2943
        paddle.enable_static()

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
2944
            out = paddle.stanh(x, self.scale_a, self.scale_b)
2945 2946 2947
            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)
2948
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2949

2950
    def test_errors(self):
2951 2952
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2953
            # The input type must be Variable.
2954
            self.assertRaises(TypeError, paddle.stanh, 1)
2955
            # The input dtype must be float16, float32, float64.
2956 2957 2958
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
2959
            self.assertRaises(TypeError, paddle.stanh, x_int32)
2960
            # support the input dtype is float16
2961 2962 2963
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
            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
2975 2976


2977 2978
def ref_softplus(x, beta=1, threshold=20):
    x_beta = beta * x
2979 2980 2981 2982
    out = np.select(
        [x_beta <= threshold, x_beta > threshold],
        [np.log(1 + np.exp(x_beta)) / beta, x],
    )
2983 2984 2985
    return out


C
chengduo 已提交
2986
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
2987 2988
    def setUp(self):
        self.op_type = "softplus"
W
Wang Bojun 已提交
2989
        self.python_api = paddle.nn.functional.softplus
2990
        self.init_dtype()
2991
        self.init_shape()
2992

2993 2994
        beta = 2
        threshold = 15
2995

2996
        np.random.seed(1024)
2997
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
2998 2999 3000
        out = ref_softplus(x, beta, threshold)
        self.inputs = {'X': x}
        self.attrs = {'beta': beta, "threshold": threshold}
3001
        self.outputs = {'Out': out}
K
kexinzhao 已提交
3002

W
Wang Bojun 已提交
3003 3004
        self.check_eager = True

3005 3006 3007
    def init_shape(self):
        self.shape = [10, 12]

K
kexinzhao 已提交
3008
    def test_check_grad(self):
3009 3010
        if self.dtype == np.float16:
            return
W
Wang Bojun 已提交
3011 3012 3013
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
K
kexinzhao 已提交
3014

3015

3016 3017 3018 3019 3020
class TestSoftplus_ZeroDim(TestSoftplus):
    def init_shape(self):
        self.shape = []


3021 3022 3023
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
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)


3051 3052 3053 3054 3055
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
3056
        np.random.seed(1024)
3057
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
3058 3059 3060
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3061
            else paddle.CPUPlace()
3062
        )
3063 3064

    def test_static_api(self):
3065
        paddle.enable_static()
3066
        with paddle.static.program_guard(paddle.static.Program()):
3067
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
3068 3069 3070 3071 3072 3073 3074
            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:
3075
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3076 3077 3078 3079 3080 3081 3082 3083 3084

    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]:
3085
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3086 3087 3088
        paddle.enable_static()

    def test_errors(self):
3089
        paddle.enable_static()
3090 3091 3092 3093
        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.
3094 3095 3096
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3097 3098
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
3099 3100 3101
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3102 3103 3104 3105 3106 3107 3108 3109
            F.softplus(x_fp16)


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


C
chengduo 已提交
3110
class TestSoftsign(TestActivation):
3111 3112
    def setUp(self):
        self.op_type = "softsign"
3113
        self.init_dtype()
3114 3115
        self.init_shape()

3116
        self.python_api = paddle.nn.functional.softsign
3117

3118
        np.random.seed(1024)
3119
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3120 3121
        out = ref_softsign(x)
        self.inputs = {'X': x}
3122
        self.outputs = {'Out': out}
3123

3124 3125 3126
    def init_shape(self):
        self.shape = [10, 12]

3127
    def test_check_grad(self):
3128 3129
        if self.dtype == np.float16:
            return
3130
        self.check_grad(['X'], 'Out', check_eager=True)
3131 3132


3133 3134 3135 3136 3137
class TestSoftsign_ZeroDim(TestSoftsign):
    def init_shape(self):
        self.shape = []


3138 3139 3140
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
3141
        np.random.seed(1024)
3142
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
3143 3144 3145
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3146
            else paddle.CPUPlace()
3147
        )
3148 3149

    def test_static_api(self):
3150
        paddle.enable_static()
3151
        with paddle.static.program_guard(paddle.static.Program()):
3152
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
3153 3154 3155 3156 3157 3158 3159
            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:
3160
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3161 3162 3163 3164 3165 3166 3167 3168 3169

    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]:
3170
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3171 3172 3173
        paddle.enable_static()

    def test_errors(self):
3174
        paddle.enable_static()
3175 3176 3177 3178
        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.
3179 3180 3181
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3182 3183
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
3184 3185 3186
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3187 3188 3189
            F.softsign(x_fp16)


3190 3191 3192 3193 3194
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
3195
class TestThresholdedRelu(TestActivation):
3196 3197
    def setUp(self):
        self.op_type = "thresholded_relu"
3198
        self.init_dtype()
3199
        self.init_shape()
3200

3201
        threshold = 15
3202

3203
        np.random.seed(1024)
3204
        x = np.random.uniform(-20, 20, self.shape).astype(self.dtype)
3205 3206 3207 3208
        x[np.abs(x) < 0.005] = 0.02
        out = ref_thresholded_relu(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"threshold": threshold}
3209
        self.outputs = {'Out': out}
3210

3211 3212 3213
    def init_shape(self):
        self.shape = [10, 12]

3214
    def test_check_grad(self):
3215 3216
        if self.dtype == np.float16:
            return
3217
        self.check_grad(['X'], 'Out')
3218 3219


3220 3221 3222 3223 3224
class TestThresholdedRelu_ZeroDim(TestThresholdedRelu):
    def init_shape(self):
        self.shape = []


3225 3226 3227 3228 3229 3230 3231
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
3232 3233 3234
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3235
            else paddle.CPUPlace()
3236
        )
3237 3238 3239 3240

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3241
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
3242 3243 3244 3245 3246 3247 3248
            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:
3249
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3250 3251 3252 3253 3254 3255 3256 3257 3258

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

3262
    def test_errors(self):
3263 3264
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3265
            # The input type must be Variable.
3266
            self.assertRaises(TypeError, F.thresholded_relu, 1)
3267
            # The input dtype must be float16, float32, float64.
3268 3269 3270
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3271
            self.assertRaises(TypeError, F.thresholded_relu, x_int32)
3272
            # support the input dtype is float16
3273 3274 3275
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3276
            F.thresholded_relu(x_fp16)
3277 3278


3279
def ref_hardsigmoid(x, slope=0.166666666666667, offset=0.5):
3280
    return np.maximum(np.minimum(x * slope + offset, 1.0), 0.0).astype(x.dtype)
3281 3282


C
chengduo 已提交
3283
class TestHardSigmoid(TestActivation):
3284 3285
    def setUp(self):
        self.op_type = "hard_sigmoid"
3286 3287 3288 3289
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
3290
        self.init_shape()
3291

3292
        x = np.random.uniform(-5, 5, self.shape).astype(self.dtype)
3293
        lower_threshold = -self.offset / self.slope
3294
        upper_threshold = (1.0 - self.offset) / self.slope
Z
zhupengyang 已提交
3295

3296
        # Same reason as TestAbs
3297 3298 3299
        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
3300

3301
        out = ref_hardsigmoid(x, self.slope, self.offset)
3302

3303 3304
        self.attrs = {'slope': self.slope, 'offset': self.offset}
        self.inputs = {'X': x}
3305
        self.outputs = {'Out': out}
3306

3307 3308 3309
    def init_shape(self):
        self.shape = [10, 12]

3310 3311
    def set_attrs(self):
        pass
3312

3313

3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
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


3325 3326 3327 3328 3329
class TestHardSigmoid_ZeroDim(TestHardSigmoid):
    def init_shape(self):
        self.shape = []


3330 3331 3332 3333
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)
3334 3335 3336
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3337
            else paddle.CPUPlace()
3338
        )
3339 3340 3341

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
3342
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
3343 3344 3345 3346 3347 3348 3349
            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:
3350
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3351 3352 3353 3354 3355 3356 3357 3358 3359

    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]:
3360
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3361
        paddle.enable_static()
3362 3363 3364 3365

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
3366
            out = paddle.nn.functional.hardsigmoid(x, slope=0.2)
3367 3368 3369
            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)
3370
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3371 3372 3373

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
3374
        out = paddle.nn.functional.hardsigmoid(x, slope=0.2)
3375
        np.testing.assert_allclose(out_ref, out.numpy(), rtol=1e-05)
3376 3377 3378 3379
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
3380
            # The input type must be Variable.
3381
            self.assertRaises(TypeError, F.hardsigmoid, 1)
3382
            # The input dtype must be float16, float32, float64.
3383 3384 3385
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3386
            self.assertRaises(TypeError, F.hardsigmoid, x_int32)
3387
            # support the input dtype is float16
3388 3389 3390
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3391
            F.hardsigmoid(x_fp16)
3392 3393


3394 3395 3396 3397 3398
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
3399
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
3400 3401
    def setUp(self):
        self.op_type = "swish"
3402
        self.python_api = paddle.nn.functional.swish
3403
        self.init_dtype()
3404 3405
        self.init_shape()

3406
        self.check_eager = True
3407

3408
        np.random.seed(1024)
3409
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3410 3411
        out = ref_swish(x)
        self.inputs = {'X': x}
H
hong19860320 已提交
3412
        self.attrs = {'beta': 1.0}
3413
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
3414

3415 3416 3417
    def init_shape(self):
        self.shape = [10, 12]

A
Abhinav Arora 已提交
3418
    def test_check_grad(self):
3419 3420
        if self.dtype == np.float16:
            return
3421 3422 3423 3424
        check_eager = False
        if hasattr(self, 'check_eager'):
            check_eager = self.check_eager
        self.check_grad(['X'], 'Out', check_eager=check_eager)
3425

A
Abhinav Arora 已提交
3426

3427 3428 3429 3430 3431
class TestSwish_ZeroDim(TestSwish):
    def init_shape(self):
        self.shape = []


3432 3433 3434 3435 3436
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)
3437 3438 3439
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3440
            else paddle.CPUPlace()
3441
        )
3442 3443 3444 3445

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
3446
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
3447 3448 3449 3450 3451 3452 3453
            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:
3454
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3455

3456
    def test_dygraph_api(self):
3457 3458 3459 3460 3461 3462 3463
        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]:
3464
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3465 3466 3467 3468 3469 3470
        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)
3471
            out = paddle.nn.functional.swish(x)
3472 3473 3474
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_swish(self.x_np)
3475
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3476

3477
    def test_errors(self):
3478 3479
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
3480
            # The input type must be Variable.
3481
            self.assertRaises(TypeError, F.swish, 1)
3482
            # The input dtype must be float16, float32, float64.
3483 3484 3485
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3486
            self.assertRaises(TypeError, F.swish, x_int32)
3487
            # support the input dtype is float16
3488 3489 3490
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3491
            F.swish(x_fp16)
3492 3493


3494 3495 3496 3497
def ref_mish(x, threshold=20.0):
    softplus = np.select(
        [x <= threshold, x > threshold], [np.log(1 + np.exp(x)), x]
    )
3498 3499 3500 3501 3502 3503
    return x * np.tanh(softplus)


class TestMish(TestActivation):
    def setUp(self):
        self.op_type = "mish"
3504
        self.python_api = paddle.nn.functional.mish
3505
        self.init_dtype()
3506
        self.init_shape()
3507 3508

        np.random.seed(1024)
3509
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3510 3511 3512 3513
        out = ref_mish(x)
        self.inputs = {'X': x}
        self.outputs = {'Out': out}

3514 3515 3516
    def init_shape(self):
        self.shape = [10, 12]

3517 3518 3519
    def test_check_output(self):
        self.check_output(check_eager=True)

3520 3521 3522
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
3523
        self.check_grad(['X'], 'Out', check_eager=True)
3524 3525


3526 3527 3528 3529 3530
class TestMish_ZeroDim(TestMish):
    def init_shape(self):
        self.shape = []


3531 3532 3533 3534 3535
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)
3536 3537 3538
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3539
            else paddle.CPUPlace()
3540
        )
3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552

    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:
3553
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3554 3555 3556 3557 3558 3559 3560 3561 3562

    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]:
3563
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3564 3565 3566 3567 3568 3569
        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)
3570
            out = paddle.nn.functional.mish(x)
3571 3572 3573
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_mish(self.x_np)
3574
        np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3575 3576 3577 3578 3579 3580 3581

    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.
3582 3583 3584
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32'
            )
3585 3586
            self.assertRaises(TypeError, F.mish, x_int32)
            # support the input dtype is float16
3587 3588 3589
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16'
            )
3590 3591 3592
            F.mish(x_fp16)


3593
# ------------------ Test Cudnn Activation----------------------
3594
def create_test_act_cudnn_class(parent, atol=1e-3, grad_atol=1e-3):
3595 3596 3597
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
    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)


3613 3614 3615 3616 3617 3618 3619
# ------------------ 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 已提交
3620 3621 3622
    class TestActFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16
3623

C
chengduo 已提交
3624
        def test_check_output(self):
3625
            place = core.CUDAPlace(0)
C
chengduo 已提交
3626 3627 3628
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
3629

C
chengduo 已提交
3630 3631 3632 3633
        def test_check_grad(self):
            place = core.CUDAPlace(0)
            support_fp16 = core.is_float16_supported(place)
            if support_fp16 and grad_check:
3634 3635 3636
                self.check_grad_with_place(
                    place, ['X'], 'Out', max_relative_error=grad_atol
                )
C
chengduo 已提交
3637 3638 3639 3640 3641 3642 3643

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


create_test_act_fp16_class(TestActivation)
R
ronnywang 已提交
3644
create_test_act_fp16_class(TestExpm1)
C
chengduo 已提交
3645
create_test_act_fp16_class(TestSigmoid)
M
minghaoBD 已提交
3646
create_test_act_fp16_class(TestSilu)
C
chengduo 已提交
3647 3648
create_test_act_fp16_class(TestLogSigmoid)
create_test_act_fp16_class(TestTanh)
3649
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
3650
create_test_act_fp16_class(TestHardShrink)
3651
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
3652 3653 3654 3655 3656
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 已提交
3657
create_test_act_fp16_class(TestTan, grad_atol=0.85)
3658
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
3659
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
3660
create_test_act_fp16_class(TestSin)
3661
create_test_act_fp16_class(TestSinh)
3662 3663
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
X
xiaoting 已提交
3664 3665 3666
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 已提交
3667 3668
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
3669
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
3670 3671
create_test_act_fp16_class(TestBRelu)
create_test_act_fp16_class(TestRelu6)
3672
create_test_act_fp16_class(TestSoftRelu, grad_atol=0.85)
C
chengduo 已提交
3673
create_test_act_fp16_class(TestELU)
3674
create_test_act_fp16_class(TestCELU)
C
chengduo 已提交
3675 3676
create_test_act_fp16_class(TestReciprocal)
create_test_act_fp16_class(TestLog)
3677 3678 3679 3680
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 已提交
3681
create_test_act_fp16_class(TestLog10, atol=5e-2)
3682
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
3683 3684
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
3685
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
3686 3687 3688 3689 3690
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)
3691
create_test_act_fp16_class(TestSwish, grad_atol=0.85)
H
huangjun12 已提交
3692
create_test_act_fp16_class(TestHardSwish)
3693
create_test_act_fp16_class(TestMish, grad_atol=0.9)
A
Abhinav Arora 已提交
3694

3695

3696 3697 3698 3699 3700 3701
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"
    )
3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
    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)
3712 3713 3714
            self.check_grad_with_place(
                place, ['X'], 'Out', max_relative_error=grad_atol
            )
3715 3716 3717 3718 3719 3720 3721

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


create_test_act_bf16_class(TestRelu)
3722
create_test_act_bf16_class(TestAbs)
3723

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