test_activation_op.py 132.8 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import os
Q
qijun 已提交
16
import unittest
17
import warnings
J
joejiong 已提交
18

Q
qijun 已提交
19
import numpy as np
W
wanghuancoder 已提交
20
from eager_op_test import OpTest, convert_float_to_uint16, paddle_static_guard
21 22
from scipy.special import erf, expit

23
import paddle
24
import paddle.nn.functional as F
25 26
from paddle import fluid, static
from paddle.fluid import Program, core, program_guard
27
from paddle.fluid.layer_helper import LayerHelper
Q
qijun 已提交
28 29


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

                in3 = paddle.static.data(
                    name='input3', shape=[-1, 12, 10], dtype="float16"
                )
                paddle.sqrt(x=in3)
Z
Zhaolong Xing 已提交
47 48


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

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

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

66 67
        self.convert_input_output()

Q
qijun 已提交
68
    def test_check_output(self):
W
wanghuancoder 已提交
69
        self.check_output()
Q
qijun 已提交
70 71

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

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

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

85 86 87
    def init_kernel_type(self):
        pass

88 89 90
    def convert_input_output(self):
        pass

Q
qijun 已提交
91

92 93 94 95 96
class TestActivation_ZeroDim(TestActivation):
    def init_shape(self):
        self.shape = []


97
class TestExpFp32_Prim(OpTest):
98 99 100 101 102 103
    def setUp(self):
        self.op_type = "exp"
        self.prim_op_type = "prim"
        self.init_dtype()
        self.init_shape()
        self.python_api = paddle.exp
104
        self.public_python_api = paddle.exp
105 106 107 108 109 110 111

        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}
112
        self.if_enable_cinn()
113 114 115 116 117 118 119 120 121 122 123 124 125

    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]

126
    def if_enable_cinn(self):
127
        self.enable_cinn = True
128 129


130
class TestExpFp64_Prim(TestExpFp32_Prim):
131 132 133 134
    def init_dtype(self):
        self.dtype = np.float64


135
class TestExpPrim_ZeroDim(TestExpFp32_Prim):
136 137 138
    def init_shape(self):
        self.shape = []

139
    def if_enable_cinn(self):
140 141 142
        self.enable_cinn = False


R
ronnywang 已提交
143 144 145
class TestExpm1(TestActivation):
    def setUp(self):
        self.op_type = "expm1"
146
        self.python_api = paddle.expm1
R
ronnywang 已提交
147
        self.init_dtype()
148
        self.init_shape()
R
ronnywang 已提交
149 150

        np.random.seed(2049)
151
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
R
ronnywang 已提交
152 153 154 155
        out = np.expm1(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
156
        self.convert_input_output()
R
ronnywang 已提交
157 158

    def test_check_grad(self):
W
wanghuancoder 已提交
159
        self.check_grad(['X'], 'Out')
160 161

    def test_check_output(self):
W
wanghuancoder 已提交
162
        self.check_output()
R
ronnywang 已提交
163 164


165 166 167 168 169
class TestExpm1_ZeroDim(TestExpm1):
    def init_shape(self):
        self.shape = []


R
ronnywang 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
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):
        def run(place):
W
wanghuancoder 已提交
186 187
            with paddle_static_guard():
                with paddle.static.program_guard(paddle.static.Program()):
188
                    X = paddle.static.data('X', self.shape, dtype=self.dtype)
W
wanghuancoder 已提交
189 190 191
                    out = paddle.expm1(X)
                    exe = paddle.static.Executor(place)
                    res = exe.run(feed={'X': self.x})
R
ronnywang 已提交
192
            for r in res:
193
                np.testing.assert_allclose(self.out_ref, r, rtol=1e-05)
R
ronnywang 已提交
194 195 196 197 198 199 200 201

        for place in self.place:
            run(place)

    def test_dygraph_api(self):
        def run(place):
            X = paddle.to_tensor(self.x)
            out = paddle.expm1(X)
202
            np.testing.assert_allclose(self.out_ref, out.numpy(), rtol=1e-05)
R
ronnywang 已提交
203 204 205 206 207

        for place in self.place:
            run(place)

    def test_errors(self):
W
wanghuancoder 已提交
208 209
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
210
                X = paddle.static.data('X', self.shape, dtype='int32')
W
wanghuancoder 已提交
211
                self.assertRaises(TypeError, paddle.expm1, X)
R
ronnywang 已提交
212 213 214
        # The input dtype must be float16, float32, float64.


215
class TestParameter:
216
    def test_out_name(self):
W
wanghuancoder 已提交
217 218 219 220 221 222 223 224 225 226 227 228
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
                np_x = np.array([0.1]).astype('float32').reshape((-1, 1))
                data = paddle.static.data(
                    name="X", shape=[-1, 1], dtype="float32"
                )
                out = eval("paddle.%s(data, name='Y')" % self.op_type)
                place = fluid.CPUPlace()
                exe = fluid.Executor(place)
                (result,) = exe.run(feed={"X": np_x}, fetch_list=[out])
                expected = eval("np.%s(np_x)" % self.op_type)
                np.testing.assert_allclose(result, expected, rtol=1e-05)
229 230 231 232 233 234 235

    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)
236
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
237 238


C
chengduo 已提交
239
class TestSigmoid(TestActivation):
Q
qijun 已提交
240 241
    def setUp(self):
        self.op_type = "sigmoid"
Z
zxcd 已提交
242 243 244
        self.prim_op_type = "comp"
        self.enable_cinn = False
        self.python_api = paddle.nn.functional.sigmoid
245
        self.public_python_api = paddle.nn.functional.sigmoid
246
        self.init_dtype()
247
        self.init_shape()
248

249
        np.random.seed(1024)
250
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
251 252 253 254
        out = 1 / (1 + np.exp(-x))

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

256 257
        self.convert_input_output()

258 259 260
    def init_dtype(self):
        self.dtype = np.float32

261
    def test_check_grad(self):
262 263
        if self.dtype == np.float16:
            return
Z
zxcd 已提交
264
        self.check_grad(['X'], 'Out', max_relative_error=0.01, check_prim=True)
265

266

267 268 269 270 271
class TestSigmoid_ZeroDim(TestSigmoid):
    def init_shape(self):
        self.shape = []


272 273 274
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
275 276 277
class TestSigmoidBF16(OpTest):
    def setUp(self):
        self.op_type = "sigmoid"
Z
zxcd 已提交
278 279 280
        self.prim_op_type = "comp"
        self.enable_cinn = False
        self.python_api = paddle.nn.functional.sigmoid
281
        self.public_python_api = paddle.nn.functional.sigmoid
282
        self.init_dtype()
283
        self.init_shape()
284
        np.random.seed(1024)
285
        x = np.random.uniform(-1, 1, self.shape).astype(np.float32)
286 287 288 289 290 291 292 293 294 295
        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

296 297 298
    def init_shape(self):
        self.shape = [11, 17]

299 300
    def test_check_output(self):
        place = core.CUDAPlace(0)
301
        # elementwise_pow doesn't support bfloat16, skip check_prim here.
302 303 304 305 306 307 308
        self.check_output_with_place(place)

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


