test_activation_op.py 74.4 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 16
from __future__ import print_function

Q
qijun 已提交
17 18
import unittest
import numpy as np
K
Kexin Zhao 已提交
19
import paddle.fluid.core as core
Q
qijun 已提交
20
from op_test import OpTest
C
Clementine 已提交
21
from scipy.special import expit, erf
22
import paddle
23
import paddle.fluid as fluid
24
import paddle.nn as nn
25
import paddle.nn.functional as F
26
from paddle.fluid import compiler, Program, program_guard
Q
qijun 已提交
27 28


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

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


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

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

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

    def test_check_output(self):
        self.check_output()

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

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

71 72 73
    def init_kernel_type(self):
        pass

Q
qijun 已提交
74

75 76
class TestParameter(object):
    def test_out_name(self):
77
        paddle.enable_static()
78
        with fluid.program_guard(fluid.Program()):
W
WuHaobo 已提交
79
            np_x = np.array([0.1])
80
            data = fluid.layers.data(name="X", shape=[1])
W
WuHaobo 已提交
81
            out = eval("paddle.%s(data, name='Y')" % self.op_type)
82 83
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
W
WuHaobo 已提交
84 85 86
            result, = exe.run(feed={"X": np_x}, fetch_list=[out])
            expected = eval("np.%s(np_x)" % self.op_type)
            self.assertEqual(result, expected)
87 88 89 90 91 92 93 94 95 96

    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)
            self.assertEqual(z, z_expected)


C
chengduo 已提交
97
class TestSigmoid(TestActivation):
Q
qijun 已提交
98
    def setUp(self):
99
        paddle.enable_static()
Q
qijun 已提交
100
        self.op_type = "sigmoid"
101 102
        self.init_dtype()

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

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

110 111 112
    def init_dtype(self):
        self.dtype = np.float32

113
    def test_check_grad(self):
114 115 116 117
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.01)

118

C
chengduo 已提交
119
class TestLogSigmoid(TestActivation):
120
    def setUp(self):
121
        paddle.enable_static()
122
        self.op_type = "logsigmoid"
123 124
        self.init_dtype()

125
        np.random.seed(2048)
126 127 128
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = np.log(1 / (1 + np.exp(-x)))

129
        self.inputs = {'X': x}
130
        self.outputs = {'Out': out}
131 132

    def test_check_grad(self):
133 134
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
135
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
136 137


138
class TestLogSigmoidAPI(unittest.TestCase):
139
    # test paddle.nn.LogSigmoid, paddle.nn.functional.log_sigmoid
140
    def setUp(self):
141
        np.random.seed(1024)
142 143 144 145 146
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
147
        paddle.enable_static()
148 149
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [11, 17])
150
            out1 = F.log_sigmoid(x)
151 152 153 154 155 156
            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:
157
            self.assertTrue(np.allclose(out_ref, r))
158 159 160 161

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
162
        out1 = F.log_sigmoid(x)
163 164 165 166
        m = paddle.nn.LogSigmoid()
        out2 = m(x)
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in [out1, out2]:
167
            self.assertTrue(np.allclose(out_ref, r.numpy()))
168 169
        paddle.enable_static()

170
    def test_fluid_api(self):
171
        paddle.enable_static()
172 173 174 175 176 177 178 179
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [11, 17])
            out = paddle.fluid.layers.logsigmoid(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        self.assertTrue(np.allclose(out_ref, res[0]))

180
    def test_errors(self):
181
        paddle.enable_static()
182 183
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
184
            self.assertRaises(TypeError, F.log_sigmoid, 1)
185 186
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.data(name='x_int32', shape=[11, 17], dtype='int32')
187
            self.assertRaises(TypeError, F.log_sigmoid, x_int32)
188 189
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[11, 17], dtype='float16')
190
            F.log_sigmoid(x_fp16)
191 192


193
class TestTanh(TestActivation, TestParameter):
194
    def setUp(self):
195
        paddle.enable_static()
196
        self.op_type = "tanh"
197
        self.init_dtype()
198
        np.random.seed(1024)
199 200 201 202 203
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.tanh(x)

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

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

210 211 212 213 214 215
    def init_dtype(self):
        #TODO If dtype is float64, the output (Out) has diff at CPUPlace
        # when using and not using inplace. Therefore, set dtype as float32
        # for now.
        self.dtype = np.float32

216

W
WangXi 已提交
217 218 219 220
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
221
        np.random.seed(1024)
W
WangXi 已提交
222 223 224 225 226
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
227
        paddle.enable_static()
W
WangXi 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12], self.dtype)
            out1 = F.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:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
241
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
242 243 244 245 246 247 248 249 250 251
        out1 = F.tanh(x)
        out2 = paddle.tanh(x)
        th = paddle.nn.Tanh()
        out3 = th(x)
        out_ref = np.tanh(self.x_np)
        for r in [out1, out2, out3]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
252
        paddle.enable_static()
W
WangXi 已提交
253 254 255 256 257 258 259 260 261
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12], self.dtype)
            out = fluid.layers.tanh(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = np.tanh(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
262
        paddle.enable_static()
W
WangXi 已提交
263 264 265 266 267 268 269 270 271 272 273
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.tanh, 1)
            # The input dtype must be float16, float32.
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.tanh, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.tanh(x_fp16)


274
class TestAtan(TestActivation, TestParameter):
275
    def setUp(self):
276
        paddle.enable_static()
277 278 279
        self.op_type = "atan"
        self.init_dtype()

280
        np.random.seed(1024)
281 282 283 284 285 286 287 288 289
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.arctan(x)

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

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

W
WuHaobo 已提交
292 293 294 295 296 297 298 299 300 301 302
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
            np_x = np.array([0.1])
            data = fluid.layers.data(name="X", shape=[1])
            out = paddle.atan(data, name='Y')
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(feed={"X": np_x}, fetch_list=[out])
            expected = np.arctan(np_x)
            self.assertEqual(result, expected)

303 304 305 306 307 308 309 310
    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)