309 310 311 312 313 314 315 316
'''
class TestSigmoidBF16_ZeroDim(TestSigmoidBF16):

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


M
minghaoBD 已提交
317 318 319
class TestSilu(TestActivation):
    def setUp(self):
        self.op_type = "silu"
Z
zxcd 已提交
320
        self.prim_op_type = "comp"
321
        self.enable_cinn = True
Z
zxcd 已提交
322
        self.python_api = paddle.nn.functional.silu
323
        self.public_python_api = paddle.nn.functional.silu
M
minghaoBD 已提交
324
        self.init_dtype()
325
        self.init_shape()
326
        self.if_enable_cinn()
M
minghaoBD 已提交
327 328

        np.random.seed(1024)
329
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
M
minghaoBD 已提交
330
        out = x / (np.exp(-x) + 1)
331
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
M
minghaoBD 已提交
332 333
        self.outputs = {'Out': out}

334 335
        self.convert_input_output()

M
minghaoBD 已提交
336 337 338
    def init_dtype(self):
        self.dtype = np.float32

339
    def if_enable_cinn(self):
340 341
        pass

M
minghaoBD 已提交
342
    def test_check_grad(self):
Z
zxcd 已提交
343
        self.check_grad(['X'], 'Out', check_prim=True)
M
minghaoBD 已提交
344 345


346 347 348
class TestSilu_ZeroDim(TestSilu):
    def init_shape(self):
        self.shape = []
Z
zxcd 已提交
349

350
    def if_enable_cinn(self):
351
        self.enable_cinn = False
Z
zxcd 已提交
352 353


M
minghaoBD 已提交
354 355 356 357
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')
358 359 360
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
M
minghaoBD 已提交
361
            else paddle.CPUPlace()
362
        )
M
minghaoBD 已提交
363 364

    def test_static_api(self):
W
wanghuancoder 已提交
365 366
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
367
                x = paddle.static.data('X', [11, 17])
W
wanghuancoder 已提交
368 369 370 371 372 373 374 375
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
M
minghaoBD 已提交
376 377 378 379 380 381 382 383

    def test_dygraph_api(self):
        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]:
384
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
M
minghaoBD 已提交
385 386

    def test_errors(self):
W
wanghuancoder 已提交
387 388 389 390 391
        with paddle_static_guard():
            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.
392
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
393 394 395 396
                    name='x_int32', shape=[11, 17], dtype='int32'
                )
                self.assertRaises(TypeError, F.silu, x_int32)
                # support the input dtype is float16
397
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
398 399 400
                    name='x_fp16', shape=[11, 17], dtype='float16'
                )
                F.silu(x_fp16)
M
minghaoBD 已提交
401 402


C
chengduo 已提交
403
class TestLogSigmoid(TestActivation):
404 405
    def setUp(self):
        self.op_type = "logsigmoid"
W
wanghuancoder 已提交
406
        self.python_api = paddle.nn.functional.log_sigmoid
407
        self.init_dtype()
408
        self.init_shape()
409

410
        np.random.seed(2048)
411
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
412
        out = np.log(1 / (1 + np.exp(-x)))
413
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
414
        self.outputs = {'Out': out}
415

416 417
        self.convert_input_output()

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


424 425 426 427 428
class TestLogSigmoid_ZeroDim(TestLogSigmoid):
    def init_shape(self):
        self.shape = []


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

    def test_static_api(self):
W
wanghuancoder 已提交
441 442
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
443
                x = paddle.static.data('X', [11, 17])
W
wanghuancoder 已提交
444 445 446 447 448 449 450 451
                out1 = F.log_sigmoid(x)
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
452 453 454

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

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


479
class TestTanh(TestActivation, TestParameter):
480 481
    def setUp(self):
        self.op_type = "tanh"
482
        self.prim_op_type = "prim"
W
wanghuancoder 已提交
483
        self.python_api = paddle.tanh
484
        self.public_python_api = paddle.tanh
485
        self.init_dtype()
486
        self.init_shape()
487
        self.if_enable_cinn()
488

489
        np.random.seed(1024)
490
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
491 492 493
        out = np.tanh(x)
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
494
        self.convert_input_output()
495 496

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

501
    def init_dtype(self):
502
        # TODO If dtype is float64, the output (Out) has diff at CPUPlace
503 504 505 506
        # when using and not using inplace. Therefore, set dtype as float32
        # for now.
        self.dtype = np.float32

507 508 509
    def if_enable_cinn(self):
        pass

510

511 512 513 514
class TestTanh_ZeroDim(TestTanh):
    def init_shape(self):
        self.shape = []

515 516 517
    def if_enable_cinn(self):
        self.enable_cinn = False

518

W
WangXi 已提交
519 520 521 522
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
523
        np.random.seed(1024)
W
WangXi 已提交
524
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
525 526 527
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
W
WangXi 已提交
528
            else paddle.CPUPlace()
529
        )
530 531 532 533
        self.executed_api()

    def executed_api(self):
        self.tanh = F.tanh
W
WangXi 已提交
534 535

    def test_static_api(self):
W
wanghuancoder 已提交
536 537
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
538
                x = paddle.static.data('X', [10, 12], self.dtype)
W
wanghuancoder 已提交
539 540 541 542 543 544 545 546
                out1 = self.tanh(x)
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
W
WangXi 已提交
547 548

    def test_dygraph_api(self):
Z
Zhou Wei 已提交
549
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
550 551 552 553 554 555
        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]:
556
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
W
WangXi 已提交
557 558

    def test_errors(self):
W
wanghuancoder 已提交
559 560 561 562 563
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, self.tanh, 1)
                # The input dtype must be float16, float32.
564
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
565 566 567 568
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, self.tanh, x_int32)
                # support the input dtype is float16
569
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
570 571 572
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                self.tanh(x_fp16)
573 574 575 576 577 578


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


581
class TestAtan(TestActivation, TestParameter):
582 583
    def setUp(self):
        self.op_type = "atan"
W
wanghuancoder 已提交
584
        self.python_api = paddle.atan
585
        self.init_dtype()
586
        self.init_shape()
587

588
        np.random.seed(1024)
589
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
590 591 592 593
        out = np.arctan(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
594
        self.convert_input_output()
595 596 597 598

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

W
WuHaobo 已提交
601
    def test_out_name(self):
W
wanghuancoder 已提交
602 603 604 605 606 607 608 609 610 611 612 613
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
                np_x = np.array([0.1]).astype('float32').reshape((-1, 1))
                data = paddle.static.data(
                    name="X", shape=[-1, 1], dtype="float32"
                )
                out = paddle.atan(data, name='Y')
                place = fluid.CPUPlace()
                exe = fluid.Executor(place)
                (result,) = exe.run(feed={"X": np_x}, fetch_list=[out])
                expected = np.arctan(np_x)
                self.assertEqual(result, expected)
W
WuHaobo 已提交
614

615 616 617 618 619 620 621 622
    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)

623

624
class TestAtan_ZeroDim(TestAtan):
625 626 627 628
    def init_shape(self):
        self.shape = []


629 630 631
class TestSinh(TestActivation):
    def setUp(self):
        self.op_type = "sinh"
W
wanghuancoder 已提交
632
        self.python_api = paddle.sinh
633
        self.init_dtype()
634
        self.init_shape()
635

636
        np.random.seed(1024)
637
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
638 639 640 641
        out = np.sinh(x)
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

642 643
        self.convert_input_output()

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

649 650 651 652 653 654 655

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


class TestSinhAPI(unittest.TestCase):
656 657 658 659
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
660
            z = paddle.sinh(x).numpy()
661
            z_expected = np.sinh(np_x)
662
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
663 664

    def test_api(self):
W
wanghuancoder 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        with paddle_static_guard():
            test_data_shape = [11, 17]
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                    "float32"
                )
                data_x = paddle.static.data(
                    name="data_x",
                    shape=test_data_shape,
                    dtype="float32",
                )

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

            expected_res = np.sinh(input_x)
            np.testing.assert_allclose(np_sinh_res, expected_res, rtol=1e-05)
688 689 690 691

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
692 693 694
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
695 696
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
697
            loss = paddle.sinh(var)
698 699 700 701 702 703 704
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


class TestSinhOpError(unittest.TestCase):
    def test_errors(self):
W
wanghuancoder 已提交
705 706 707 708 709
        with paddle_static_guard():
            with program_guard(Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, paddle.sinh, 1)
                # The input dtype must be float16, float32, float64.
710
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
711 712 713 714
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, paddle.sinh, x_int32)
                # support the input dtype is float16
715
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
716 717 718
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                paddle.sinh(x_fp16)
719 720 721 722 723


class TestCosh(TestActivation):
    def setUp(self):
        self.op_type = "cosh"
W
wanghuancoder 已提交
724
        self.python_api = paddle.cosh
725
        self.init_dtype()
726
        self.init_shape()
727

728
        np.random.seed(1024)
729
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
730 731 732 733
        out = np.cosh(x)
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}

734 735
        self.convert_input_output()

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

741 742 743 744 745 746 747

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


class TestCoshAPI(unittest.TestCase):
748 749 750 751
    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
752
            z = paddle.cosh(x).numpy()
753
            z_expected = np.cosh(np_x)
754
            np.testing.assert_allclose(z, z_expected, rtol=1e-05)
755 756

    def test_api(self):
W
wanghuancoder 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        with paddle_static_guard():
            test_data_shape = [11, 17]
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                    "float32"
                )
                data_x = paddle.static.data(
                    name="data_x",
                    shape=test_data_shape,
                    dtype="float32",
                )

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

            expected_res = np.cosh(input_x)
            np.testing.assert_allclose(np_cosh_res, expected_res, rtol=1e-05)
780 781 782 783

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
784 785 786
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
787 788
            var = fluid.dygraph.to_variable(input_x)
            var.stop_gradient = False
789
            loss = paddle.cosh(var)
790 791 792 793 794 795 796
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


class TestCoshOpError(unittest.TestCase):
    def test_errors(self):
W
wanghuancoder 已提交
797 798 799 800 801
        with paddle_static_guard():
            with program_guard(Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, paddle.cosh, 1)
                # The input dtype must be float16, float32, float64.
802
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
803 804 805 806
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, paddle.cosh, x_int32)
                # support the input dtype is float16
807
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
808 809 810
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                paddle.cosh(x_fp16)
811 812


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


class TestTanhshrink(TestActivation):
K
Kavya Srinet 已提交
819 820
    def setUp(self):
        self.op_type = "tanh_shrink"
W
wanghuancoder 已提交
821
        self.python_api = paddle.nn.functional.tanhshrink
822
        self.init_dtype()
823
        self.init_shape()
824

825
        np.random.seed(1024)
826
        x = np.random.uniform(10, 20, self.shape).astype(self.dtype)
827
        out = ref_tanhshrink(x)
828
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
829
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
830

831 832
        self.convert_input_output()

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

838

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


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

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

    def test_dygraph_api(self):
        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]:
875
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
876 877

    def test_errors(self):
W
wanghuancoder 已提交
878 879 880 881 882
        with paddle_static_guard():
            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.
883
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
884 885 886 887
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.tanhshrink, x_int32)
                # support the input dtype is float16
888
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
889 890 891
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.tanhshrink(x_fp16)
892 893


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


C
chengduo 已提交
900
class TestHardShrink(TestActivation):
901 902
    def setUp(self):
        self.op_type = "hard_shrink"
W
wanghuancoder 已提交
903
        self.python_api = paddle.nn.functional.hardshrink
904
        self.init_dtype()
905
        self.init_shape()
906

907 908
        self.threshold = 0.5
        self.set_attrs()
909
        np.random.seed(1024)
910
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype) * 10
911
        out = ref_hardshrink(x, self.threshold)
912 913
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
914

915
        self.attrs = {'threshold': self.threshold}
916 917

        self.convert_input_output()
918

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

922 923 924
    def set_attrs(self):
        pass

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


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


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

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


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

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

    def test_dygraph_api(self):
Z
Zhou Wei 已提交
969
        x = paddle.to_tensor(self.x_np)
970 971 972 973 974
        out1 = F.hardshrink(x)
        hd = paddle.nn.Hardshrink()
        out2 = hd(x)
        out_ref = ref_hardshrink(self.x_np, 0.5)
        for r in [out1, out2]:
975
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
976 977 978 979 980 981

        out1 = F.hardshrink(x, 0.6)
        hd = paddle.nn.Hardshrink(0.6)
        out2 = hd(x)
        out_ref = ref_hardshrink(self.x_np, 0.6)
        for r in [out1, out2]:
982
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
983

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


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

    def test_static_api(self):
W
wanghuancoder 已提交
1021 1022
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
1023
                x = paddle.static.data('X', [10, 12], dtype="float32")
W
wanghuancoder 已提交
1024 1025 1026 1027 1028 1029 1030 1031
                out1 = F.hardtanh(x)
                m = paddle.nn.Hardtanh()
                out2 = m(x)
                exe = paddle.static.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
            out_ref = ref_hardtanh(self.x_np)
            for r in res:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1032 1033

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

        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]:
1047
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1048 1049

    def test_errors(self):
W
wanghuancoder 已提交
1050 1051 1052 1053 1054
        with paddle_static_guard():
            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.
1055
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
1056 1057 1058 1059
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.hardtanh, x_int32)
                # support the input dtype is float16
1060
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
1061 1062 1063
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.hardtanh(x_fp16)
1064 1065


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


class TestSoftshrink(TestActivation):
1075 1076
    def setUp(self):
        self.op_type = "softshrink"
1077
        self.python_api = paddle.nn.functional.softshrink
1078
        self.init_dtype()
1079
        self.init_shape()
1080

1081
        threshold = 0.8
1082

1083
        np.random.seed(1023)
1084
        x = np.random.uniform(0.25, 10, self.shape).astype(self.dtype)
1085
        out = ref_softshrink(x, threshold)
1086 1087

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

1090 1091
        self.attrs = {"lambda": threshold}

1092
    def test_check_grad(self):
1093 1094
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
1095
        self.check_grad(['X'], 'Out')
1096

1097

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


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

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

    def test_dygraph_api(self):
        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]:
1135
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1136

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


1159
class TestSqrt(TestActivation, TestParameter):
1160 1161
    def setUp(self):
        self.op_type = "sqrt"
1162
        self.prim_op_type = "prim"
1163
        self.python_api = paddle.sqrt
1164 1165
        self.public_python_api = paddle.sqrt

1166
        self.init_dtype()
1167
        self.init_shape()
1168

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

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

1178
    # TODO(wanghao107) add prim test
1179
    def test_check_grad(self):
1180 1181
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
1182
        self.check_grad(['X'], 'Out')
1183 1184

    def test_check_output(self):
W
wanghuancoder 已提交
1185
        self.check_output()
1186

1187

1188 1189 1190 1191 1192
class TestSqrtPrimFp32(TestActivation):
    def setUp(self):
        self.op_type = "sqrt"
        self.prim_op_type = "prim"
        self.python_api = paddle.sqrt
1193
        self.public_python_api = paddle.sqrt
1194 1195 1196 1197 1198 1199 1200 1201
        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}
1202
        self.enable_cinn = True
1203 1204 1205 1206

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
1207
        self.check_grad(['X'], 'Out', check_prim=True)
1208 1209

    def test_check_output(self):
W
wanghuancoder 已提交
1210
        self.check_output()
1211 1212 1213 1214 1215

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


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


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

    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)


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

        np.random.seed(1023)
1249
        x = np.random.uniform(0.1, 1, self.shape).astype(np.float32)
1250 1251 1252 1253 1254 1255
        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)}
1256
        self.enable_cinn = False
1257 1258 1259 1260

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

1261 1262 1263
    def init_shape(self):
        self.shape = [11, 17]

1264 1265
    def test_check_output(self):
        place = core.CUDAPlace(0)
W
wanghuancoder 已提交
1266
        self.check_output_with_place(place)
1267 1268 1269

    def test_check_grad(self):
        place = core.CUDAPlace(0)
W
wanghuancoder 已提交
1270
        self.check_grad_with_place(place, ['X'], 'Out', check_prim=True)
1271 1272


M
mhy-666 已提交
1273 1274 1275 1276 1277
class TestSqrtComp(TestActivation, TestParameter):
    def setUp(self):
        self.op_type = "sqrt"
        self.prim_op_type = "comp"
        self.python_api = paddle.sqrt
1278
        self.public_python_api = paddle.sqrt
M
mhy-666 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287
        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}
1288
        self.convert_input_output()
M
mhy-666 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        self.enable_cinn = True

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

    def test_check_output(self):
        self.check_output(check_dygraph=True, check_prim=True)


class TestSqrtCompFp32(TestActivation):
    def setUp(self):
        self.op_type = "sqrt"
        self.prim_op_type = "comp"
        self.python_api = paddle.sqrt
1305
        self.public_python_api = paddle.sqrt
M
mhy-666 已提交
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
        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 = True

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

    def test_check_output(self):
        self.check_output(check_dygraph=True, check_prim=True)

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


Z
zhoukunsheng 已提交
1328 1329 1330
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
1331
        self.prim_op_type = "comp"
Z
zyfncg 已提交
1332
        self.python_api = paddle.rsqrt
1333
        self.public_python_api = paddle.rsqrt
Z
zhoukunsheng 已提交
1334
        self.init_dtype()
1335
        self.init_shape()
Z
zhoukunsheng 已提交
1336

1337
        np.random.seed(1024)
1338
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
1339 1340 1341 1342
        out = 1.0 / np.sqrt(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
1343
        self.convert_input_output()
1344
        self.enable_cinn = True
Z
zhoukunsheng 已提交
1345

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

1349 1350 1351
    def test_check_output(self):
        self.check_output(check_prim=True)

Z
zhoukunsheng 已提交
1352 1353 1354
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1355 1356 1357 1358 1359 1360
        self.check_grad(
            ['X'],
            'Out',
            max_relative_error=0.0005,
            check_prim=True,
        )
Z
zhoukunsheng 已提交
1361 1362


1363 1364 1365 1366 1367 1368 1369 1370
'''
class TestRsqrt_ZeroDim(TestRsqrt):

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


C
chengduo 已提交
1371
class TestAbs(TestActivation):
1372 1373
    def setUp(self):
        self.op_type = "abs"
1374 1375
        self.prim_op_type = "prim"
        self.python_api = paddle.abs
1376
        self.public_python_api = paddle.abs
1377
        self.enable_cinn = False
1378
        self.init_dtype()
1379
        self.init_shape()
1380

1381
        np.random.seed(1024)
1382
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
C
chengduo 已提交
1383
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
1384
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
1385
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
1386 1387
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
1388 1389 1390 1391
        out = np.abs(x)

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

1394 1395 1396
    def init_shape(self):
        self.shape = [4, 25]

1397
    def test_check_grad(self):
1398 1399
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
1400
        self.check_grad(['X'], 'Out', check_prim=True)
1401

1402

1403 1404 1405 1406 1407
class TestAbs_ZeroDim(TestAbs):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1408
class TestCeil(TestActivation):
D
dzhwinter 已提交
1409 1410
    def setUp(self):
        self.op_type = "ceil"
1411
        self.python_api = paddle.ceil
1412
        self.init_dtype()
1413
        self.init_shape()
1414

1415
        np.random.seed(1024)
1416
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1417 1418 1419 1420
        out = np.ceil(x)

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

1423 1424 1425
    def init_shape(self):
        self.shape = [10, 12]

D
dzhwinter 已提交
1426
    # The same reason with TestFloor
C
chengduo 已提交
1427
    def test_check_grad(self):
1428 1429 1430
        pass


1431 1432 1433 1434 1435
class TestCeil_ZeroDim(TestCeil):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1436
class TestFloor(TestActivation):
D
dzhwinter 已提交
1437 1438
    def setUp(self):
        self.op_type = "floor"
1439
        self.prim_op_type = "prim"
1440
        self.python_api = paddle.floor
1441
        self.public_python_api = paddle.floor
1442
        self.init_dtype()
1443
        self.init_shape()
1444

1445
        np.random.seed(1024)
1446
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1447 1448 1449 1450
        out = np.floor(x)

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

1453 1454 1455
    def init_shape(self):
        self.shape = [10, 12]

D
dzhwinter 已提交
1456
    # the gradient on floor, ceil, round is undefined.
1457
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
1458 1459
    # The same reason with TestFloor
    def test_check_grad(self):
1460 1461 1462
        pass


1463 1464 1465 1466 1467
class TestFloor_ZeroDim(TestFloor):
    def init_shape(self):
        self.shape = []


1468
class TestFloor_Prim(TestActivation):
1469 1470 1471 1472
    def setUp(self):
        self.op_type = "floor"
        self.prim_op_type = "prim"
        self.python_api = paddle.floor
1473
        self.public_python_api = paddle.floor
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        self.init_dtype()
        self.init_shape()

        if len(self.shape) == 0:
            # for 0-D tensor, skip cinn testing
            self.enable_cinn = False

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

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

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

    def test_check_grad(self):
1492 1493 1494 1495 1496
        # the gradient on floor, ceil, round is undefined.
        # we return zero as gradient, but the numpy return nan.
        # for prim, we compare result with eager python api,
        # so, we use only_prim flag to express we only test prim.
        self.check_grad(['X'], 'Out', check_prim=True, only_check_prim=True)
1497 1498


1499
class TestFloor_ZeroDim_Prim(TestFloor_Prim):
1500 1501 1502 1503
    def init_shape(self):
        self.shape = []


1504
class TestFloorFp16_Prim(TestFloor_Prim):
1505 1506 1507 1508
    def init_dtype(self):
        self.dtype = np.float16


C
chengduo 已提交
1509
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
1510 1511
    def setUp(self):
        self.op_type = "cos"
W
wanghuancoder 已提交
1512
        self.python_api = paddle.cos
1513 1514
        self.public_python_api = paddle.cos
        self.prim_op_type = "prim"
1515
        self.init_dtype()
1516
        self.init_shape()
1517 1518
        # prim not support now
        self.enable_cinn = False
1519

1520
        np.random.seed(1024)
1521
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1522 1523 1524
        out = np.cos(x)
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
1525
        self.convert_input_output()
C
add sin  
chengduoZH 已提交
1526

1527 1528 1529
    def init_shape(self):
        self.shape = [10, 12]

C
add sin  
chengduoZH 已提交
1530
    def test_check_grad(self):
1531 1532
        if self.dtype == np.float16:
            return
1533
        self.check_grad(['X'], 'Out', check_prim=True)
C
add sin  
chengduoZH 已提交
1534

1535

1536 1537 1538 1539 1540
class TestCos_ZeroDim(TestCos):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
1541 1542 1543 1544
class TestTan(TestActivation):
    def setUp(self):
        np.random.seed(1024)
        self.op_type = "tan"
W
wanghuancoder 已提交
1545
        self.python_api = paddle.tan
J
joejiong 已提交
1546
        self.init_dtype()
1547 1548
        self.init_shape()

J
joejiong 已提交
1549
        self.dtype = 'float32'
1550
        self.x_np = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1551 1552 1553
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
J
joejiong 已提交
1554
            else paddle.CPUPlace()
1555
        )
J
joejiong 已提交
1556 1557 1558 1559 1560

        out = np.tan(self.x_np)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(self.x_np)}
        self.outputs = {'Out': out}
1561
        self.convert_input_output()
J
joejiong 已提交
1562

1563 1564 1565
    def init_shape(self):
        self.shape = [10, 12]

J
joejiong 已提交
1566 1567 1568 1569 1570
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581

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)
1582 1583 1584
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1585
            else paddle.CPUPlace()
1586
        )
1587

J
joejiong 已提交
1588 1589 1590 1591
    def test_dygraph_api(self):
        x = paddle.to_tensor(self.x_np)
        out_test = paddle.tan(x)
        out_ref = np.tan(self.x_np)
1592
        np.testing.assert_allclose(out_ref, out_test.numpy(), rtol=1e-05)
J
joejiong 已提交
1593 1594

    def test_static_api(self):
W
wanghuancoder 已提交
1595 1596 1597 1598 1599 1600 1601 1602
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                x = paddle.static.data('X', [11, 17], self.dtype)
                out = paddle.tan(x)
                exe = paddle.static.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = np.tan(self.x_np)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
J
joejiong 已提交
1603 1604 1605 1606

    def test_backward(self):
        test_data_shape = [11, 17]
        with fluid.dygraph.guard():
1607 1608 1609
            input_x = np.random.uniform(0.1, 1, test_data_shape).astype(
                "float32"
            )
J
joejiong 已提交
1610 1611 1612 1613 1614 1615 1616 1617
            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)


1618 1619 1620
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
W
wanghuancoder 已提交
1621
        self.python_api = paddle.acos
1622
        self.init_dtype()
1623
        self.init_shape()
1624

1625
        np.random.seed(1024)
1626
        x = np.random.uniform(-0.95, 0.95, self.shape).astype(self.dtype)
1627 1628 1629 1630
        out = np.arccos(x)

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

1633 1634 1635
    def init_shape(self):
        self.shape = [10, 12]

1636 1637 1638
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1639
        self.check_grad(['X'], 'Out')
1640 1641


1642 1643 1644 1645 1646
class TestAcos_ZeroDim(TestAcos):
    def init_shape(self):
        self.shape = []


1647
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
1648 1649
    def setUp(self):
        self.op_type = "sin"
W
wanghuancoder 已提交
1650
        self.python_api = paddle.sin
1651 1652
        self.public_python_api = paddle.sin
        self.prim_op_type = "prim"
1653
        self.init_dtype()
1654
        self.init_shape()
1655 1656
        # prim not support now
        self.enable_cinn = False
1657

1658
        np.random.seed(1024)
1659
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1660 1661 1662
        out = np.sin(x)
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
1663
        self.convert_input_output()
C
add cos  
chengduoZH 已提交
1664

1665 1666 1667
    def init_shape(self):
        self.shape = [10, 12]

C
add cos  
chengduoZH 已提交
1668
    def test_check_grad(self):
1669 1670
        if self.dtype == np.float16:
            return
1671
        self.check_grad(['X'], 'Out', check_prim=True)
C
add cos  
chengduoZH 已提交
1672 1673


1674 1675 1676 1677 1678
class TestSin_ZeroDim(TestSin):
    def init_shape(self):
        self.shape = []


1679 1680 1681
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
W
wanghuancoder 已提交
1682
        self.python_api = paddle.asin
1683
        self.init_dtype()
1684
        self.init_shape()
1685

1686
        np.random.seed(2048)
1687
        x = np.random.uniform(-0.95, 0.95, self.shape).astype(self.dtype)
1688 1689 1690 1691
        out = np.arcsin(x)

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

1694 1695 1696
    def init_shape(self):
        self.shape = [10, 12]

1697 1698 1699
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1700
        self.check_grad(['X'], 'Out')
1701 1702


1703 1704 1705 1706 1707
class TestAsin_ZeroDim(TestAsin):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1708 1709 1710
class TestAcosh(TestActivation):
    def setUp(self):
        self.op_type = "acosh"
W
wanghuancoder 已提交
1711
        self.python_api = paddle.acosh
X
xiaoting 已提交
1712
        self.init_dtype()
1713
        self.init_shape()
X
xiaoting 已提交
1714 1715

        np.random.seed(1024)
1716
        x = np.random.uniform(2, 3, self.shape).astype(self.dtype)
X
xiaoting 已提交
1717 1718 1719 1720
        out = np.arccosh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
1721
        self.convert_input_output()
X
xiaoting 已提交
1722

1723 1724 1725
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1726 1727 1728 1729 1730 1731
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1732 1733 1734 1735 1736
class TestAcosh_ZeroDim(TestAcosh):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1737 1738 1739
class TestAsinh(TestActivation):
    def setUp(self):
        self.op_type = "asinh"
W
wanghuancoder 已提交
1740
        self.python_api = paddle.asinh
X
xiaoting 已提交
1741
        self.init_dtype()
1742
        self.init_shape()
X
xiaoting 已提交
1743 1744

        np.random.seed(1024)
1745
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
X
xiaoting 已提交
1746 1747 1748 1749
        out = np.arcsinh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
1750
        self.convert_input_output()
X
xiaoting 已提交
1751

1752 1753 1754
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1755 1756 1757 1758 1759 1760
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1761 1762 1763 1764 1765
class TestAsinh_ZeroDim(TestAsinh):
    def init_shape(self):
        self.shape = []


X
xiaoting 已提交
1766 1767 1768
class TestAtanh(TestActivation):
    def setUp(self):
        self.op_type = "atanh"
W
wanghuancoder 已提交
1769
        self.python_api = paddle.atanh
X
xiaoting 已提交
1770
        self.init_dtype()
1771
        self.init_shape()
X
xiaoting 已提交
1772 1773

        np.random.seed(400)
1774
        x = np.random.uniform(-0.9, 0.9, self.shape).astype(self.dtype)
X
xiaoting 已提交
1775 1776 1777 1778
        out = np.arctanh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
1779
        self.convert_input_output()
X
xiaoting 已提交
1780

1781 1782 1783
    def init_shape(self):
        self.shape = [10, 12]

X
xiaoting 已提交
1784 1785 1786 1787 1788 1789
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out')


1790 1791 1792 1793 1794
class TestAtanh_ZeroDim(TestAtanh):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1795
class TestRound(TestActivation):
D
dzhwinter 已提交
1796 1797
    def setUp(self):
        self.op_type = "round"
1798
        self.python_api = paddle.round
1799
        self.init_dtype()
1800
        self.init_shape()
1801

1802
        np.random.seed(1024)
1803
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
1804 1805 1806 1807
        out = np.round(x)

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

1810 1811 1812
    def init_shape(self):
        self.shape = [10, 12]

C
chengduo 已提交
1813
    def test_check_grad(self):
1814 1815 1816
        pass


1817 1818 1819 1820 1821
class TestRound_ZeroDim(TestRound):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
1822
class TestRelu(TestActivation):
1823
    def setUp(self):
Q
qijun 已提交
1824
        self.op_type = "relu"
K
Kang Zhao 已提交
1825 1826
        self.python_api = paddle.nn.functional.relu
        self.prim_op_type = "comp"