311

312 313
class TestSinh(TestActivation):
    def setUp(self):
314
        paddle.enable_static()
315 316 317
        self.op_type = "sinh"
        self.init_dtype()

318
        np.random.seed(1024)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.sinh(x)

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

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

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

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

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

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

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


class TestSinhOpError(unittest.TestCase):
    def test_errors(self):
374
        paddle.enable_static()
375 376 377 378 379 380 381 382 383 384 385 386 387
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.sinh, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.sinh, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.sinh(x_fp16)


class TestCosh(TestActivation):
    def setUp(self):
388
        paddle.enable_static()
389 390 391
        self.op_type = "cosh"
        self.init_dtype()

392
        np.random.seed(1024)
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.cosh(x)

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

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

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

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

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

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

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


class TestCoshOpError(unittest.TestCase):
    def test_errors(self):
448
        paddle.enable_static()
449 450 451 452 453 454 455 456 457 458 459
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.cosh, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.cosh, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.cosh(x_fp16)


460 461 462 463 464 465
def ref_tanhshrink(x):
    out = x - np.tanh(x)
    return out


class TestTanhshrink(TestActivation):
K
Kavya Srinet 已提交
466
    def setUp(self):
467
        paddle.enable_static()
K
Kavya Srinet 已提交
468
        self.op_type = "tanh_shrink"
469 470
        self.init_dtype()

471
        np.random.seed(1024)
472 473
        x = np.random.uniform(10, 20, [10, 17]).astype(self.dtype)
        out = ref_tanhshrink(x)
474

475
        self.inputs = {'X': x}
476
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
477 478

    def test_check_grad(self):
479 480
        if self.dtype == np.float16:
            return
481
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
482

483

484 485 486
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
487
        np.random.seed(1024)
488 489 490 491 492
        self.x_np = np.random.uniform(10, 20, [10, 17]).astype(np.float64)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