1827
        self.public_python_api = paddle.nn.functional.relu
K
Kexin Zhao 已提交
1828
        self.init_dtype()
1829
        self.init_shape()
K
Kang Zhao 已提交
1830
        self.skip_cinn()
K
Kexin Zhao 已提交
1831

1832
        np.random.seed(1024)
1833 1834 1835 1836 1837
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.02
        out = np.maximum(x, 0)
        self.inputs = {'X': x}
K
Kexin Zhao 已提交
1838 1839

        self.outputs = {'Out': out}
1840
        self.convert_input_output()
1841 1842

    def test_check_grad(self):
K
Kexin Zhao 已提交
1843 1844
        if self.dtype == np.float16:
            return
K
Kang Zhao 已提交
1845 1846 1847 1848 1849 1850 1851
        self.check_grad(['X'], 'Out', check_prim=True)

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

    def skip_cinn(self):
        self.enable_cinn = False
A
Adam 已提交
1852 1853


1854 1855 1856 1857
class TestRelu_ZeroDim(TestRelu):
    def init_shape(self):
        self.shape = []

K
Kang Zhao 已提交
1858 1859 1860
    def skip_cinn(self):
        self.enable_cinn = False

1861

1862 1863 1864
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1865
        np.random.seed(1024)
1866
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
1867 1868 1869
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
1870
            else paddle.CPUPlace()
1871
        )
1872 1873 1874 1875
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1876 1877

    def test_static_api(self):
W
wanghuancoder 已提交
1878 1879
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
1880
                x = paddle.static.data('X', [10, 12], dtype="float32")
W
wanghuancoder 已提交
1881 1882 1883 1884 1885 1886 1887 1888
                out1 = self.relu(x)
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
1889 1890 1891 1892

    def test_dygraph_api(self):
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.ReLU()
1893 1894
        out1 = m(x)
        out2 = self.relu(x)
1895 1896
        out_ref = np.maximum(self.x_np, 0)
        for r in [out1, out2]:
1897
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
1898

1899
    def test_errors(self):
W
wanghuancoder 已提交
1900 1901 1902 1903 1904 1905
        with paddle_static_guard():
            with paddle_static_guard():
                with paddle.static.program_guard(paddle.static.Program()):
                    # The input type must be Variable.
                    self.assertRaises(TypeError, self.relu, 1)
                    # The input dtype must be float16, float32, float64.
1906
                    x_int32 = paddle.static.data(
W
wanghuancoder 已提交
1907 1908 1909 1910
                        name='x_int32', shape=[10, 12], dtype='int32'
                    )
                    self.assertRaises(TypeError, self.relu, x_int32)
                    # support the input dtype is float16
1911
                    x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
1912 1913 1914
                        name='x_fp16', shape=[10, 12], dtype='float16'
                    )
                    self.relu(x_fp16)
1915 1916 1917 1918 1919 1920


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


1923 1924 1925 1926 1927 1928
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1929
class TestLeakyRelu(TestActivation):
1930 1931 1932
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1933 1934
    def setUp(self):
        self.op_type = "leaky_relu"
W
wanghuancoder 已提交
1935
        self.python_api = paddle.nn.functional.leaky_relu
1936 1937
        self.public_python_api = paddle.nn.functional.leaky_relu
        self.prim_op_type = "comp"
A
Adam 已提交
1938
        self.init_dtype()
1939
        self.init_shape()
1940
        alpha = self.get_alpha()
A
Adam 已提交
1941

1942
        np.random.seed(1024)
1943
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
A
Adam 已提交
1944
        # The same reason with TestAbs
1945 1946
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1947

1948
        self.inputs = {'X': x}
A
Adam 已提交
1949
        self.outputs = {'Out': out}
1950
        self.attrs = {'alpha': alpha}
1951
        self.convert_input_output()
A
Adam 已提交
1952

1953 1954 1955
    def test_check_output(self):
        self.check_output(check_prim=True)

A
Adam 已提交
1956 1957 1958
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1959
        self.check_grad(['X'], 'Out', check_prim=True)
1960 1961


1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
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


1977 1978 1979 1980
class TestLeakyRelu_ZeroDim(TestLeakyRelu):
    def init_shape(self):
        self.shape = []

1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
    def setUp(self):
        self.op_type = "leaky_relu"
        self.prim_op_type = "comp"
        self.enable_cinn = False
        self.python_api = paddle.nn.functional.leaky_relu
        self.public_python_api = paddle.nn.functional.relu
        self.init_dtype()
        self.init_shape()
        alpha = self.get_alpha()

        np.random.seed(1024)
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)

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

2001

2002 2003 2004
class TestLeakyReluAPI(unittest.TestCase):
    # test paddle.nn.LeakyReLU, paddle.nn.functional.leaky_relu,
    def setUp(self):
2005
        np.random.seed(1024)
2006
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
2007 2008 2009
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2010
            else paddle.CPUPlace()
2011
        )
2012 2013

    def test_static_api(self):
W
wanghuancoder 已提交
2014 2015
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
2016
                x = paddle.static.data('X', [10, 12], dtype="float32")
W
wanghuancoder 已提交
2017 2018 2019 2020 2021 2022 2023 2024
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2025 2026

    def test_dygraph_api(self):
Z
Zhou Wei 已提交
2027
        x = paddle.to_tensor(self.x_np)
2028 2029 2030 2031 2032
        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]:
2033
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2034 2035 2036 2037 2038 2039

        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]:
2040
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2041

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


2059 2060
def gelu(x, approximate):
    if approximate:
2061 2062 2063 2064 2065 2066 2067 2068
        y_ref = (
            0.5
            * x
            * (
                1.0
                + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))
            )
        )
2069 2070 2071 2072 2073 2074
    else:
        y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
    return y_ref.astype(x.dtype)


class TestGeluApproximate(TestActivation):
C
Clementine 已提交
2075 2076
    def setUp(self):
        self.op_type = "gelu"
2077 2078
        self.prim_op_type = "comp"
        self.python_api = paddle.nn.functional.gelu
2079
        self.public_python_api = paddle.nn.functional.gelu
C
Clementine 已提交
2080
        self.init_dtype()
2081
        self.init_shape()
2082
        approximate = True
2083
        np.random.seed(1024)
2084
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
2085
        out = gelu(x, approximate)
C
Clementine 已提交
2086

2087
        self.inputs = {'X': x}
2088 2089 2090
        self.outputs = {'Out': out}
        self.attrs = {"approximate": approximate}

2091 2092 2093 2094
        # The backward decomposite of gelu is inconsistent with raw kernel on
        # cpu device, lower threshold to support 1e-8 for pass the unittest
        self.rev_comp_rtol = 1e-8
        self.rev_comp_atol = 1e-8
2095 2096 2097
        # Cumulative error occurs between comp and cinn, so that we also set cinn_rtol to 1e-8 as rev_comp_rtol = 1e-8
        self.cinn_rtol = 1e-8
        self.cinn_atol = 1e-8
C
cxxly 已提交
2098

2099 2100 2101
    def test_check_output(self):
        self.check_output(check_prim=True)

2102 2103 2104
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
2105
        self.check_grad(['X'], 'Out', check_prim=True)
2106 2107 2108 2109 2110


class TestGelu(TestActivation):
    def setUp(self):
        self.op_type = "gelu"
2111 2112
        self.prim_op_type = "comp"
        self.python_api = paddle.nn.functional.gelu
2113
        self.public_python_api = paddle.nn.functional.gelu
2114
        self.init_dtype()
2115
        self.init_shape()
2116
        approximate = False
2117
        np.random.seed(2048)
2118
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
2119
        out = gelu(x, approximate)
2120
        self.if_enable_cinn()
C
Clementine 已提交
2121

2122
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
C
Clementine 已提交
2123
        self.outputs = {'Out': out}
2124
        self.convert_input_output()
2125
        self.attrs = {"approximate": approximate}
2126 2127 2128 2129
        # The backward decomposite of gelu is inconsistent with raw kernel on
        # cpu, lower threshold to support 1e-8 for pass the unittest
        self.rev_comp_rtol = 1e-8
        self.rev_comp_atol = 1e-8
2130 2131 2132
        # Cumulative error occurs between comp and cinn, so that we also set cinn_rtol to 1e-8 as rev_comp_rtol = 1e-8
        self.cinn_rtol = 1e-8
        self.cinn_atol = 1e-8
C
Clementine 已提交
2133

2134
    def if_enable_cinn(self):
2135
        pass
2136 2137 2138 2139

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

C
Clementine 已提交
2140 2141 2142
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
2143
        self.check_grad(['X'], 'Out', check_prim=True)
C
Clementine 已提交
2144 2145


2146 2147 2148 2149
class TestGelu_ZeroDim(TestGelu):
    def init_shape(self):
        self.shape = []

2150 2151 2152
    def if_enable_cinn(self):
        self.enable_cinn = False

2153

2154 2155 2156
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
2157
        np.random.seed(1024)
2158
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
2159 2160 2161
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2162
            else paddle.CPUPlace()
2163
        )
C
cxxly 已提交
2164 2165
        self.enable_cinn = False

2166 2167 2168 2169
        # The backward decomposite of gelu is inconsistent with raw kernel on
        # cpu, lower threshold to support 1e-8 for pass the unittest
        self.rev_comp_rtol = 1e-8
        self.rev_comp_atol = 1e-8
2170 2171

    def test_static_api(self):
W
wanghuancoder 已提交
2172 2173
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
2174
                x = paddle.static.data('X', [11, 17], dtype="float32")
W
wanghuancoder 已提交
2175 2176 2177 2178 2179 2180 2181 2182
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2183 2184 2185 2186 2187 2188 2189 2190

    def test_dygraph_api(self):
        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]:
2191
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2192 2193 2194 2195 2196 2197

        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]:
2198
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2199 2200

    def test_errors(self):
W
wanghuancoder 已提交
2201 2202 2203 2204 2205
        with paddle_static_guard():
            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.
2206
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
2207 2208 2209 2210
                    name='x_int32', shape=[11, 17], dtype='int32'
                )
                self.assertRaises(TypeError, F.gelu, x_int32)
                # support the input dtype is float16
2211
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
2212 2213 2214
                    name='x_fp16', shape=[11, 17], dtype='float16'
                )
                F.gelu(x_fp16)
2215 2216


C
chengduo 已提交
2217
class TestBRelu(TestActivation):
2218 2219
    def setUp(self):
        self.op_type = "brelu"
W
wanghuancoder 已提交
2220
        self.python_api = paddle.nn.functional.hardtanh
2221 2222
        self.init_dtype()

2223
        np.random.seed(1024)
Z
zhupengyang 已提交
2224
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
2225 2226
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
2227 2228
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
2229
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
2230 2231 2232
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
2233 2234

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
F
fengjiayi 已提交
2235
        self.outputs = {'Out': t}
2236 2237
        self.convert_input_output()
        self.attrs = {'t_min': t_min, 't_max': t_max}
2238 2239

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

2244

2245 2246 2247 2248 2249 2250 2251
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 已提交
2252
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
2253
    def setUp(self):
2254
        self.op_type = "relu6"
2255
        self.init_dtype()
2256
        self.init_shape()
2257
        self.python_api = paddle.nn.functional.relu6
2258

2259
        np.random.seed(1024)
2260
        x = np.random.uniform(-1, 10, self.shape).astype(self.dtype)
2261
        x[np.abs(x) < 0.005] = 0.02
2262
        out = ref_relu6(x)
2263

2264
        self.attrs = {'threshold': 6.0}
2265 2266

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
2267
        self.outputs = {'Out': out}
2268
        self.convert_input_output()
K
Kavya Srinet 已提交
2269

2270 2271 2272
    def init_shape(self):
        self.shape = [10, 12]

2273 2274 2275
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2276
        self.check_grad(['X'], 'Out')
2277 2278


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


2284 2285 2286
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
2287
        np.random.seed(1024)
2288 2289
        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
2290 2291 2292
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2293
            else paddle.CPUPlace()
2294
        )
2295 2296

    def test_static_api(self):
W
wanghuancoder 已提交
2297 2298
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
2299
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
2300 2301 2302 2303 2304 2305 2306 2307
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2308 2309 2310 2311 2312 2313 2314 2315

    def test_dygraph_api(self):
        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]:
2316
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2317 2318

    def test_fluid_api(self):
W
wanghuancoder 已提交
2319 2320
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
2321
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
2322 2323 2324 2325 2326
                out = paddle.nn.functional.relu6(x)
                exe = fluid.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = ref_relu6(self.x_np)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
2327

2328
    def test_errors(self):
W
wanghuancoder 已提交
2329 2330 2331 2332 2333
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, F.relu6, 1)
                # The input dtype must be float16, float32, float64.
2334
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
2335 2336 2337 2338
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.relu6, x_int32)
                # support the input dtype is float16
2339
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
2340 2341 2342
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.relu6(x_fp16)
2343 2344


2345 2346
class TestRelu6APIWarnings(unittest.TestCase):
    def test_warnings(self):
W
wanghuancoder 已提交
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
        with paddle_static_guard():
            with warnings.catch_warnings(record=True) as context:
                warnings.simplefilter("always")

                helper = LayerHelper("relu6")
                data = paddle.static.data(
                    name='data', shape=[None, 3, 32, 32], dtype='float32'
                )
                out = helper.create_variable_for_type_inference(
                    dtype=data.dtype
                )
                os.environ['FLAGS_print_extra_attrs'] = "1"
                helper.append_op(
                    type="relu6",
                    inputs={'X': data},
                    outputs={'Out': out},
                    attrs={'threshold': 6.0},
                )
                self.assertTrue(
                    "op relu6 use extra_attr: threshold"
                    in str(context[-1].message)
                )
                os.environ['FLAGS_print_extra_attrs'] = "0"
2370 2371


2372
def ref_hardswish(x, threshold=6.0, scale=6.0, offset=3.0):
Z
Zhang Ting 已提交
2373 2374 2375 2376
    x_dtype = x.dtype
    if x_dtype == 'float16':
        x_dtype = 'float16'
        x = x.astype('float32')
2377 2378 2379
    return (
        x * np.minimum(np.maximum(x + offset, 0.0), threshold) / scale
    ).astype(x_dtype)
2380 2381


H
huangjun12 已提交
2382 2383 2384 2385
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()
2386
        self.init_shape()
R
Roc 已提交
2387
        self.prim_op_type = "comp"
2388
        self.python_api = paddle.nn.functional.hardswish
2389
        self.public_python_api = paddle.nn.functional.hardswish
J
jakpiase 已提交
2390

2391
        np.random.seed(1024)
2392
        x = np.random.uniform(-6, 6, self.shape).astype(self.dtype)
H
huangjun12 已提交
2393 2394 2395
        threshold = 6.0
        scale = 6.0
        offset = 3.0
2396
        # the same with TestAbs
H
huangjun12 已提交
2397 2398
        x[np.abs(x + offset) < 0.005] = 0.02
        x[np.abs(x - threshold + offset) < 0.005] = threshold - offset + 0.02
2399
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
2400

2401
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
H
huangjun12 已提交
2402
        self.outputs = {'Out': out}
2403 2404
        self.convert_input_output()
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
R
Roc 已提交
2405
        self.enable_cinn = False
H
huangjun12 已提交
2406

2407 2408 2409
    def init_shape(self):
        self.shape = [10, 12]

2410 2411 2412
    def if_only_check_prim(self):
        return False

H
huangjun12 已提交
2413
    def test_check_grad(self):
2414 2415 2416 2417 2418 2419
        self.check_grad(
            ['X'],
            'Out',
            check_prim=True,
            only_check_prim=self.if_only_check_prim(),
        )
2420 2421

    def test_check_output(self):
W
wanghuancoder 已提交
2422
        self.check_output(check_prim=True)
H
huangjun12 已提交
2423 2424


2425
class TestHardSwish_ZeroDim(TestHardSwish):
R
Roc 已提交
2426 2427 2428 2429 2430 2431 2432 2433
    def setUp(self):
        super().setUp()
        self.enable_cinn = False

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


2434 2435 2436 2437
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)
2438 2439 2440
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2441
            else paddle.CPUPlace()
2442
        )
2443 2444

    def test_static_api(self):
W
wanghuancoder 已提交
2445 2446
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
2447
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
2448 2449 2450 2451 2452 2453 2454 2455
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2456 2457

    def test_dygraph_api(self):
2458
        x = paddle.to_tensor([11648.0, 11448.0])
2459 2460 2461
        out1 = F.hardswish(x)
        m = paddle.nn.Hardswish()
        out2 = m(x)
2462
        out_ref = [11648.0, 11448.0]
2463
        for r in [out1, out2]:
2464
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2465 2466

    def test_fluid_api(self):
W
wanghuancoder 已提交
2467 2468
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
2469
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
2470 2471 2472 2473 2474 2475
                out = paddle.nn.functional.hardswish(x)
                exe = fluid.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = ref_hardswish(self.x_np)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)

2476
        x = paddle.to_tensor(self.x_np)
2477
        out = paddle.nn.functional.hardswish(x)
2478
        np.testing.assert_allclose(out_ref, out.numpy(), rtol=1e-05)
2479 2480

    def test_errors(self):
W
wanghuancoder 已提交
2481 2482 2483 2484 2485
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, F.hardswish, 1)
                # The input dtype must be float16, float32, float64.
2486
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
2487 2488 2489 2490
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.hardswish, x_int32)
                # support the input dtype is float16
2491
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
2492 2493 2494
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.hardswish(x_fp16)
2495 2496


C
chengduo 已提交
2497
class TestSoftRelu(TestActivation):
2498 2499
    def setUp(self):
        self.op_type = "soft_relu"
2500 2501
        self.init_dtype()

2502
        np.random.seed(4096)
2503
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
2504
        threshold = 2.0
Q
qijun 已提交
2505 2506
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
2507
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
2508 2509 2510
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
2511
        out = np.log(np.exp(t) + 1)
2512 2513 2514

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
2515 2516
        self.convert_input_output()
        self.attrs = {'threshold': threshold}
2517

2518 2519 2520
    def test_check_output(self):
        self.check_output(check_dygraph=False)

2521
    def test_check_grad(self):
2522 2523
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2524 2525 2526
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.02, check_dygraph=False
        )
2527

2528

2529
def elu(x, alpha):
Z
zhupengyang 已提交
2530
    out_ref = np.where(x > 0, x, alpha * (np.exp(x) - 1))
2531 2532 2533
    return out_ref.astype(x.dtype)


C
chengduo 已提交
2534
class TestELU(TestActivation):
2535 2536
    def setUp(self):
        self.op_type = "elu"
2537
        self.init_dtype()
2538
        self.init_shape()
W
wanghuancoder 已提交
2539
        self.python_api = paddle.nn.functional.elu
2540

2541
        np.random.seed(1024)
2542
        x = np.random.uniform(-3, 3, self.shape).astype(self.dtype)
Z
zhupengyang 已提交
2543
        alpha = self.get_alpha()
2544
        out = elu(x, alpha)
2545 2546
        # 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
2547 2548

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
2549
        self.outputs = {'Out': out}
2550 2551
        self.convert_input_output()
        self.attrs = {'alpha': alpha}
2552

2553 2554 2555
    def init_shape(self):
        self.shape = [10, 12]

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

Z
zhupengyang 已提交
2561
    def get_alpha(self):
2562
        return 1.0
Z
zhupengyang 已提交
2563 2564 2565 2566 2567 2568


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

2569

2570 2571 2572 2573 2574
class TestELU_ZeroDim(TestELU):
    def init_shape(self):
        self.shape = []


2575 2576 2577
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
2578
        np.random.seed(1024)
2579
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
2580 2581 2582
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2583
            else paddle.CPUPlace()
2584
        )
2585 2586 2587 2588
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
2589 2590

    def test_static_api(self):
W
wanghuancoder 已提交
2591 2592
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
2593
                x = paddle.static.data('X', [10, 12], dtype="float32")
W
wanghuancoder 已提交
2594 2595 2596 2597 2598 2599 2600 2601
                out1 = self.elu(x)
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2602 2603 2604

    def test_dygraph_api(self):
        x = paddle.to_tensor(self.x_np)
2605 2606
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
2607 2608 2609 2610
        m = paddle.nn.ELU()
        out2 = m(x)
        out_ref = elu(self.x_np, 1.0)
        for r in [out1, out2]:
2611
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2612

2613 2614
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
2615 2616 2617 2618
        m = paddle.nn.ELU(0.2)
        out2 = m(x)
        out_ref = elu(self.x_np, 0.2)
        for r in [out1, out2]:
2619
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2620

2621
    def test_errors(self):
W
wanghuancoder 已提交
2622 2623 2624 2625 2626
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, self.elu, 1)
                # The input dtype must be float16, float32, float64.
2627
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
2628 2629 2630 2631
                    name='x_int32', shape=[10, 12], dtype='int32'
                )
                self.assertRaises(TypeError, self.elu, x_int32)
                # support the input dtype is float16
2632
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
2633 2634 2635
                    name='x_fp16', shape=[10, 12], dtype='float16'
                )
                self.elu(x_fp16)
2636 2637


Z
zhupengyang 已提交
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
class TestELUInplaceAPI(TestELUAPI):
    # test paddle.nn.functional.elu_
    def executed_api(self):
        self.elu = F.elu_

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


2648 2649 2650 2651 2652 2653 2654 2655 2656
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()
2657
        self.init_shape()
2658

2659
        self.python_api = paddle.nn.functional.celu
2660
        np.random.seed(1024)
2661
        x = np.random.uniform(-3, 3, self.shape).astype(self.dtype)
2662 2663
        alpha = 1.5
        out = celu(x, alpha)
2664 2665

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
2666
        self.outputs = {'Out': out}
2667 2668
        self.convert_input_output()
        self.attrs = {'alpha': alpha}
2669

2670 2671 2672
    def init_shape(self):
        self.shape = [10, 12]

2673 2674 2675
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2676
        self.check_grad(['X'], 'Out')
2677 2678


2679 2680 2681 2682 2683
class TestCELU_ZeroDim(TestCELU):
    def init_shape(self):
        self.shape = []


2684 2685 2686 2687 2688
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')
2689 2690 2691
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
2692
            else paddle.CPUPlace()
2693
        )
2694 2695 2696 2697 2698 2699
        self.executed_api()

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

    def test_static_api(self):
W
wanghuancoder 已提交
2700 2701
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
2702
                x = paddle.static.data('X', [10, 12], dtype="float32")
W
wanghuancoder 已提交
2703 2704 2705 2706 2707 2708 2709 2710
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
2711 2712 2713 2714 2715 2716 2717 2718 2719

    def test_dygraph_api(self):
        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]:
2720
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2721 2722 2723 2724 2725 2726 2727

        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]:
2728
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
2729 2730

    def test_errors(self):
W
wanghuancoder 已提交
2731 2732 2733 2734 2735
        with paddle_static_guard():
            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.
2736
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
2737 2738 2739 2740
                    name='x_int32', shape=[10, 12], dtype='int32'
                )
                self.assertRaises(TypeError, self.celu, x_int32)
                # The alpha must be not equal 0
2741
                x_fp32 = paddle.static.data(
W
wanghuancoder 已提交
2742 2743 2744 2745
                    name='x_fp32', shape=[10, 12], dtype='float32'
                )
                self.assertRaises(ZeroDivisionError, F.celu, x_fp32, 0)
                # support the input dtype is float16
2746
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
2747 2748 2749
                    name='x_fp16', shape=[10, 12], dtype='float16'
                )
                self.celu(x_fp16)
2750 2751


C
chengduo 已提交
2752
class TestReciprocal(TestActivation):
Q
qijun 已提交
2753 2754
    def setUp(self):
        self.op_type = "reciprocal"
2755
        self.python_api = paddle.reciprocal
2756
        self.init_dtype()
2757
        self.init_shape()
2758

2759
        np.random.seed(1024)
2760
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
2761 2762 2763 2764
        out = np.reciprocal(x)

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

    def test_check_grad(self):
2768 2769
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2770
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
2771 2772

    def test_check_output(self):
W
wanghuancoder 已提交
2773
        self.check_output()
Q
qijun 已提交
2774 2775


2776 2777 2778 2779 2780
class TestReciprocal_ZeroDim(TestReciprocal):
    def init_shape(self):
        self.shape = []


C
chengduo 已提交
2781
class TestLog(TestActivation):
Q
qijun 已提交
2782 2783
    def setUp(self):
        self.op_type = "log"
2784
        self.prim_op_type = "prim"
2785
        self.python_api = paddle.log
2786
        self.public_python_api = paddle.log
2787
        self.init_dtype()
2788
        self.init_shape()
2789

2790 2791 2792 2793
        if len(self.shape) == 0:
            # for 0-D tensor, skip cinn testing
            self.enable_cinn = False