493
        paddle.enable_static()
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', self.x_np.shape, self.x_np.dtype)
            out1 = F.tanhshrink(x)
            tanhshrink = paddle.nn.Tanhshrink()
            out2 = tanhshrink(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_tanhshrink(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
517
        paddle.enable_static()
518 519 520 521 522 523 524 525 526
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.tanh_shrink(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_tanhshrink(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
527
        paddle.enable_static()
528 529 530 531 532 533 534 535 536 537 538
        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.
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.tanhshrink, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.tanhshrink(x_fp16)


539 540 541 542 543 544
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
545
class TestHardShrink(TestActivation):
546
    def setUp(self):
547
        paddle.enable_static()
548
        self.op_type = "hard_shrink"
549 550
        self.init_dtype()

551 552
        self.threshold = 0.5
        self.set_attrs()
553
        np.random.seed(1024)
Z
zhupengyang 已提交
554
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype) * 10
555
        out = ref_hardshrink(x, self.threshold)
556

557
        self.attrs = {'threshold': self.threshold}
558
        self.inputs = {'X': x}
559
        self.outputs = {'Out': out}
560

561 562 563
    def set_attrs(self):
        pass

564
    def test_check_grad(self):
565 566
        if self.dtype == np.float16:
            return
567
        self.check_grad(['X'], 'Out')
568 569


570 571 572 573 574
class TestHardShrink_threshold_negative(TestHardShrink):
    def set_attrs(self):
        self.threshold = -0.1


575 576 577
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
578
        paddle.enable_static()
579
        np.random.seed(1024)
580 581 582 583 584
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
585
        paddle.enable_static()
586 587 588 589 590 591 592 593 594 595 596 597 598
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.hardshrink(x)
            hd = paddle.nn.Hardshrink()
            out2 = hd(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardshrink(self.x_np, 0.5)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
599
        x = paddle.to_tensor(self.x_np)
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
        out1 = F.hardshrink(x)
        hd = paddle.nn.Hardshrink()
        out2 = hd(x)
        out_ref = ref_hardshrink(self.x_np, 0.5)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

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

    def test_fluid_api(self):
616
        paddle.enable_static()
617 618 619 620 621 622 623 624
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
            out = fluid.layers.hard_shrink(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardshrink(self.x_np, 0.5)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

625
    def test_errors(self):
626
        paddle.enable_static()
627
        with paddle.static.program_guard(paddle.static.Program()):
628
            # The input type must be Variable.
629
            self.assertRaises(TypeError, F.hardshrink, 1)
630
            # The input dtype must be float16, float32, float64.
631 632
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.hardshrink, x_int32)
633
            # support the input dtype is float16
634 635
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.hardshrink(x_fp16)
636 637


638 639 640 641 642 643 644 645 646 647 648
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):
649
        np.random.seed(1024)
650 651 652 653 654
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
655
        paddle.enable_static()
656 657 658 659 660 661 662 663 664 665 666 667 668
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.hardtanh(x)
            m = paddle.nn.Hardtanh()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardtanh(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
669
        x = paddle.to_tensor(self.x_np)
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        out1 = F.hardtanh(x)
        m = paddle.nn.Hardtanh()
        out2 = m(x)
        out_ref = ref_hardtanh(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

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

    def test_errors(self):
686
        paddle.enable_static()
687 688 689 690 691 692 693 694 695 696 697
        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.
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.hardtanh(x_fp16)


698 699 700 701 702 703 704 705
def ref_softshrink(x, threshold=0.5):
    out = np.copy(x)
    out = (out < -threshold) * (out + threshold) + (out > threshold) * (
        out - threshold)
    return out


class TestSoftshrink(TestActivation):
706
    def setUp(self):
707
        paddle.enable_static()
708
        self.op_type = "softshrink"
709 710
        self.init_dtype()

711
        threshold = 0.8
712

713
        np.random.seed(1023)
714 715 716 717
        x = np.random.uniform(0.25, 10, [10, 12]).astype(self.dtype)
        out = ref_softshrink(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"lambda": threshold}
718
        self.outputs = {'Out': out}
719 720

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

725

726 727 728 729
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
730
        np.random.seed(1024)
731 732 733 734 735
        self.x_np = np.random.uniform(0.25, 10, [10, 12]).astype(np.float64)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
736
        paddle.enable_static()
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', self.x_np.shape, self.x_np.dtype)
            out1 = F.softshrink(x, self.threshold)
            softshrink = paddle.nn.Softshrink(self.threshold)
            out2 = softshrink(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_softshrink(self.x_np, self.threshold)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
760
        paddle.enable_static()
761 762 763 764 765 766 767 768
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.softshrink(x, self.threshold)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_softshrink(self.x_np, self.threshold)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

769
    def test_errors(self):
770
        paddle.enable_static()
771
        with paddle.static.program_guard(paddle.static.Program()):
772
            # The input type must be Variable.
773
            self.assertRaises(TypeError, F.softshrink, 1)
774
            # The input dtype must be float16, float32, float64.
775 776
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.softshrink, x_int32)
777 778 779
            # The threshold must be no less than zero
            x_fp32 = paddle.data(name='x_fp32', shape=[12, 10], dtype='float32')
            self.assertRaises(ValueError, F.softshrink, x_fp32, -1.0)
780
            # support the input dtype is float16
781 782
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.softshrink(x_fp16)
783 784


785
class TestSqrt(TestActivation, TestParameter):
786
    def setUp(self):
787
        paddle.enable_static()
788
        self.op_type = "sqrt"
789 790
        self.init_dtype()

791
        np.random.seed(1023)
792 793 794 795 796
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.sqrt(x)

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

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

803

Z
zhoukunsheng 已提交
804 805
class TestRsqrt(TestActivation):
    def setUp(self):
806
        paddle.enable_static()
Z
zhoukunsheng 已提交
807 808 809
        self.op_type = "rsqrt"
        self.init_dtype()

810
        np.random.seed(1024)
Z
zhupengyang 已提交
811
        x = np.random.uniform(0.1, 1, [10, 12]).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
812 813 814 815 816 817 818 819 820 821 822
        out = 1.0 / np.sqrt(x)

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

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


C
chengduo 已提交
823
class TestAbs(TestActivation):
824
    def setUp(self):
825
        paddle.enable_static()
826
        self.op_type = "abs"
827 828
        self.init_dtype()

829
        np.random.seed(1024)
830
        x = np.random.uniform(-1, 1, [4, 25]).astype(self.dtype)
C
chengduo 已提交
831
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
832
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
833
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
834 835
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
836 837 838 839
        out = np.abs(x)

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

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

846

C
chengduo 已提交
847
class TestCeil(TestActivation):
D
dzhwinter 已提交
848
    def setUp(self):
849
        paddle.enable_static()
D
dzhwinter 已提交
850
        self.op_type = "ceil"
851 852
        self.init_dtype()

853
        np.random.seed(1024)
Z
zhupengyang 已提交
854
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
855 856 857 858
        out = np.ceil(x)

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

D
dzhwinter 已提交
860
    # The same reason with TestFloor
C
chengduo 已提交
861
    def test_check_grad(self):
862 863 864
        pass


C
chengduo 已提交
865
class TestFloor(TestActivation):
D
dzhwinter 已提交
866
    def setUp(self):
867
        paddle.enable_static()
D
dzhwinter 已提交
868
        self.op_type = "floor"
869 870
        self.init_dtype()

871
        np.random.seed(1024)
Z
zhupengyang 已提交
872
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
873 874 875 876
        out = np.floor(x)

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

D
dzhwinter 已提交
878
    # the gradient on floor, ceil, round is undefined.
879
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
880 881
    # The same reason with TestFloor
    def test_check_grad(self):
882 883 884
        pass


C
chengduo 已提交
885
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
886
    def setUp(self):
887
        paddle.enable_static()
C
add cos  
chengduoZH 已提交
888
        self.op_type = "cos"
889 890
        self.init_dtype()

891
        np.random.seed(1024)
Z
zhupengyang 已提交
892
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
893 894 895 896
        out = np.cos(x)

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

    def test_check_grad(self):
899 900
        if self.dtype == np.float16:
            return
901
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
902

903

904 905
class TestAcos(TestActivation):
    def setUp(self):
906
        paddle.enable_static()
907 908 909
        self.op_type = "acos"
        self.init_dtype()

910
        np.random.seed(1024)
Z
zhupengyang 已提交
911
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
912 913 914 915 916 917 918 919
        out = np.arccos(x)

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

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


923
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
924
    def setUp(self):
925
        paddle.enable_static()
C
add sin  
chengduoZH 已提交
926
        self.op_type = "sin"
927 928
        self.init_dtype()

929
        np.random.seed(1024)
Z
zhupengyang 已提交
930
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
931 932 933 934
        out = np.sin(x)

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

    def test_check_grad(self):
937 938
        if self.dtype == np.float16:
            return
939
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
940 941


942 943
class TestAsin(TestActivation):
    def setUp(self):
944
        paddle.enable_static()
945 946 947
        self.op_type = "asin"
        self.init_dtype()

948
        np.random.seed(2048)
Z
zhupengyang 已提交
949
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
950 951 952 953 954 955 956 957
        out = np.arcsin(x)

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

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


C
chengduo 已提交
961
class TestRound(TestActivation):
D
dzhwinter 已提交
962
    def setUp(self):
963
        paddle.enable_static()
D
dzhwinter 已提交
964
        self.op_type = "round"
965 966
        self.init_dtype()

967
        np.random.seed(1024)
Z
zhupengyang 已提交
968
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
969 970 971 972
        out = np.round(x)

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

C
chengduo 已提交
974
    def test_check_grad(self):
975 976 977
        pass


C
chengduo 已提交
978
class TestRelu(TestActivation):
979
    def setUp(self):
980
        paddle.enable_static()
Q
qijun 已提交
981
        self.op_type = "relu"
K
Kexin Zhao 已提交
982 983
        self.init_dtype()

984
        np.random.seed(1024)
K
Kexin Zhao 已提交
985
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
Q
qijun 已提交
986 987
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.02
K
Kexin Zhao 已提交
988 989
        out = np.maximum(x, 0)

990
        self.inputs = {'X': x}
K
Kexin Zhao 已提交
991
        self.outputs = {'Out': out}
992 993

    def test_check_grad(self):
K
Kexin Zhao 已提交
994 995
        if self.dtype == np.float16:
            return
996
        self.check_grad(['X'], 'Out')
A
Adam 已提交
997 998


999 1000 1001
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1002
        np.random.seed(1024)
1003 1004 1005 1006 1007
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1008
        paddle.enable_static()
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.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:
            self.assertEqual(np.allclose(out_ref, r), True)

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

1031
    def test_errors(self):
1032
        paddle.enable_static()
1033
        with paddle.static.program_guard(paddle.static.Program()):
1034
            # The input type must be Variable.
1035
            self.assertRaises(TypeError, F.relu, 1)
1036
            # The input dtype must be float16, float32, float64.
1037 1038
            x_int32 = paddle.data(name='x_int32', shape=[10, 12], dtype='int32')
            self.assertRaises(TypeError, F.relu, x_int32)
1039
            # support the input dtype is float16
1040 1041
            x_fp16 = paddle.data(name='x_fp16', shape=[10, 12], dtype='float16')
            F.relu(x_fp16)
1042 1043


1044 1045 1046 1047 1048 1049
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1050
class TestLeakyRelu(TestActivation):
1051 1052 1053
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1054
    def setUp(self):
1055
        paddle.enable_static()
A
Adam 已提交
1056 1057
        self.op_type = "leaky_relu"
        self.init_dtype()
1058
        alpha = self.get_alpha()
A
Adam 已提交
1059

1060
        np.random.seed(1024)
A
Adam 已提交
1061 1062
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        # The same reason with TestAbs
1063 1064
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1065

1066
        self.inputs = {'X': x}
A
Adam 已提交
1067
        self.outputs = {'Out': out}
1068
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1069 1070 1071 1072

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


1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
class TestLeakyReluAlpha1(TestLeakyRelu):
    def get_alpha(self):
        return 2


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


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


class TestLeakyReluAPI(unittest.TestCase):
    # test paddle.nn.LeakyReLU, paddle.nn.functional.leaky_relu,
    # fluid.layers.leaky_relu
    def setUp(self):
1095
        np.random.seed(1024)
1096 1097 1098 1099 1100
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1101
        paddle.enable_static()
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.leaky_relu(x)
            m = paddle.nn.LeakyReLU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_leaky_relu(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
Z
Zhou Wei 已提交
1115
        x = paddle.to_tensor(self.x_np)
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
        out1 = F.leaky_relu(x)
        m = paddle.nn.LeakyReLU()
        out2 = m(x)
        out_ref = ref_leaky_relu(self.x_np)
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)

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

    def test_fluid_api(self):
1132
        paddle.enable_static()
1133 1134 1135 1136 1137 1138 1139 1140
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
            out = fluid.layers.leaky_relu(x, 0.01)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_leaky_relu(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

1141
    def test_errors(self):
1142
        paddle.enable_static()
1143
        with paddle.static.program_guard(paddle.static.Program()):
1144
            # The input type must be Variable.
1145
            self.assertRaises(TypeError, F.leaky_relu, 1)
1146
            # The input dtype must be float16, float32, float64.
1147 1148 1149 1150 1151
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.leaky_relu(x_fp16)
1152 1153


1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
def gelu(x, approximate):
    if approximate:
        y_ref = 0.5 * x * (1.0 + np.tanh(
            np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
    else:
        y_ref = 0.5 * x * (1 + erf(x / np.sqrt(2)))
    return y_ref.astype(x.dtype)


class TestGeluApproximate(TestActivation):
C
Clementine 已提交
1164
    def setUp(self):
1165
        paddle.enable_static()
C
Clementine 已提交
1166 1167
        self.op_type = "gelu"
        self.init_dtype()
1168
        approximate = True
1169
        np.random.seed(1024)
1170 1171
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
1172

1173
        self.inputs = {'X': x}
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        self.outputs = {'Out': out}
        self.attrs = {"approximate": approximate}

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


class TestGelu(TestActivation):
    def setUp(self):
1185
        paddle.enable_static()
1186 1187 1188
        self.op_type = "gelu"
        self.init_dtype()
        approximate = False
1189
        np.random.seed(2048)
C
Clementine 已提交
1190
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1191
        out = gelu(x, approximate)
C
Clementine 已提交
1192

1193
        self.inputs = {'X': x}
C
Clementine 已提交
1194
        self.outputs = {'Out': out}
1195
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1196 1197 1198 1199

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


1203 1204 1205
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1206
        np.random.seed(1024)
1207 1208 1209 1210 1211
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1212
        paddle.enable_static()
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [11, 17])
            out1 = F.gelu(x)
            m = paddle.nn.GELU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = gelu(self.x_np, False)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

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

    def test_errors(self):
1243
        paddle.enable_static()
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
        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.
            x_int32 = paddle.data(name='x_int32', shape=[11, 17], dtype='int32')
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[11, 17], dtype='float16')
            F.gelu(x_fp16)


C
chengduo 已提交
1255
class TestBRelu(TestActivation):
1256
    def setUp(self):
1257
        paddle.enable_static()
1258
        self.op_type = "brelu"
1259 1260
        self.init_dtype()

1261
        np.random.seed(1024)
Z
zhupengyang 已提交
1262
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1263 1264
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
1265 1266
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
1267
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
1268 1269 1270
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
1271 1272 1273

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

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

1281

1282 1283
class TestBReluOpError(unittest.TestCase):
    def test_errors(self):
1284
        paddle.enable_static()
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.brelu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.brelu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.layers.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.brelu(x_fp16)


1297 1298 1299 1300 1301 1302 1303
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 已提交
1304
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
1305
    def setUp(self):
1306
        paddle.enable_static()
1307
        self.op_type = "relu6"
1308 1309
        self.init_dtype()

1310
        np.random.seed(1024)
Z
zhupengyang 已提交
1311
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
1312
        x[np.abs(x) < 0.005] = 0.02
1313
        out = ref_relu6(x)
1314

1315 1316
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
1317
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
1318

1319 1320 1321
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1322
        self.check_grad(['X'], 'Out')
1323 1324


1325 1326 1327
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
1328
        np.random.seed(1024)
1329 1330 1331 1332 1333 1334
        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
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1335
        paddle.enable_static()
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', self.x_np.shape, self.x_np.dtype)
            out1 = F.relu6(x)
            relu6 = paddle.nn.ReLU6()
            out2 = relu6(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_relu6(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
1359
        paddle.enable_static()
1360 1361 1362 1363 1364 1365 1366 1367
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.relu6(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_relu6(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

1368
    def test_errors(self):
1369
        paddle.enable_static()
1370
        with paddle.static.program_guard(paddle.static.Program()):
1371
            # The input type must be Variable.
1372
            self.assertRaises(TypeError, F.relu6, 1)
1373
            # The input dtype must be float16, float32, float64.
1374 1375
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.relu6, x_int32)
1376
            # support the input dtype is float16
1377 1378
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.relu6(x_fp16)
1379 1380


H
huangjun12 已提交
1381 1382
class TestHardSwish(TestActivation):
    def setUp(self):
1383
        paddle.enable_static()
H
huangjun12 已提交
1384 1385 1386
        self.op_type = 'hard_swish'
        self.init_dtype()

1387
        np.random.seed(1024)
Z
zhupengyang 已提交
1388
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
        threshold = 6.0
        scale = 6.0
        offset = 3.0
        #the same with TestAbs
        x[np.abs(x + offset) < 0.005] = 0.02
        x[np.abs(x - threshold + offset) < 0.005] = threshold - offset + 0.02
        out = x * np.minimum(np.maximum(x + offset, 0), threshold) / scale

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
        self.outputs = {'Out': out}

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


1407 1408
class TestHardSwishOpError(unittest.TestCase):
    def test_errors(self):
1409
        paddle.enable_static()
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hard_swish, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.hard_swish, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.hard_swish(x_fp16)


C
chengduo 已提交
1421
class TestSoftRelu(TestActivation):
1422
    def setUp(self):
1423
        paddle.enable_static()
1424
        self.op_type = "soft_relu"
1425 1426
        self.init_dtype()

1427
        np.random.seed(4096)
1428
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1429
        threshold = 2.0
Q
qijun 已提交
1430 1431
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
1432
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
1433 1434 1435
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
1436 1437 1438 1439 1440
        out = np.log((np.exp(t) + 1))

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

    def test_check_grad(self):
1443 1444
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1445
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
1446

1447

1448 1449
class TestSoftReluOpError(unittest.TestCase):
    def test_errors(self):
1450
        paddle.enable_static()
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.soft_relu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.soft_relu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.soft_relu(x_fp16)


1462 1463 1464 1465 1466
def elu(x, alpha):
    out_ref = np.maximum(0, x) + np.minimum(0, alpha * (np.exp(x) - 1))
    return out_ref.astype(x.dtype)


C
chengduo 已提交
1467
class TestELU(TestActivation):
1468
    def setUp(self):
1469
        paddle.enable_static()
1470
        self.op_type = "elu"
1471 1472
        self.init_dtype()

1473
        np.random.seed(1024)
Z
zhupengyang 已提交
1474
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
1475
        alpha = 1.
1476
        out = elu(x, alpha)
1477 1478 1479 1480
        # Note: unlike other Relu extensions, point 0 on standard ELU function (i.e. alpha = 1)
        # is differentiable, so we can skip modifications like x[np.abs(x) < 0.005] = 0.02 here
        self.inputs = {'X': x}
        self.attrs = {'alpha': alpha}
1481
        self.outputs = {'Out': out}
1482 1483

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


1489 1490 1491
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
1492
        np.random.seed(1024)
1493 1494 1495 1496 1497
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1498
        paddle.enable_static()
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.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:
            self.assertEqual(np.allclose(out_ref, r), True)

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

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

1528
    def test_errors(self):
1529
        paddle.enable_static()
1530 1531 1532 1533 1534 1535 1536 1537 1538
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.elu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.data(name='x_int32', shape=[10, 12], dtype='int32')
            self.assertRaises(TypeError, F.elu, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[10, 12], dtype='float16')
            F.elu(x_fp16)
1539 1540


C
chengduo 已提交
1541
class TestReciprocal(TestActivation):
Q
qijun 已提交
1542
    def setUp(self):
1543
        paddle.enable_static()
Q
qijun 已提交
1544
        self.op_type = "reciprocal"
1545 1546
        self.init_dtype()

1547
        np.random.seed(1024)
1548 1549 1550 1551 1552
        x = np.random.uniform(1, 2, [11, 17]).astype(self.dtype)
        out = np.reciprocal(x)

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

    def test_check_grad(self):
1555 1556
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1557
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Q
qijun 已提交
1558 1559


C
chengduo 已提交
1560
class TestLog(TestActivation):
Q
qijun 已提交
1561
    def setUp(self):
1562
        paddle.enable_static()
Q
qijun 已提交
1563
        self.op_type = "log"
1564 1565
        self.init_dtype()

1566
        np.random.seed(1024)
1567 1568 1569 1570 1571
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log(x)

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

    def test_check_grad(self):
1574 1575
        if self.dtype == np.float16:
            return
1576
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1577

1578 1579 1580 1581 1582 1583 1584 1585 1586
    def test_error(self):
        in1 = fluid.layers.data(
            name="in1", shape=[11, 17], append_batch_size=False, dtype="int32")
        in2 = fluid.layers.data(
            name="in2", shape=[11, 17], append_batch_size=False, dtype="int64")

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

1587

1588 1589
class TestLog1p(TestActivation):
    def setUp(self):
1590
        paddle.enable_static()
1591 1592 1593
        self.op_type = "log1p"
        self.init_dtype()

1594
        np.random.seed(1024)
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log1p(x)

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

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

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

            out1 = paddle.log1p(data_x)
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
1618 1619 1620
            res1 = exe.run(fluid.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
1621
        expected_res = np.log1p(input_x)
1622
        self.assertTrue(np.allclose(res1, expected_res))
1623 1624 1625 1626 1627 1628 1629 1630

        # 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))
1631
        self.assertTrue(np.allclose(np_z, z_expected))
1632 1633


C
chengduo 已提交
1634
class TestSquare(TestActivation):
Q
qijun 已提交
1635
    def setUp(self):
1636
        paddle.enable_static()
Q
qijun 已提交
1637
        self.op_type = "square"
1638 1639
        self.init_dtype()

1640
        np.random.seed(1024)
1641 1642 1643 1644 1645
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.square(x)

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

    def test_check_grad(self):
1648 1649
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1650
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
Q
qijun 已提交
1651

1652

C
chengduo 已提交
1653
class TestPow(TestActivation):
1654
    def setUp(self):
1655
        paddle.enable_static()
1656
        self.op_type = "pow"
1657 1658
        self.init_dtype()

1659
        np.random.seed(1024)
1660 1661 1662 1663
        x = np.random.uniform(1, 2, [11, 17]).astype(self.dtype)
        out = np.power(x, 3)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
Y
Yang Yang(Tony) 已提交
1664
        self.attrs = {'factor': 3.0}
1665
        self.outputs = {'Out': out}
1666 1667

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

1672

1673 1674
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
1675
        paddle.enable_static()
1676 1677 1678
        self.op_type = "pow"
        self.init_dtype()

1679
        np.random.seed(1024)
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
        x = np.random.uniform(1, 2, [11, 17]).astype(self.dtype)
        out = np.power(x, 3)

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

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

    def test_check_output(self):
        self.check_output()

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

    def test_api(self):
        input = np.random.uniform(1, 2, [11, 17]).astype("float32")
        x = fluid.layers.data(
            name="x", shape=[11, 17], append_batch_size=False, dtype="float32")
1703 1704 1705 1706 1707
        res = fluid.layers.data(
            name="res",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
1708 1709 1710 1711 1712

        factor_1 = 2.0
        factor_2 = fluid.layers.fill_constant([1], "float32", 3.0)
        out_1 = fluid.layers.pow(x, factor=factor_1)
        out_2 = fluid.layers.pow(x, factor=factor_2)
1713 1714 1715
        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)
1716 1717

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
1718
        res_1, res_2, res, res_6 = exe.run(
1719 1720
            fluid.default_main_program(),
            feed={"x": input},
W
WuHaobo 已提交
1721
            fetch_list=[out_1, out_2, res, out_6])
1722 1723 1724

        assert np.array_equal(res_1, np.power(input, 2))
        assert np.array_equal(res_2, np.power(input, 3))
1725
        assert np.array_equal(res_6, np.power(input, 3))
1726

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
    def test_error(self):
        in1 = fluid.layers.data(
            name="in1", shape=[11, 17], append_batch_size=False, dtype="int32")
        in2 = fluid.layers.data(
            name="in2", shape=[11, 17], append_batch_size=False, dtype="int64")
        in3 = fluid.layers.data(
            name="in3",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
        in4 = fluid.layers.data(
            name="in4",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float64")

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

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

1750

C
chengduo 已提交
1751
class TestSTanh(TestActivation):
1752
    def setUp(self):
1753
        paddle.enable_static()
1754
        self.op_type = "stanh"
1755 1756
        self.init_dtype()

1757
        np.random.seed(1024)
1758
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
1759 1760
        scale_a = 2.0 / 3.0
        scale_b = 1.7159
1761 1762 1763
        out = scale_b * np.tanh(x * scale_a)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
1764
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
1765
        self.outputs = {'Out': out}
1766

Q
qijun 已提交
1767
    def test_check_grad(self):
1768 1769
        if self.dtype == np.float16:
            return
1770
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1771

1772

1773 1774
class TestSTanhOpError(unittest.TestCase):
    def test_errors(self):
1775
        paddle.enable_static()
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.stanh, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.stanh, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.stanh(x_fp16)


1787 1788 1789 1790 1791 1792 1793
def ref_softplus(x, beta=1, threshold=20):
    x_beta = beta * x
    out = np.select([x_beta <= threshold, x_beta > threshold],
                    [np.log(1 + np.exp(x_beta)) / beta, x])
    return out


C
chengduo 已提交
1794
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
1795
    def setUp(self):
1796
        paddle.enable_static()
K
kexinzhao 已提交
1797
        self.op_type = "softplus"
1798 1799
        self.init_dtype()

1800 1801
        beta = 2
        threshold = 15
1802

1803
        np.random.seed(1024)
1804 1805 1806 1807
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softplus(x, beta, threshold)
        self.inputs = {'X': x}
        self.attrs = {'beta': beta, "threshold": threshold}
1808
        self.outputs = {'Out': out}
K
kexinzhao 已提交
1809 1810

    def test_check_grad(self):
1811 1812
        if self.dtype == np.float16:
            return
1813
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
1814

1815

1816 1817 1818 1819 1820
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
1821
        np.random.seed(1024)
1822 1823 1824 1825 1826
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1827
        paddle.enable_static()
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', self.x_np.shape, self.x_np.dtype)
            out1 = F.softplus(x, self.beta, self.threshold)
            softplus = paddle.nn.Softplus(self.beta, self.threshold)
            out2 = softplus(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_softplus(self.x_np, self.beta, self.threshold)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
1851
        paddle.enable_static()
1852 1853 1854 1855 1856 1857 1858 1859 1860
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.softplus(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_softplus(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
1861
        paddle.enable_static()
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
        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.
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.softplus(x_fp16)


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


C
chengduo 已提交
1878
class TestSoftsign(TestActivation):
1879
    def setUp(self):
1880
        paddle.enable_static()
1881
        self.op_type = "softsign"
1882 1883
        self.init_dtype()

1884
        np.random.seed(1024)
1885 1886 1887
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softsign(x)
        self.inputs = {'X': x}
1888
        self.outputs = {'Out': out}
1889 1890

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


1896 1897 1898
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
1899
        np.random.seed(1024)
1900 1901 1902 1903 1904
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
1905
        paddle.enable_static()
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', self.x_np.shape, self.x_np.dtype)
            out1 = F.softsign(x)
            softsign = paddle.nn.Softsign()
            out2 = softsign(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_softsign(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
1929
        paddle.enable_static()
1930 1931 1932 1933 1934 1935 1936 1937 1938
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.softsign(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_softsign(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_errors(self):
1939
        paddle.enable_static()
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
        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.
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.softsign(x_fp16)


C
chengduo 已提交
1951
class TestThresholdedRelu(TestActivation):
1952
    def setUp(self):
1953
        paddle.enable_static()
1954
        self.op_type = "thresholded_relu"
1955 1956
        self.init_dtype()

1957
        threshold = 0.25
Z
zhupengyang 已提交
1958
        self.delta = 0.005
1959
        np.random.seed(1024)
1960
        X = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1961 1962

        # Same reason as TestAbs
Z
zhupengyang 已提交
1963
        X[np.abs(X - threshold) < self.delta] = threshold + 0.2
1964
        out = (X > threshold) * X
1965

1966
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(X)}
1967
        self.attrs = {'threshold': threshold}
1968
        self.outputs = {'Out': out}
1969 1970

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


1976 1977
class TestThresholdedReluOpError(unittest.TestCase):
    def test_errors(self):
1978
        paddle.enable_static()
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.thresholded_relu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.thresholded_relu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.thresholded_relu(x_fp16)


C
chengduo 已提交
1990
class TestHardSigmoid(TestActivation):
1991
    def setUp(self):
1992
        paddle.enable_static()
1993
        self.op_type = "hard_sigmoid"
1994 1995
        self.init_dtype()

1996
        np.random.seed(1024)
Z
zhupengyang 已提交
1997
        X = np.random.uniform(-5, 5, [10, 12]).astype("float32")
1998 1999 2000 2001 2002
        slope = 0.2
        offset = 0.5
        lower_threshold = -offset / slope
        upper_threshold = (1 - offset) / slope

Z
zhupengyang 已提交
2003 2004
        self.delta = 0.005

2005
        # Same reason as TestAbs
Z
zhupengyang 已提交
2006 2007
        X[(X - lower_threshold) < self.delta] = lower_threshold - 0.02
        X[(X - upper_threshold) < self.delta] = upper_threshold + 0.02
2008 2009

        temp = X * slope + offset
2010 2011 2012 2013
        out = np.maximum(0.0, np.minimum(1.0, temp))

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

    def test_check_grad(self):
2016 2017
        if self.dtype == np.float16:
            return
Z
zhupengyang 已提交
2018
        self.check_grad(['X'], 'Out')
2019

2020

2021 2022
class TestHardSigmoidOpError(unittest.TestCase):
    def test_errors(self):
2023
        paddle.enable_static()
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hard_sigmoid, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.hard_sigmoid, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.hard_sigmoid(x_fp16)


C
chengduo 已提交
2035
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
2036
    def setUp(self):
2037
        paddle.enable_static()
A
Abhinav Arora 已提交
2038
        self.op_type = "swish"
2039 2040
        self.init_dtype()

2041
        np.random.seed(1024)
2042 2043 2044 2045 2046 2047 2048
        X = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        beta = 2.3
        out = X * expit(beta * X)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(X)}
        self.attrs = {'beta': beta}
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
2049 2050

    def test_check_grad(self):
2051 2052
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
2053
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
A
Abhinav Arora 已提交
2054

2055

2056 2057
class TestSwishOpError(unittest.TestCase):
    def test_errors(self):
2058
        paddle.enable_static()
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.swish, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.swish, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.swish(x_fp16)


2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
#------------------ Test Error Activation----------------------
def create_test_error_class(op_type):
    class TestOpErrors(unittest.TestCase):
        def test_errors(self):
            with program_guard(Program(), Program()):
                op = getattr(fluid.layers, op_type)
                # The input dtype of op_type must be float32, float64.
                in1 = fluid.layers.data(
                    name='input2', shape=[12, 10], dtype="int32")
                in2 = fluid.layers.data(
                    name='input3', shape=[12, 10], dtype="int64")
                self.assertRaises(TypeError, op, in1)
                self.assertRaises(TypeError, op, in2)

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


create_test_error_class('acos')
create_test_error_class('asin')
create_test_error_class('atan')
create_test_error_class('ceil')
create_test_error_class('cos')
create_test_error_class('floor')
create_test_error_class('reciprocal')
create_test_error_class('round')
create_test_error_class('rsqrt')
create_test_error_class('sin')
create_test_error_class('sqrt')
create_test_error_class('tanh')


2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
#------------------ Test Cudnn Activation----------------------
def create_test_act_cudnn_class(parent, atol=1e-3, grad_atol=1e-3):
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActCudnn(parent):
        def init_kernel_type(self):
            self.attrs = {"use_cudnn": True}

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


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


C
chengduo 已提交
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
#------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(parent,
                               atol=1e-3,
                               grad_check=True,
                               grad_atol=0.80):
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16
2132

C
chengduo 已提交
2133
        def test_check_output(self):
2134
            place = core.CUDAPlace(0)
C
chengduo 已提交
2135 2136 2137
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
2138

C
chengduo 已提交
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
        def test_check_grad(self):
            place = core.CUDAPlace(0)
            support_fp16 = core.is_float16_supported(place)
            if support_fp16 and grad_check:
                self.check_grad_with_place(
                    place, ['X'], 'Out', max_relative_error=grad_atol)

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


create_test_act_fp16_class(TestActivation)
create_test_act_fp16_class(TestSigmoid)
create_test_act_fp16_class(TestLogSigmoid)
create_test_act_fp16_class(TestTanh)
2155
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
2156
create_test_act_fp16_class(TestHardShrink)
2157
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
2158 2159 2160 2161 2162
create_test_act_fp16_class(TestSqrt)
create_test_act_fp16_class(TestAbs)
create_test_act_fp16_class(TestCeil, grad_check=False)
create_test_act_fp16_class(TestFloor, grad_check=False)
create_test_act_fp16_class(TestCos, grad_atol=0.85)
2163
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
2164
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
2165
create_test_act_fp16_class(TestSin)
2166
create_test_act_fp16_class(TestSinh)
2167 2168
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
C
chengduo 已提交
2169 2170
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
2171
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
2172 2173 2174 2175 2176 2177
create_test_act_fp16_class(TestBRelu)
create_test_act_fp16_class(TestRelu6)
create_test_act_fp16_class(TestSoftRelu)
create_test_act_fp16_class(TestELU)
create_test_act_fp16_class(TestReciprocal)
create_test_act_fp16_class(TestLog)
2178
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
2179 2180
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
2181
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
2182 2183 2184 2185 2186 2187
create_test_act_fp16_class(TestSTanh, grad_atol=0.9)
create_test_act_fp16_class(TestSoftplus)
create_test_act_fp16_class(TestSoftsign)
create_test_act_fp16_class(TestThresholdedRelu)
create_test_act_fp16_class(TestHardSigmoid)
create_test_act_fp16_class(TestSwish)
H
huangjun12 已提交
2188
create_test_act_fp16_class(TestHardSwish)
A
Abhinav Arora 已提交
2189

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