2794
        np.random.seed(1024)
2795
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2796 2797 2798 2799
        out = np.log(x)

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

    def test_check_grad(self):
2803 2804
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2805
        self.check_grad(['X'], 'Out', check_prim=True)
Q
qijun 已提交
2806

2807
    def test_error(self):
W
wanghuancoder 已提交
2808 2809 2810 2811 2812 2813 2814 2815
        with paddle_static_guard():
            with paddle_static_guard():
                in1 = paddle.static.data(
                    name="in1", shape=[11, 17], dtype="int32"
                )
                in2 = paddle.static.data(
                    name="in2", shape=[11, 17], dtype="int64"
                )
2816

W
wanghuancoder 已提交
2817 2818
                self.assertRaises(TypeError, paddle.log, in1)
                self.assertRaises(TypeError, paddle.log, in2)
2819

2820

2821 2822
class Test_Log_Op_Fp16(unittest.TestCase):
    def test_api_fp16(self):
W
wanghuancoder 已提交
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
        with paddle_static_guard():
            with static.program_guard(
                paddle.static.Program(), paddle.static.Program()
            ):
                x = [[2, 3, 4], [7, 8, 9]]
                x = paddle.to_tensor(x, dtype='float16')
                out = paddle.log(x)
                if core.is_compiled_with_cuda():
                    place = paddle.CUDAPlace(0)
                    exe = paddle.static.Executor(place)
                    (res,) = exe.run(fetch_list=[out])
2834 2835


2836 2837 2838 2839 2840
class TestLog_ZeroDim(TestLog):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
2841 2842 2843
class TestLog2(TestActivation):
    def setUp(self):
        self.op_type = "log2"
2844
        self.python_api = paddle.log2
J
joejiong 已提交
2845
        self.init_dtype()
2846
        self.init_shape()
J
joejiong 已提交
2847

2848
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
J
joejiong 已提交
2849 2850 2851 2852
        out = np.log2(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
2853
        self.convert_input_output()
J
joejiong 已提交
2854 2855 2856 2857

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2858
        self.check_grad(['X'], 'Out')
J
joejiong 已提交
2859 2860

    def test_error(self):
W
wanghuancoder 已提交
2861 2862 2863
        with paddle_static_guard():
            in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
            in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")
J
joejiong 已提交
2864

W
wanghuancoder 已提交
2865 2866
            self.assertRaises(TypeError, paddle.log2, in1)
            self.assertRaises(TypeError, paddle.log2, in2)
J
joejiong 已提交
2867 2868

    def test_api(self):
W
wanghuancoder 已提交
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
        with paddle_static_guard():
            with paddle.static.program_guard(
                paddle.static.Program(), paddle.static.Program()
            ):
                input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
                data_x = paddle.static.data(
                    name="data_x", shape=[11, 17], dtype="float64"
                )

                out1 = paddle.log2(data_x)
                exe = paddle.static.Executor(place=fluid.CPUPlace())
                exe.run(paddle.static.default_startup_program())
                (res1,) = exe.run(
                    paddle.static.default_main_program(),
                    feed={"data_x": input_x},
                    fetch_list=[out1],
                )
            expected_res = np.log2(input_x)
            np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
J
joejiong 已提交
2888 2889 2890 2891 2892 2893 2894 2895

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


2899 2900 2901 2902 2903
class TestLog2_ZeroDim(TestLog2):
    def init_shape(self):
        self.shape = []


J
joejiong 已提交
2904 2905 2906
class TestLog10(TestActivation):
    def setUp(self):
        self.op_type = "log10"
2907
        self.python_api = paddle.log10
J
joejiong 已提交
2908
        self.init_dtype()
2909
        self.init_shape()
J
joejiong 已提交
2910

2911
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
J
joejiong 已提交
2912 2913 2914 2915
        out = np.log10(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
2916
        self.convert_input_output()
J
joejiong 已提交
2917 2918 2919 2920

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2921
        self.check_grad(['X'], 'Out')
J
joejiong 已提交
2922

2923 2924 2925 2926 2927 2928 2929

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


class TestLog10API(unittest.TestCase):
J
joejiong 已提交
2930
    def test_error(self):
W
wanghuancoder 已提交
2931 2932 2933
        with paddle_static_guard():
            in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
            in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")
J
joejiong 已提交
2934

W
wanghuancoder 已提交
2935 2936
            self.assertRaises(TypeError, paddle.log10, in1)
            self.assertRaises(TypeError, paddle.log10, in2)
J
joejiong 已提交
2937 2938

    def test_api(self):
W
wanghuancoder 已提交
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
        with paddle_static_guard():
            with paddle.static.program_guard(
                paddle.static.Program(), paddle.static.Program()
            ):
                input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
                data_x = paddle.static.data(
                    name="data_x", shape=[11, 17], dtype="float64"
                )

                out1 = paddle.log10(data_x)
                exe = paddle.static.Executor(place=paddle.CPUPlace())
                exe.run(paddle.static.default_startup_program())
                (res1,) = exe.run(
                    paddle.static.default_main_program(),
                    feed={"data_x": input_x},
                    fetch_list=[out1],
                )
            expected_res = np.log10(input_x)
            np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
J
joejiong 已提交
2958 2959 2960 2961 2962 2963 2964 2965

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


2969 2970 2971
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
2972
        self.python_api = paddle.log1p
2973
        self.init_dtype()
2974
        self.init_shape()
2975

2976
        np.random.seed(1024)
2977
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
2978 2979 2980 2981
        out = np.log1p(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
2982
        self.convert_input_output()
2983 2984 2985 2986

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
2987
        self.check_grad(['X'], 'Out')
2988

2989

2990 2991
class Test_Log1p_Op_Fp16(unittest.TestCase):
    def test_api_fp16(self):
W
wanghuancoder 已提交
2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
        with paddle_static_guard():
            with static.program_guard(
                paddle.static.Program(), paddle.static.Program()
            ):
                x = [[2, 3, 4], [7, 8, 9]]
                x = paddle.to_tensor(x, dtype='float16')
                out = paddle.log1p(x)
                if core.is_compiled_with_cuda():
                    place = paddle.CUDAPlace(0)
                    exe = paddle.static.Executor(place)
                    (res,) = exe.run(fetch_list=[out])
3003 3004


3005 3006 3007 3008 3009 3010
class TestLog1p_ZeroDim(TestLog1p):
    def init_shape(self):
        self.shape = []


class TestLog1pAPI(unittest.TestCase):
3011
    def test_api(self):
W
wanghuancoder 已提交
3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
                data_x = paddle.static.data(
                    name="data_x",
                    shape=[11, 17],
                    dtype="float64",
                )

                out1 = paddle.log1p(data_x)
                exe = fluid.Executor(place=fluid.CPUPlace())
                exe.run(fluid.default_startup_program())
                (res1,) = exe.run(
                    fluid.default_main_program(),
                    feed={"data_x": input_x},
                    fetch_list=[out1],
                )
            expected_res = np.log1p(input_x)
            np.testing.assert_allclose(res1, expected_res, rtol=1e-05)
3031 3032 3033 3034 3035 3036 3037 3038

        # 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))
3039
        np.testing.assert_allclose(np_z, z_expected, rtol=1e-05)
3040 3041


C
chengduo 已提交
3042
class TestSquare(TestActivation):
Q
qijun 已提交
3043 3044
    def setUp(self):
        self.op_type = "square"
3045
        self.python_api = paddle.square
3046
        self.init_dtype()
3047
        self.init_shape()
3048

3049
        np.random.seed(1024)
3050
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
3051 3052 3053 3054
        out = np.square(x)

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

    def test_check_grad(self):
3058 3059
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
3060
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
3061 3062

    def test_check_output(self):
W
wanghuancoder 已提交
3063
        self.check_output()
Q
qijun 已提交
3064

3065

3066 3067 3068 3069 3070
class TestSquare_ZeroDim(TestSquare):
    def init_shape(self):
        self.shape = []


3071 3072 3073
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
3074 3075 3076
class TestSquareBF16(OpTest):
    def setUp(self):
        self.op_type = "square"
3077
        self.python_api = paddle.square
3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
        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)
W
wanghuancoder 已提交
3094
        self.check_output_with_place(place)
3095 3096 3097

    def test_check_grad(self):
        place = core.CUDAPlace(0)
W
wanghuancoder 已提交
3098
        self.check_grad_with_place(place, ['X'], 'Out', numeric_grad_delta=0.5)
3099 3100


C
chengduo 已提交
3101
class TestPow(TestActivation):
3102 3103
    def setUp(self):
        self.op_type = "pow"
3104
        self.prim_op_type = "comp"
3105
        self.python_api = paddle.pow
3106
        self.public_python_api = paddle.pow
3107
        self.init_dtype()
3108
        self.init_shape()
3109

3110
        np.random.seed(1024)
3111
        x = np.random.uniform(1, 2, self.shape).astype(self.dtype)
3112 3113 3114 3115
        out = np.power(x, 3)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
3116 3117
        self.attrs = {'factor': 3.0}
        self.convert_input_output()
3118

3119
    def test_check_output(self):
3120
        self.check_output(check_prim=True)
3121

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

3127

3128 3129 3130 3131
class TestPow_ZeroDim(TestPow):
    def init_shape(self):
        self.shape = []

3132
    def setUp(self):
3133
        super().setUp()
3134 3135
        self.enable_cinn = False

3136

3137 3138 3139
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
3140
        self.python_api = paddle.pow
3141
        self.enable_cinn = False
3142 3143
        self.init_dtype()

3144
        np.random.seed(1024)
3145 3146 3147 3148 3149
        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),
W
wanghuancoder 已提交
3150
            'FactorTensor': np.array([3.0]).astype(self.dtype),
3151 3152 3153 3154 3155 3156
        }

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

    def test_check_output(self):
W
wanghuancoder 已提交
3157
        self.check_output()
3158 3159 3160 3161

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
3162
        self.check_grad(['X'], 'Out')
3163 3164

    def test_api(self):
W
wanghuancoder 已提交
3165 3166 3167 3168 3169 3170 3171 3172
        with paddle_static_guard():
            input = np.random.uniform(1, 2, [11, 17]).astype("float32")
            x = paddle.static.data(name="x", shape=[11, 17], dtype="float32")
            res = paddle.static.data(
                name="res", shape=[11, 17], dtype="float32"
            )

            factor_1 = 2.0
3173
            factor_2 = paddle.tensor.fill_constant([1], "float32", 3.0)
W
wanghuancoder 已提交
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
            out_1 = paddle.pow(x, factor_1)
            out_2 = paddle.pow(x, factor_2)
            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)

            exe = fluid.Executor(place=fluid.CPUPlace())
            res_1, res_2, res, res_6 = exe.run(
                fluid.default_main_program(),
                feed={"x": input},
                fetch_list=[out_1, out_2, res, out_6],
            )
3186

W
wanghuancoder 已提交
3187 3188 3189
            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))
3190 3191


3192 3193 3194 3195 3196
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
3197
class TestSTanh(TestActivation):
3198 3199 3200 3201 3202 3203
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

3204 3205
    def setUp(self):
        self.op_type = "stanh"
W
wanghuancoder 已提交
3206
        self.python_api = paddle.stanh
3207
        self.init_dtype()
3208 3209
        self.init_shape()

3210 3211
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
3212

3213
        np.random.seed(1024)
3214
        x = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
3215 3216
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
3217

3218
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
3219
        self.outputs = {'Out': out}
3220 3221
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
        self.convert_input_output()
3222

Q
qijun 已提交
3223
    def test_check_grad(self):
3224 3225
        if self.dtype == np.float16:
            return
3226
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
3227

3228

3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
class TestSTanhScaleA(TestSTanh):
    def get_scale_a(self):
        return 2.0


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


3239 3240 3241 3242 3243
class TestSTanh_ZeroDim(TestSTanh):
    def init_shape(self):
        self.shape = []


3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
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()
3257 3258 3259
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
3260
            else paddle.CPUPlace()
3261
        )
3262 3263

    def test_static_api(self):
W
wanghuancoder 已提交
3264 3265
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
3266
                x = paddle.static.data('X', [10, 12])
W
wanghuancoder 已提交
3267 3268 3269 3270 3271 3272
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3273 3274 3275 3276 3277 3278

    def test_dygraph_api(self):
        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]:
3279
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3280 3281

    def test_fluid_api(self):
W
wanghuancoder 已提交
3282 3283
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
3284
                x = paddle.static.data('X', [10, 12], dtype="float32")
W
wanghuancoder 已提交
3285 3286 3287 3288 3289
                out = paddle.stanh(x, self.scale_a, self.scale_b)
                exe = fluid.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3290

3291
    def test_errors(self):
W
wanghuancoder 已提交
3292 3293 3294 3295 3296
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, paddle.stanh, 1)
                # The input dtype must be float16, float32, float64.
3297
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3298 3299 3300 3301
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, paddle.stanh, x_int32)
                # support the input dtype is float16
3302
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3303 3304 3305
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                paddle.stanh(x_fp16)
3306 3307 3308 3309 3310 3311 3312 3313 3314 3315


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


class TestSTanhAPIScaleB(TestSTanhAPI):
    def get_scale_b(self):
        return 0.5
3316 3317


3318 3319
def ref_softplus(x, beta=1, threshold=20):
    x_beta = beta * x
3320 3321 3322 3323
    out = np.select(
        [x_beta <= threshold, x_beta > threshold],
        [np.log(1 + np.exp(x_beta)) / beta, x],
    )
3324 3325 3326
    return out


C
chengduo 已提交
3327
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
3328 3329
    def setUp(self):
        self.op_type = "softplus"
W
Wang Bojun 已提交
3330
        self.python_api = paddle.nn.functional.softplus
3331
        self.init_dtype()
3332
        self.init_shape()
3333

3334 3335
        beta = 2
        threshold = 15
3336

3337
        np.random.seed(1024)
3338
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3339 3340 3341
        out = ref_softplus(x, beta, threshold)
        self.inputs = {'X': x}
        self.attrs = {'beta': beta, "threshold": threshold}
3342
        self.outputs = {'Out': out}
K
kexinzhao 已提交
3343

3344 3345 3346
    def init_shape(self):
        self.shape = [10, 12]

K
kexinzhao 已提交
3347
    def test_check_grad(self):
3348 3349
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
3350
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
3351

3352

3353 3354 3355 3356 3357
class TestSoftplus_ZeroDim(TestSoftplus):
    def init_shape(self):
        self.shape = []


3358 3359 3360
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
3361 3362 3363 3364
class TestSoftplusBF16(OpTest):
    def setUp(self):
        self.op_type = "softplus"
        self.init_dtype()
W
wanghuancoder 已提交
3365
        self.python_api = paddle.nn.functional.softplus
3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388

        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)


3389 3390 3391 3392 3393
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
3394
        np.random.seed(1024)
3395
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
3396 3397 3398
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3399
            else paddle.CPUPlace()
3400
        )
3401 3402

    def test_static_api(self):
W
wanghuancoder 已提交
3403 3404
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
3405
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
3406 3407 3408 3409 3410 3411 3412 3413
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3414 3415 3416 3417 3418 3419 3420 3421

    def test_dygraph_api(self):
        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]:
3422
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3423 3424

    def test_errors(self):
W
wanghuancoder 已提交
3425 3426 3427 3428 3429
        with paddle_static_guard():
            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.
3430
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3431 3432 3433 3434
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.softplus, x_int32)
                # support the input dtype is float16
3435
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3436 3437 3438
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.softplus(x_fp16)
3439 3440 3441 3442 3443 3444 3445


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


C
chengduo 已提交
3446
class TestSoftsign(TestActivation):
3447 3448
    def setUp(self):
        self.op_type = "softsign"
3449
        self.init_dtype()
3450 3451
        self.init_shape()

3452
        self.python_api = paddle.nn.functional.softsign
3453

3454
        np.random.seed(1024)
3455
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3456
        out = ref_softsign(x)
3457 3458

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

3462 3463 3464
    def init_shape(self):
        self.shape = [10, 12]

3465
    def test_check_grad(self):
3466 3467
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
3468
        self.check_grad(['X'], 'Out')
3469 3470


3471 3472 3473 3474 3475
class TestSoftsign_ZeroDim(TestSoftsign):
    def init_shape(self):
        self.shape = []


3476 3477 3478
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
3479
        np.random.seed(1024)
3480
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
3481 3482 3483
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3484
            else paddle.CPUPlace()
3485
        )
3486 3487

    def test_static_api(self):
W
wanghuancoder 已提交
3488 3489
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
3490
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
3491 3492 3493 3494 3495 3496 3497 3498
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3499 3500 3501 3502 3503 3504 3505 3506

    def test_dygraph_api(self):
        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]:
3507
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3508 3509

    def test_errors(self):
W
wanghuancoder 已提交
3510 3511 3512 3513 3514
        with paddle_static_guard():
            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.
3515
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3516 3517 3518 3519
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.softsign, x_int32)
                # support the input dtype is float16
3520
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3521 3522 3523
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.softsign(x_fp16)
3524 3525


3526 3527 3528 3529 3530
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
3531
class TestThresholdedRelu(TestActivation):
3532 3533
    def setUp(self):
        self.op_type = "thresholded_relu"
3534
        self.init_dtype()
3535
        self.init_shape()
W
wanghuancoder 已提交
3536
        self.python_api = paddle.nn.functional.thresholded_relu
3537

3538
        threshold = 15
3539

3540
        np.random.seed(1024)
3541
        x = np.random.uniform(-20, 20, self.shape).astype(self.dtype)
3542 3543
        x[np.abs(x) < 0.005] = 0.02
        out = ref_thresholded_relu(x, threshold)
3544 3545

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
3546
        self.outputs = {'Out': out}
3547 3548
        self.attrs = {"threshold": threshold}
        self.convert_input_output()
3549

3550 3551 3552
    def init_shape(self):
        self.shape = [10, 12]

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


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


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

    def test_static_api(self):
W
wanghuancoder 已提交
3578 3579
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
3580
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
3581 3582 3583 3584 3585 3586 3587 3588
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3589 3590 3591 3592 3593 3594 3595 3596

    def test_dygraph_api(self):
        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]:
3597
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3598

3599
    def test_errors(self):
W
wanghuancoder 已提交
3600 3601 3602 3603 3604
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, F.thresholded_relu, 1)
                # The input dtype must be float16, float32, float64.
3605
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3606 3607 3608 3609
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.thresholded_relu, x_int32)
                # support the input dtype is float16
3610
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3611 3612 3613
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.thresholded_relu(x_fp16)
3614 3615


3616
def ref_hardsigmoid(x, slope=0.166666666666667, offset=0.5):
3617
    return np.maximum(np.minimum(x * slope + offset, 1.0), 0.0).astype(x.dtype)
3618 3619


C
chengduo 已提交
3620
class TestHardSigmoid(TestActivation):
3621 3622
    def setUp(self):
        self.op_type = "hard_sigmoid"
3623 3624 3625 3626
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
3627
        self.init_shape()
W
wanghuancoder 已提交
3628
        self.python_api = paddle.nn.functional.hardsigmoid
3629

3630
        x = np.random.uniform(-5, 5, self.shape).astype(self.dtype)
3631
        lower_threshold = -self.offset / self.slope
3632
        upper_threshold = (1.0 - self.offset) / self.slope
Z
zhupengyang 已提交
3633

3634
        # Same reason as TestAbs
3635 3636 3637
        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
3638

3639
        out = ref_hardsigmoid(x, self.slope, self.offset)
3640

3641
        self.attrs = {'slope': self.slope, 'offset': self.offset}
3642 3643

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

3647 3648 3649
    def init_shape(self):
        self.shape = [10, 12]

3650 3651
    def set_attrs(self):
        pass
3652

3653

3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
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


3665 3666 3667 3668 3669
class TestHardSigmoid_ZeroDim(TestHardSigmoid):
    def init_shape(self):
        self.shape = []


3670 3671 3672 3673
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)
3674 3675 3676
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3677
            else paddle.CPUPlace()
3678
        )
3679 3680

    def test_static_api(self):
W
wanghuancoder 已提交
3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3692 3693 3694 3695 3696 3697 3698 3699

    def test_dygraph_api(self):
        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]:
3700
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3701 3702

    def test_fluid_api(self):
W
wanghuancoder 已提交
3703 3704
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
3705
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
3706 3707 3708 3709 3710 3711
                out = paddle.nn.functional.hardsigmoid(x, slope=0.2)
                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)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)

3712
        paddle.disable_static(self.place)
3713
        x = paddle.to_tensor(self.x_np)
3714
        out = paddle.nn.functional.hardsigmoid(x, slope=0.2)
3715
        np.testing.assert_allclose(out_ref, out.numpy(), rtol=1e-05)
3716 3717

    def test_errors(self):
W
wanghuancoder 已提交
3718 3719 3720 3721 3722
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, F.hardsigmoid, 1)
                # The input dtype must be float16, float32, float64.
3723
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3724 3725 3726 3727
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.hardsigmoid, x_int32)
                # support the input dtype is float16
3728
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3729 3730 3731
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.hardsigmoid(x_fp16)
3732 3733


3734 3735 3736 3737 3738
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
3739
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
3740 3741
    def setUp(self):
        self.op_type = "swish"
3742
        self.python_api = paddle.nn.functional.swish
3743
        self.init_dtype()
3744 3745
        self.init_shape()

3746
        np.random.seed(1024)
3747
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3748
        out = ref_swish(x)
3749 3750

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
3751
        self.outputs = {'Out': out}
3752 3753
        self.attrs = {'beta': 1.0}
        self.convert_input_output()
A
Abhinav Arora 已提交
3754

3755 3756 3757
    def init_shape(self):
        self.shape = [10, 12]

A
Abhinav Arora 已提交
3758
    def test_check_grad(self):
3759 3760
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
3761 3762 3763 3764
        self.check_grad(
            ['X'],
            'Out',
        )
3765

A
Abhinav Arora 已提交
3766

3767 3768 3769 3770 3771
class TestSwish_ZeroDim(TestSwish):
    def init_shape(self):
        self.shape = []


3772 3773 3774 3775 3776
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)
3777 3778 3779
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3780
            else paddle.CPUPlace()
3781
        )
3782 3783

    def test_static_api(self):
W
wanghuancoder 已提交
3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
                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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3795

3796
    def test_dygraph_api(self):
3797 3798 3799 3800 3801 3802
        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]:
3803
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3804 3805

    def test_fluid_api(self):
W
wanghuancoder 已提交
3806 3807
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
3808
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
3809 3810 3811 3812 3813
                out = paddle.nn.functional.swish(x)
                exe = fluid.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = ref_swish(self.x_np)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3814

3815
    def test_errors(self):
W
wanghuancoder 已提交
3816 3817 3818 3819 3820
        with paddle_static_guard():
            with paddle.static.program_guard(paddle.static.Program()):
                # The input type must be Variable.
                self.assertRaises(TypeError, F.swish, 1)
                # The input dtype must be float16, float32, float64.
3821
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3822 3823 3824 3825
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.swish, x_int32)
                # support the input dtype is float16
3826
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3827 3828 3829
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.swish(x_fp16)
3830 3831


3832 3833 3834 3835
def ref_mish(x, threshold=20.0):
    softplus = np.select(
        [x <= threshold, x > threshold], [np.log(1 + np.exp(x)), x]
    )
3836 3837 3838 3839 3840 3841
    return x * np.tanh(softplus)


class TestMish(TestActivation):
    def setUp(self):
        self.op_type = "mish"
3842
        self.python_api = paddle.nn.functional.mish
3843
        self.init_dtype()
3844
        self.init_shape()
3845 3846

        np.random.seed(1024)
3847
        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
3848
        out = ref_mish(x)
3849 3850

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

3854 3855 3856
    def init_shape(self):
        self.shape = [10, 12]

3857
    def test_check_output(self):
W
wanghuancoder 已提交
3858
        self.check_output()
3859

3860 3861 3862
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
W
wanghuancoder 已提交
3863
        self.check_grad(['X'], 'Out')
3864 3865


3866 3867 3868 3869 3870
class TestMish_ZeroDim(TestMish):
    def init_shape(self):
        self.shape = []


3871 3872 3873 3874 3875
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)
3876 3877 3878
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
3879
            else paddle.CPUPlace()
3880
        )
3881 3882

    def test_static_api(self):
W
wanghuancoder 已提交
3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
        with paddle_static_guard():
            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:
                np.testing.assert_allclose(out_ref, r, rtol=1e-05)
3894 3895 3896 3897 3898 3899 3900 3901

    def test_dygraph_api(self):
        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]:
3902
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
3903 3904

    def test_fluid_api(self):
W
wanghuancoder 已提交
3905 3906
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program()):
3907
                x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
W
wanghuancoder 已提交
3908 3909 3910 3911 3912
                out = paddle.nn.functional.mish(x)
                exe = fluid.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = ref_mish(self.x_np)
            np.testing.assert_allclose(out_ref, res[0], rtol=1e-05)
3913 3914

    def test_errors(self):
W
wanghuancoder 已提交
3915 3916 3917 3918 3919
        with paddle_static_guard():
            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.
3920
                x_int32 = paddle.static.data(
W
wanghuancoder 已提交
3921 3922 3923 3924
                    name='x_int32', shape=[12, 10], dtype='int32'
                )
                self.assertRaises(TypeError, F.mish, x_int32)
                # support the input dtype is float16
3925
                x_fp16 = paddle.static.data(
W
wanghuancoder 已提交
3926 3927 3928
                    name='x_fp16', shape=[12, 10], dtype='float16'
                )
                F.mish(x_fp16)
3929 3930


3931
# ------------------ Test Cudnn Activation----------------------
3932
def create_test_act_cudnn_class(parent, atol=1e-3, grad_atol=1e-3):
3933 3934 3935
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
3936 3937 3938 3939
    class TestActCudnn(parent):
        def init_kernel_type(self):
            self.attrs = {"use_cudnn": True}

3940
    cls_name = "{}_{}".format(parent.__name__, "cudnn")
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
    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)


3951 3952
# ------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(
3953 3954 3955
    parent,
    atol=1e-3,
    grad_check=True,
3956
    check_dygraph=True,
3957 3958
    check_prim=False,
    enable_cinn=True,
3959
    grad_atol=1e-2,
3960
    **kwargs
3961 3962 3963 3964
):
    @unittest.skipIf(
        not paddle.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
C
chengduo 已提交
3965
    class TestActFp16(parent):
3966 3967 3968 3969 3970
        def setUp(self):
            super().setUp()
            for k, v in kwargs.items():
                setattr(self, k, v)

C
chengduo 已提交
3971 3972
        def init_dtype(self):
            self.dtype = np.float16
3973

3974
        def if_enable_cinn(self):
3975 3976
            self.enable_cinn = enable_cinn

C
chengduo 已提交
3977
        def test_check_output(self):
3978
            place = core.CUDAPlace(0)
C
chengduo 已提交
3979 3980
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
3981
                self.check_output_with_place(
3982 3983 3984 3985
                    place,
                    atol=atol,
                    check_dygraph=check_dygraph,
                    check_prim=check_prim,
3986
                )
3987

C
chengduo 已提交
3988 3989 3990 3991
        def test_check_grad(self):
            place = core.CUDAPlace(0)
            support_fp16 = core.is_float16_supported(place)
            if support_fp16 and grad_check:
3992
                self.check_grad_with_place(
3993 3994 3995
                    place,
                    ['X'],
                    'Out',
3996
                    check_dygraph=check_dygraph,
3997 3998
                    check_prim=check_prim,
                    max_relative_error=grad_atol,
3999
                )
C
chengduo 已提交
4000

4001
    cls_name = "{}_{}".format(parent.__name__, "FP16OP")
C
chengduo 已提交
4002 4003 4004 4005
    TestActFp16.__name__ = cls_name
    globals()[cls_name] = TestActFp16


4006
create_test_act_fp16_class(TestActivation, check_prim=True)
R
ronnywang 已提交
4007
create_test_act_fp16_class(TestExpm1)
4008 4009
create_test_act_fp16_class(TestSigmoid, check_prim=True)
create_test_act_fp16_class(TestSilu, check_prim=True)
C
chengduo 已提交
4010 4011
create_test_act_fp16_class(TestLogSigmoid)
create_test_act_fp16_class(TestTanh)
4012
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
4013
create_test_act_fp16_class(TestHardShrink)
4014
create_test_act_fp16_class(TestSoftshrink)
4015
create_test_act_fp16_class(TestSqrt, check_prim=True)
M
mhy-666 已提交
4016
create_test_act_fp16_class(TestSqrtComp, check_prim=True)
4017
create_test_act_fp16_class(TestAbs, check_prim=True)
C
chengduo 已提交
4018
create_test_act_fp16_class(TestCeil, grad_check=False)
4019
create_test_act_fp16_class(TestFloor, check_prim=True, grad_check=False)
4020 4021 4022 4023
create_test_act_fp16_class(TestCos)
create_test_act_fp16_class(TestTan)
create_test_act_fp16_class(TestCosh)
create_test_act_fp16_class(TestAcos)
C
chengduo 已提交
4024
create_test_act_fp16_class(TestSin)
4025
create_test_act_fp16_class(TestSinh)
4026 4027
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
4028 4029 4030
create_test_act_fp16_class(TestAcosh)
create_test_act_fp16_class(TestAsinh)
create_test_act_fp16_class(TestAtanh)
C
chengduo 已提交
4031
create_test_act_fp16_class(TestRound, grad_check=False)
K
Kang Zhao 已提交
4032
create_test_act_fp16_class(TestRelu, check_prim=True)
4033 4034 4035
create_test_act_fp16_class(
    TestGelu,
    check_prim=True,
4036
    enable_cinn=True,
4037 4038
    rev_comp_rtol=1e-3,
    rev_comp_atol=1e-3,
4039 4040
    cinn_rtol=1e-3,
    cinn_atol=1e-3,
4041
)
C
chengduo 已提交
4042 4043
create_test_act_fp16_class(TestBRelu)
create_test_act_fp16_class(TestRelu6)
4044
create_test_act_fp16_class(TestSoftRelu, check_dygraph=False)
C
chengduo 已提交
4045
create_test_act_fp16_class(TestELU)
4046
create_test_act_fp16_class(TestCELU)
C
chengduo 已提交
4047
create_test_act_fp16_class(TestReciprocal)
4048
create_test_act_fp16_class(TestLog, check_prim=True)
4049
if core.is_compiled_with_rocm():
4050
    create_test_act_fp16_class(TestLog2)
4051
else:
4052 4053 4054
    create_test_act_fp16_class(TestLog2)
create_test_act_fp16_class(TestLog10)
create_test_act_fp16_class(TestLog1p)
C
chengduo 已提交
4055
create_test_act_fp16_class(TestSquare)
4056 4057 4058
create_test_act_fp16_class(TestPow, check_prim=True)
create_test_act_fp16_class(TestPow_factor_tensor)
create_test_act_fp16_class(TestSTanh)
C
chengduo 已提交
4059 4060 4061 4062
create_test_act_fp16_class(TestSoftplus)
create_test_act_fp16_class(TestSoftsign)
create_test_act_fp16_class(TestThresholdedRelu)
create_test_act_fp16_class(TestHardSigmoid)
4063
create_test_act_fp16_class(TestSwish)
4064
create_test_act_fp16_class(TestHardSwish, check_prim=True)
4065
create_test_act_fp16_class(TestMish)
4066 4067 4068 4069 4070 4071 4072
create_test_act_fp16_class(TestLeakyRelu, check_prim=True)
create_test_act_fp16_class(TestLeakyReluAlpha1, check_prim=True)
create_test_act_fp16_class(TestLeakyReluAlpha2, check_prim=True)
create_test_act_fp16_class(TestLeakyReluAlpha3, check_prim=True)
create_test_act_fp16_class(
    TestLeakyRelu_ZeroDim, check_prim=True, enable_cinn=False
)
4073
create_test_act_fp16_class(TestRsqrt)
A
Abhinav Arora 已提交
4074

4075

4076
def create_test_act_bf16_class(
4077 4078 4079 4080 4081 4082 4083 4084
    parent,
    atol=1e-2,
    grad_check=True,
    check_dygraph=True,
    check_prim=False,
    enable_cinn=True,
    grad_atol=1e-2,
    **kwargs
4085 4086
):
    @unittest.skipIf(
4087 4088 4089
        not core.is_compiled_with_cuda()
        or not core.is_bfloat16_supported(core.CUDAPlace(0)),
        "core is not compiled with CUDA and do not support bfloat16",
4090
    )
4091
    class TestActBF16(parent):
4092 4093 4094 4095 4096
        def setUp(self):
            super().setUp()
            for k, v in kwargs.items():
                setattr(self, k, v)

4097
        def init_dtype(self):
4098 4099 4100 4101 4102
            self.dtype = np.float32

        def convert_input_output(self):
            self.inputs = {'X': convert_float_to_uint16(self.inputs['X'])}
            self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
4103 4104 4105 4106 4107 4108 4109 4110
            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)
4111 4112 4113 4114
            if grad_check:
                self.check_grad_with_place(
                    place, ['X'], 'Out', max_relative_error=grad_atol
                )
4115

4116
    cls_name = "{}_{}".format(parent.__name__, "BF16OP")
4117 4118 4119 4120
    TestActBF16.__name__ = cls_name
    globals()[cls_name] = TestActBF16


4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150
create_test_act_bf16_class(TestActivation, check_prim=True)
create_test_act_bf16_class(TestExpm1)
create_test_act_bf16_class(TestSigmoid, check_prim=True)
create_test_act_bf16_class(TestSilu, check_prim=True)
create_test_act_bf16_class(TestLogSigmoid)
create_test_act_bf16_class(TestTanh)
create_test_act_bf16_class(TestTanhshrink)
create_test_act_bf16_class(TestHardShrink)
create_test_act_bf16_class(TestSoftshrink)
create_test_act_bf16_class(TestSqrt, check_prim=True)
create_test_act_bf16_class(TestSqrtComp, check_prim=True)
create_test_act_bf16_class(TestAbs, check_prim=True)
create_test_act_bf16_class(TestCeil, grad_check=False)
create_test_act_bf16_class(TestFloor, grad_check=False, check_prim=True)
create_test_act_bf16_class(TestCos)
create_test_act_bf16_class(TestTan)
create_test_act_bf16_class(TestCosh)
create_test_act_bf16_class(TestAcos)
create_test_act_bf16_class(TestSin)
create_test_act_bf16_class(TestSinh)
create_test_act_bf16_class(TestAsin)
create_test_act_bf16_class(TestAtan)
create_test_act_bf16_class(TestAcosh)
create_test_act_bf16_class(TestAsinh)
create_test_act_bf16_class(TestAtanh)
create_test_act_bf16_class(TestRound, grad_check=False)
create_test_act_bf16_class(TestRelu, check_prim=True)
create_test_act_bf16_class(
    TestGelu,
    check_prim=True,
4151
    enable_cinn=True,
4152 4153
    rev_comp_rtol=1e-2,
    rev_comp_atol=1e-2,
4154 4155
    cinn_rtol=1e-2,
    cinn_atol=1e-2,
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
)
create_test_act_bf16_class(TestBRelu)
create_test_act_bf16_class(TestRelu6)
create_test_act_bf16_class(TestSoftRelu, check_dygraph=False)
create_test_act_bf16_class(TestELU)
create_test_act_bf16_class(TestCELU)
create_test_act_bf16_class(TestReciprocal)
create_test_act_bf16_class(TestLog, check_prim=True)
if core.is_compiled_with_rocm():
    create_test_act_bf16_class(TestLog2)
else:
    create_test_act_bf16_class(TestLog2)
create_test_act_bf16_class(TestLog10)
create_test_act_bf16_class(TestLog1p)
create_test_act_bf16_class(TestSquare)
create_test_act_bf16_class(TestPow, check_prim=True)
create_test_act_bf16_class(TestPow_factor_tensor)
create_test_act_bf16_class(TestSTanh)
create_test_act_bf16_class(TestSoftplus)
create_test_act_bf16_class(TestSoftsign)
create_test_act_bf16_class(TestThresholdedRelu)
create_test_act_bf16_class(TestHardSigmoid)
create_test_act_bf16_class(TestSwish)
create_test_act_bf16_class(TestHardSwish, check_prim=True)
create_test_act_bf16_class(TestMish)
4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
create_test_act_bf16_class(TestLeakyRelu, check_prim=True, enable_cinn=False)
create_test_act_bf16_class(
    TestLeakyReluAlpha1, check_prim=True, enable_cinn=False
)
create_test_act_bf16_class(
    TestLeakyReluAlpha2, check_prim=True, enable_cinn=False
)
create_test_act_bf16_class(
    TestLeakyReluAlpha3, check_prim=True, enable_cinn=False
)
create_test_act_bf16_class(
    TestLeakyRelu_ZeroDim, check_prim=True, enable_cinn=False
)
4194
create_test_act_bf16_class(TestRsqrt)
4195

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