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

15 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
paddle.enable_static()

Q
qijun 已提交
30

31
class TestSqrtOpError(unittest.TestCase):
Z
Zhaolong Xing 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of sqrt op must be Variable or numpy.ndarray.
            in1 = 1
            self.assertRaises(TypeError, fluid.layers.sqrt, in1)
            # The input dtype of sqrt op must be float16, float32, float64.
            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 已提交
47
class TestActivation(OpTest):
Q
qijun 已提交
48 49
    def setUp(self):
        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 77
class TestParameter(object):
    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
W
WuHaobo 已提交
78
            np_x = np.array([0.1])
79
            data = fluid.layers.data(name="X", shape=[1])
W
WuHaobo 已提交
80
            out = eval("paddle.%s(data, name='Y')" % self.op_type)
81 82
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
W
WuHaobo 已提交
83 84 85
            result, = exe.run(feed={"X": np_x}, fetch_list=[out])
            expected = eval("np.%s(np_x)" % self.op_type)
            self.assertEqual(result, expected)
86 87 88 89 90 91 92 93 94 95

    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 已提交
96
class TestSigmoid(TestActivation):
Q
qijun 已提交
97 98
    def setUp(self):
        self.op_type = "sigmoid"
99 100
        self.init_dtype()

101
        np.random.seed(1024)
102 103 104 105 106
        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 已提交
107

108 109 110
    def init_dtype(self):
        self.dtype = np.float32

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

116

C
chengduo 已提交
117
class TestLogSigmoid(TestActivation):
118 119
    def setUp(self):
        self.op_type = "logsigmoid"
120 121
        self.init_dtype()

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

126
        self.inputs = {'X': x}
127
        self.outputs = {'Out': out}
128 129

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


135
class TestLogSigmoidAPI(unittest.TestCase):
136
    # test paddle.nn.LogSigmoid, paddle.nn.functional.log_sigmoid
137
    def setUp(self):
138
        np.random.seed(1024)
139 140 141 142 143
        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):
144
        paddle.enable_static()
145
        with paddle.static.program_guard(paddle.static.Program()):
146
            x = paddle.fluid.data('X', [11, 17])
147
            out1 = F.log_sigmoid(x)
148 149 150 151 152 153
            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:
154
            self.assertTrue(np.allclose(out_ref, r))
155 156 157 158

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

167
    def test_fluid_api(self):
168
        paddle.enable_static()
169
        with paddle.static.program_guard(paddle.static.Program()):
170
            x = paddle.fluid.data('X', [11, 17])
171 172 173 174 175 176
            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]))

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


192
class TestTanh(TestActivation, TestParameter):
193 194
    def setUp(self):
        self.op_type = "tanh"
195
        self.init_dtype()
196
        np.random.seed(1024)
197 198 199 200 201
        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}
202 203

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

208 209 210 211 212 213
    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

214

W
WangXi 已提交
215 216 217 218
class TestTanhAPI(unittest.TestCase):
    # test paddle.tanh, paddle.nn.tanh, paddle.nn.functional.tanh
    def setUp(self):
        self.dtype = 'float32'
219
        np.random.seed(1024)
W
WangXi 已提交
220 221 222
        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()
223 224 225 226
        self.executed_api()

    def executed_api(self):
        self.tanh = F.tanh
W
WangXi 已提交
227 228

    def test_static_api(self):
229
        paddle.enable_static()
W
WangXi 已提交
230
        with paddle.static.program_guard(paddle.static.Program()):
231
            x = paddle.fluid.data('X', [10, 12], self.dtype)
232
            out1 = self.tanh(x)
W
WangXi 已提交
233 234 235 236 237 238 239 240 241 242
            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 已提交
243
        x = paddle.to_tensor(self.x_np)
W
WangXi 已提交
244 245 246 247 248 249 250 251 252 253
        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):
254
        paddle.enable_static()
W
WangXi 已提交
255 256 257 258 259 260 261 262 263
        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):
264
        paddle.enable_static()
W
WangXi 已提交
265 266
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
267
            self.assertRaises(TypeError, self.tanh, 1)
W
WangXi 已提交
268
            # The input dtype must be float16, float32.
J
joejiong 已提交
269 270
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
271
            self.assertRaises(TypeError, self.tanh, x_int32)
W
WangXi 已提交
272
            # support the input dtype is float16
J
joejiong 已提交
273 274
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
275 276 277 278 279 280 281
            self.tanh(x_fp16)


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


284
class TestAtan(TestActivation, TestParameter):
285 286 287 288
    def setUp(self):
        self.op_type = "atan"
        self.init_dtype()

289
        np.random.seed(1024)
290 291 292 293 294 295 296 297 298
        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
299
        self.check_grad(['X'], 'Out')
300

W
WuHaobo 已提交
301 302 303 304 305 306 307 308 309 310 311
    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)

312 313 314 315 316 317 318 319
    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)

320

321 322 323 324 325
class TestSinh(TestActivation):
    def setUp(self):
        self.op_type = "sinh"
        self.init_dtype()

326
        np.random.seed(1024)
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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        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):
        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):
        self.op_type = "cosh"
        self.init_dtype()

398
        np.random.seed(1024)
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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        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):
        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)


465 466 467 468 469 470
def ref_tanhshrink(x):
    out = x - np.tanh(x)
    return out


class TestTanhshrink(TestActivation):
K
Kavya Srinet 已提交
471 472
    def setUp(self):
        self.op_type = "tanh_shrink"
473 474
        self.init_dtype()

475
        np.random.seed(1024)
476 477
        x = np.random.uniform(10, 20, [10, 17]).astype(self.dtype)
        out = ref_tanhshrink(x)
478

479
        self.inputs = {'X': x}
480
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
481 482

    def test_check_grad(self):
483 484
        if self.dtype == np.float16:
            return
485
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
486

487

488 489 490
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
491
        np.random.seed(1024)
492 493 494 495 496
        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):
497
        paddle.enable_static()
498
        with paddle.static.program_guard(paddle.static.Program()):
499
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
            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):
521
        paddle.enable_static()
522 523 524 525 526 527 528 529 530
        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):
531
        paddle.enable_static()
532 533 534 535
        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.
J
joejiong 已提交
536 537
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
538 539
            self.assertRaises(TypeError, F.tanhshrink, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
540 541
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
542 543 544
            F.tanhshrink(x_fp16)


545 546 547 548 549 550
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
551
class TestHardShrink(TestActivation):
552 553
    def setUp(self):
        self.op_type = "hard_shrink"
554 555
        self.init_dtype()

556 557
        self.threshold = 0.5
        self.set_attrs()
558
        np.random.seed(1024)
Z
zhupengyang 已提交
559
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype) * 10
560
        out = ref_hardshrink(x, self.threshold)
561

562
        self.attrs = {'threshold': self.threshold}
563
        self.inputs = {'X': x}
564
        self.outputs = {'Out': out}
565

566 567 568
    def set_attrs(self):
        pass

569
    def test_check_grad(self):
570 571
        if self.dtype == np.float16:
            return
572
        self.check_grad(['X'], 'Out')
573 574


575 576 577 578 579
class TestHardShrink_threshold_negative(TestHardShrink):
    def set_attrs(self):
        self.threshold = -0.1


580 581 582
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
583
        np.random.seed(1024)
584 585 586 587 588
        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):
589
        paddle.enable_static()
590
        with paddle.static.program_guard(paddle.static.Program()):
591
            x = paddle.fluid.data('X', [10, 12])
592 593 594 595 596 597 598 599 600 601 602
            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 已提交
603
        x = paddle.to_tensor(self.x_np)
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        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):
620
        paddle.enable_static()
621 622 623 624 625 626 627 628
        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)

629
    def test_errors(self):
630
        paddle.enable_static()
631
        with paddle.static.program_guard(paddle.static.Program()):
632
            # The input type must be Variable.
633
            self.assertRaises(TypeError, F.hardshrink, 1)
634
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
635 636
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
637
            self.assertRaises(TypeError, F.hardshrink, x_int32)
638
            # support the input dtype is float16
J
joejiong 已提交
639 640
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
641
            F.hardshrink(x_fp16)
642 643


644 645 646 647 648 649 650 651 652 653 654
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):
655
        np.random.seed(1024)
656 657 658 659 660
        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):
661
        paddle.enable_static()
662
        with paddle.static.program_guard(paddle.static.Program()):
663
            x = paddle.fluid.data('X', [10, 12])
664 665 666 667 668 669 670 671 672 673 674
            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 已提交
675
        x = paddle.to_tensor(self.x_np)
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        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):
692
        paddle.enable_static()
693 694 695 696
        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.
J
joejiong 已提交
697 698
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
699 700
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
701 702
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
703 704 705
            F.hardtanh(x_fp16)


706 707 708 709 710 711 712 713
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):
714 715
    def setUp(self):
        self.op_type = "softshrink"
716 717
        self.init_dtype()

718
        threshold = 0.8
719

720
        np.random.seed(1023)
721 722 723 724
        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}
725
        self.outputs = {'Out': out}
726 727

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

732

733 734 735 736
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
737
        np.random.seed(1024)
738 739 740 741 742
        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):
743
        paddle.enable_static()
744
        with paddle.static.program_guard(paddle.static.Program()):
745
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
            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):
767
        paddle.enable_static()
768 769 770 771 772 773 774 775
        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)

776
    def test_errors(self):
777
        paddle.enable_static()
778
        with paddle.static.program_guard(paddle.static.Program()):
779
            # The input type must be Variable.
780
            self.assertRaises(TypeError, F.softshrink, 1)
781
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
782 783
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
784
            self.assertRaises(TypeError, F.softshrink, x_int32)
785
            # The threshold must be no less than zero
J
joejiong 已提交
786 787
            x_fp32 = paddle.fluid.data(
                name='x_fp32', shape=[12, 10], dtype='float32')
788
            self.assertRaises(ValueError, F.softshrink, x_fp32, -1.0)
789
            # support the input dtype is float16
J
joejiong 已提交
790 791
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
792
            F.softshrink(x_fp16)
793 794


795
class TestSqrt(TestActivation, TestParameter):
796 797
    def setUp(self):
        self.op_type = "sqrt"
798 799
        self.init_dtype()

800
        np.random.seed(1023)
801 802 803 804 805
        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}
806 807

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

812

Z
zhoukunsheng 已提交
813 814 815 816 817
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
        self.init_dtype()

818
        np.random.seed(1024)
Z
zhupengyang 已提交
819
        x = np.random.uniform(0.1, 1, [10, 12]).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
820 821 822 823 824 825 826 827 828 829 830
        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 已提交
831
class TestAbs(TestActivation):
832 833
    def setUp(self):
        self.op_type = "abs"
834 835
        self.init_dtype()

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

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

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

853

C
chengduo 已提交
854
class TestCeil(TestActivation):
D
dzhwinter 已提交
855 856
    def setUp(self):
        self.op_type = "ceil"
857 858
        self.init_dtype()

859
        np.random.seed(1024)
Z
zhupengyang 已提交
860
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
861 862 863 864
        out = np.ceil(x)

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

D
dzhwinter 已提交
866
    # The same reason with TestFloor
C
chengduo 已提交
867
    def test_check_grad(self):
868 869 870
        pass


C
chengduo 已提交
871
class TestFloor(TestActivation):
D
dzhwinter 已提交
872 873
    def setUp(self):
        self.op_type = "floor"
874 875
        self.init_dtype()

876
        np.random.seed(1024)
Z
zhupengyang 已提交
877
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
878 879 880 881
        out = np.floor(x)

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

D
dzhwinter 已提交
883
    # the gradient on floor, ceil, round is undefined.
884
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
885 886
    # The same reason with TestFloor
    def test_check_grad(self):
887 888 889
        pass


C
chengduo 已提交
890
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
891 892
    def setUp(self):
        self.op_type = "cos"
893 894
        self.init_dtype()

895
        np.random.seed(1024)
Z
zhupengyang 已提交
896
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
897 898 899 900
        out = np.cos(x)

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

    def test_check_grad(self):
903 904
        if self.dtype == np.float16:
            return
905
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
906

907

908 909 910 911 912
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()

913
        np.random.seed(1024)
Z
zhupengyang 已提交
914
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
915 916 917 918 919 920 921 922
        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
923
        self.check_grad(['X'], 'Out')
924 925


926
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
927 928
    def setUp(self):
        self.op_type = "sin"
929 930
        self.init_dtype()

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

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

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


944 945 946 947 948
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()

949
        np.random.seed(2048)
Z
zhupengyang 已提交
950
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
951 952 953 954 955 956 957 958
        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
959
        self.check_grad(['X'], 'Out')
960 961


C
chengduo 已提交
962
class TestRound(TestActivation):
D
dzhwinter 已提交
963 964
    def setUp(self):
        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):
Q
qijun 已提交
980
        self.op_type = "relu"
K
Kexin Zhao 已提交
981 982
        self.init_dtype()

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

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

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


998 999 1000
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1001
        np.random.seed(1024)
1002 1003 1004
        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()
1005 1006 1007 1008
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1009 1010

    def test_static_api(self):
1011
        paddle.enable_static()
1012
        with paddle.static.program_guard(paddle.static.Program()):
1013
            x = paddle.fluid.data('X', [10, 12])
1014
            out1 = self.relu(x)
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
            m = paddle.nn.ReLU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = np.maximum(self.x_np, 0)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.ReLU()
1027 1028
        out1 = m(x)
        out2 = self.relu(x)
1029 1030 1031 1032 1033
        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()

1034
    def test_errors(self):
1035
        paddle.enable_static()
1036
        with paddle.static.program_guard(paddle.static.Program()):
1037
            # The input type must be Variable.
1038
            self.assertRaises(TypeError, self.relu, 1)
1039
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1040 1041
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
1042
            self.assertRaises(TypeError, self.relu, x_int32)
1043
            # support the input dtype is float16
J
joejiong 已提交
1044 1045
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
1046 1047 1048 1049 1050 1051 1052
            self.relu(x_fp16)


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


1055 1056 1057 1058 1059 1060
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1061
class TestLeakyRelu(TestActivation):
1062 1063 1064
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1065 1066 1067
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()
1068
        alpha = self.get_alpha()
A
Adam 已提交
1069

1070
        np.random.seed(1024)
A
Adam 已提交
1071 1072
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        # The same reason with TestAbs
1073 1074
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1075

1076
        self.inputs = {'X': x}
A
Adam 已提交
1077
        self.outputs = {'Out': out}
1078
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1079 1080 1081 1082

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


1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
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):
1105
        np.random.seed(1024)
1106 1107 1108 1109 1110
        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):
1111
        paddle.enable_static()
1112
        with paddle.static.program_guard(paddle.static.Program()):
1113
            x = paddle.fluid.data('X', [10, 12])
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
            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 已提交
1125
        x = paddle.to_tensor(self.x_np)
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        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):
1142
        paddle.enable_static()
1143 1144 1145 1146 1147 1148 1149 1150
        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)

1151
    def test_errors(self):
1152
        paddle.enable_static()
1153
        with paddle.static.program_guard(paddle.static.Program()):
1154
            # The input type must be Variable.
1155
            self.assertRaises(TypeError, F.leaky_relu, 1)
1156
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1157 1158
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1159 1160
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
1161 1162
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1163
            F.leaky_relu(x_fp16)
1164 1165


1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
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 已提交
1176 1177 1178
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1179
        approximate = True
1180
        np.random.seed(1024)
1181 1182
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
1183

1184
        self.inputs = {'X': x}
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
        self.outputs = {'Out': out}
        self.attrs = {"approximate": approximate}

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


class TestGelu(TestActivation):
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
        approximate = False
1199
        np.random.seed(2048)
C
Clementine 已提交
1200
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1201
        out = gelu(x, approximate)
C
Clementine 已提交
1202

1203
        self.inputs = {'X': x}
C
Clementine 已提交
1204
        self.outputs = {'Out': out}
1205
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1206 1207 1208 1209

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


1213 1214 1215
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1216
        np.random.seed(1024)
1217 1218 1219 1220 1221
        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):
1222
        paddle.enable_static()
1223
        with paddle.static.program_guard(paddle.static.Program()):
1224
            x = paddle.fluid.data('X', [11, 17])
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
            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):
1253
        paddle.enable_static()
1254 1255 1256 1257
        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.
J
joejiong 已提交
1258 1259
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32')
1260 1261
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
1262 1263
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16')
1264 1265 1266
            F.gelu(x_fp16)


C
chengduo 已提交
1267
class TestBRelu(TestActivation):
1268 1269
    def setUp(self):
        self.op_type = "brelu"
1270 1271
        self.init_dtype()

1272
        np.random.seed(1024)
Z
zhupengyang 已提交
1273
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1274 1275
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
1276 1277
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
1278
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
1279 1280 1281
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
1282 1283 1284

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

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

1292

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
class TestBreluAPI(unittest.TestCase):
    # test paddle.fluid.layers.brelu
    def setUp(self):
        np.random.seed(1024)
        self.t_min = 0.
        self.t_max = 24.
        self.x_np = np.random.uniform(-1, 30, [10, 12]).astype('float32')
        self.out_ref = np.copy(self.x_np)
        self.out_ref[self.out_ref < self.t_min] = self.t_min
        self.out_ref[self.out_ref > self.t_max] = self.t_max
        self.out_ref = self.out_ref.astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_fluid_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.static.data('X', [10, 12])
            out = paddle.fluid.layers.brelu(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            self.assertTrue(np.allclose(self.out_ref, res[0]))

            paddle.disable_static(self.place)
            x = paddle.to_tensor(self.x_np)
            out = paddle.fluid.layers.brelu(x)
            self.assertTrue(np.allclose(self.out_ref, out.numpy()))
            paddle.enable_static()

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.brelu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.brelu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.layers.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.brelu(x_fp16)


1334 1335 1336 1337 1338 1339 1340
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 已提交
1341
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
1342
    def setUp(self):
1343
        self.op_type = "relu6"
1344 1345
        self.init_dtype()

1346
        np.random.seed(1024)
Z
zhupengyang 已提交
1347
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
1348
        x[np.abs(x) < 0.005] = 0.02
1349
        out = ref_relu6(x)
1350

1351 1352
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
1353
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
1354

1355 1356 1357
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1358
        self.check_grad(['X'], 'Out')
1359 1360


1361 1362 1363
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
1364
        np.random.seed(1024)
1365 1366 1367 1368 1369 1370
        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):
1371
        paddle.enable_static()
1372
        with paddle.static.program_guard(paddle.static.Program()):
1373
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
            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):
1395
        paddle.enable_static()
1396 1397 1398 1399 1400 1401 1402 1403
        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)

1404
    def test_errors(self):
1405
        paddle.enable_static()
1406
        with paddle.static.program_guard(paddle.static.Program()):
1407
            # The input type must be Variable.
1408
            self.assertRaises(TypeError, F.relu6, 1)
1409
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1410 1411
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1412
            self.assertRaises(TypeError, F.relu6, x_int32)
1413
            # support the input dtype is float16
J
joejiong 已提交
1414 1415
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1416
            F.relu6(x_fp16)
1417 1418


1419 1420 1421 1422 1423
def ref_hardswish(x, threshold=6.0, scale=6.0, offset=3.0):
    return (x * np.minimum(np.maximum(x + offset, 0.), threshold) /
            scale).astype(x.dtype)


H
huangjun12 已提交
1424 1425 1426 1427 1428
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()

1429
        np.random.seed(1024)
Z
zhupengyang 已提交
1430
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
1431 1432 1433 1434 1435 1436
        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
1437
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
1438

1439
        self.inputs = {'X': x}
H
huangjun12 已提交
1440 1441 1442 1443 1444 1445
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
        self.outputs = {'Out': out}

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


1449 1450 1451 1452 1453 1454 1455 1456 1457
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)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
1458
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
            out1 = F.hardswish(x)
            m = paddle.nn.Hardswish()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardswish(self.x_np)
        for r in res:
            self.assertTrue(np.allclose(out_ref, r))

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.hardswish(x)
        m = paddle.nn.Hardswish()
        out2 = m(x)
        out_ref = ref_hardswish(self.x_np)
        for r in [out1, out2]:
            self.assertTrue(np.allclose(out_ref, r.numpy()))
1477
        paddle.enable_static()
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.hard_swish(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardswish(self.x_np)
        self.assertTrue(np.allclose(out_ref, res[0]))

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out = paddle.fluid.layers.hard_swish(x)
        self.assertTrue(np.allclose(out_ref, out.numpy()))
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
1496
            # The input type must be Variable.
1497
            self.assertRaises(TypeError, F.hardswish, 1)
1498
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1499 1500
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1501
            self.assertRaises(TypeError, F.hardswish, x_int32)
1502
            # support the input dtype is float16
J
joejiong 已提交
1503 1504
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1505
            F.hardswish(x_fp16)
1506 1507


C
chengduo 已提交
1508
class TestSoftRelu(TestActivation):
1509 1510
    def setUp(self):
        self.op_type = "soft_relu"
1511 1512
        self.init_dtype()

1513
        np.random.seed(4096)
1514
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1515
        threshold = 2.0
Q
qijun 已提交
1516 1517
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
1518
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
1519 1520 1521
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
1522 1523 1524 1525 1526
        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}
1527 1528

    def test_check_grad(self):
1529 1530
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1531
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
1532

1533

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
class TestSoftReluOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.soft_relu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.soft_relu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.soft_relu(x_fp16)


1547 1548 1549 1550 1551
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 已提交
1552
class TestELU(TestActivation):
1553 1554
    def setUp(self):
        self.op_type = "elu"
1555 1556
        self.init_dtype()

1557
        np.random.seed(1024)
Z
zhupengyang 已提交
1558
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
1559
        alpha = 1.
1560
        out = elu(x, alpha)
1561 1562 1563 1564
        # 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}
1565
        self.outputs = {'Out': out}
1566 1567

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


1573 1574 1575
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
1576
        np.random.seed(1024)
1577 1578 1579
        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()
1580 1581 1582 1583
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
1584 1585

    def test_static_api(self):
1586
        paddle.enable_static()
1587
        with paddle.static.program_guard(paddle.static.Program()):
1588
            x = paddle.fluid.data('X', [10, 12])
1589
            out1 = self.elu(x)
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
            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)
1601 1602
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
1603 1604 1605 1606 1607 1608
        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)

1609 1610
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
1611 1612 1613 1614 1615 1616 1617
        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()

1618
    def test_errors(self):
1619
        paddle.enable_static()
1620 1621
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
1622
            self.assertRaises(TypeError, self.elu, 1)
1623
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1624 1625
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
1626
            self.assertRaises(TypeError, self.elu, x_int32)
1627
            # support the input dtype is float16
J
joejiong 已提交
1628 1629
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
1630 1631 1632 1633 1634 1635 1636
            self.elu(x_fp16)


class TestELUInplaceAPI(TestELUAPI):
    # test paddle.nn.functional.elu_
    def executed_api(self):
        self.elu = F.elu_
1637 1638


C
chengduo 已提交
1639
class TestReciprocal(TestActivation):
Q
qijun 已提交
1640 1641
    def setUp(self):
        self.op_type = "reciprocal"
1642 1643
        self.init_dtype()

1644
        np.random.seed(1024)
1645 1646 1647 1648 1649
        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 已提交
1650 1651

    def test_check_grad(self):
1652 1653
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1654
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Q
qijun 已提交
1655 1656


C
chengduo 已提交
1657
class TestLog(TestActivation):
Q
qijun 已提交
1658 1659
    def setUp(self):
        self.op_type = "log"
1660 1661
        self.init_dtype()

1662
        np.random.seed(1024)
1663 1664 1665 1666 1667
        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 已提交
1668 1669

    def test_check_grad(self):
1670 1671
        if self.dtype == np.float16:
            return
1672
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1673

1674 1675 1676 1677 1678 1679 1680 1681 1682
    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)

1683

J
joejiong 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
class TestLog2(TestActivation):
    def setUp(self):
        self.op_type = "log2"
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log2(x)

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

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

    def test_error(self):
        in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
        in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")

        self.assertRaises(TypeError, paddle.log2, in1)
        self.assertRaises(TypeError, paddle.log2, in2)

    def test_api(self):
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            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)
        self.assertTrue(np.allclose(res1, expected_res))

        # dygraph
        with fluid.dygraph.guard():
            np_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = paddle.to_tensor(np_x)
            z = paddle.log2(data_x)
            np_z = z.numpy()
            z_expected = np.array(np.log2(np_x))
        self.assertTrue(np.allclose(np_z, z_expected))


J
joejiong 已提交
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
class TestLog10(TestActivation):
    def setUp(self):
        self.op_type = "log10"
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        out = np.log10(x)

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

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

    def test_error(self):
        in1 = paddle.static.data(name="in1", shape=[11, 17], dtype="int32")
        in2 = paddle.static.data(name="in2", shape=[11, 17], dtype="int64")

        self.assertRaises(TypeError, paddle.log10, in1)
        self.assertRaises(TypeError, paddle.log10, in2)

    def test_api(self):
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
            input_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            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)
        self.assertTrue(np.allclose(res1, expected_res))

        # dygraph
        with fluid.dygraph.guard():
            np_x = np.random.uniform(0.1, 1, [11, 17]).astype("float64")
            data_x = paddle.to_tensor(np_x)
            z = paddle.log10(data_x)
            np_z = z.numpy()
            z_expected = np.array(np.log10(np_x))
        self.assertTrue(np.allclose(np_z, z_expected))


1782 1783 1784 1785 1786
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
        self.init_dtype()

1787
        np.random.seed(1024)
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
        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())
1811 1812 1813
            res1 = exe.run(fluid.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
1814
        expected_res = np.log1p(input_x)
1815
        self.assertTrue(np.allclose(res1, expected_res))
1816 1817 1818 1819 1820 1821 1822 1823

        # 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))
1824
        self.assertTrue(np.allclose(np_z, z_expected))
1825 1826


C
chengduo 已提交
1827
class TestSquare(TestActivation):
Q
qijun 已提交
1828 1829
    def setUp(self):
        self.op_type = "square"
1830 1831
        self.init_dtype()

1832
        np.random.seed(1024)
1833 1834 1835 1836 1837
        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 已提交
1838 1839

    def test_check_grad(self):
1840 1841
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1842
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
Q
qijun 已提交
1843

1844

C
chengduo 已提交
1845
class TestPow(TestActivation):
1846 1847
    def setUp(self):
        self.op_type = "pow"
1848 1849
        self.init_dtype()

1850
        np.random.seed(1024)
1851 1852 1853 1854
        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) 已提交
1855
        self.attrs = {'factor': 3.0}
1856
        self.outputs = {'Out': out}
1857 1858

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

1863

1864 1865 1866 1867 1868
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
        self.init_dtype()

1869
        np.random.seed(1024)
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
        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
1887
        self.check_grad(['X'], 'Out')
1888 1889 1890 1891 1892

    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")
1893 1894 1895 1896 1897
        res = fluid.layers.data(
            name="res",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
1898 1899 1900 1901 1902

        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)
1903 1904 1905
        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)
1906 1907

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
1908
        res_1, res_2, res, res_6 = exe.run(
1909 1910
            fluid.default_main_program(),
            feed={"x": input},
W
WuHaobo 已提交
1911
            fetch_list=[out_1, out_2, res, out_6])
1912 1913 1914

        assert np.array_equal(res_1, np.power(input, 2))
        assert np.array_equal(res_2, np.power(input, 3))
1915
        assert np.array_equal(res_6, np.power(input, 3))
1916

1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
    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)

1940

1941 1942 1943 1944 1945
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
1946
class TestSTanh(TestActivation):
1947 1948 1949 1950 1951 1952
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

1953 1954
    def setUp(self):
        self.op_type = "stanh"
1955
        self.init_dtype()
1956 1957
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
1958

1959
        np.random.seed(1024)
1960
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
1961 1962
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
1963

1964
        self.inputs = {'X': x}
1965
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
1966
        self.outputs = {'Out': out}
1967

Q
qijun 已提交
1968
    def test_check_grad(self):
1969 1970
        if self.dtype == np.float16:
            return
1971
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1972

1973

1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
class TestSTanhScaleA(TestSTanh):
    def get_scale_a(self):
        return 2.0


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


class TestSTanhAPI(unittest.TestCase):
    # test paddle.nn.stanh
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

    def setUp(self):
        np.random.seed(1024)
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.scale_a = self.get_scale_a()
        self.scale_b = self.get_scale_b()
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.fluid.data('X', [10, 12])
            out = paddle.stanh(x, self.scale_a, self.scale_b)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out = paddle.stanh(x, self.scale_a, self.scale_b)
        out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
        for r in [out]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', [10, 12])
            out = fluid.layers.stanh(x, self.scale_a, self.scale_b)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_stanh(self.x_np, self.scale_a, self.scale_b)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

2030
    def test_errors(self):
2031 2032
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2033
            # The input type must be Variable.
2034
            self.assertRaises(TypeError, paddle.stanh, 1)
2035
            # The input dtype must be float16, float32, float64.
2036 2037 2038
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, paddle.stanh, x_int32)
2039
            # support the input dtype is float16
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
            paddle.stanh(x_fp16)


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


class TestSTanhAPIScaleB(TestSTanhAPI):
    def get_scale_b(self):
        return 0.5
2053 2054


2055 2056 2057 2058 2059 2060 2061
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 已提交
2062
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
2063 2064
    def setUp(self):
        self.op_type = "softplus"
2065 2066
        self.init_dtype()

2067 2068
        beta = 2
        threshold = 15
2069

2070
        np.random.seed(1024)
2071 2072 2073 2074
        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}
2075
        self.outputs = {'Out': out}
K
kexinzhao 已提交
2076 2077

    def test_check_grad(self):
2078 2079
        if self.dtype == np.float16:
            return
2080
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
2081

2082

2083 2084 2085 2086 2087
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
2088
        np.random.seed(1024)
2089 2090 2091 2092 2093
        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):
2094
        paddle.enable_static()
2095
        with paddle.static.program_guard(paddle.static.Program()):
2096
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
            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):
2118
        paddle.enable_static()
2119 2120 2121 2122 2123 2124 2125 2126 2127
        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):
2128
        paddle.enable_static()
2129 2130 2131 2132
        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.
J
joejiong 已提交
2133 2134
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2135 2136
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
2137 2138
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2139 2140 2141 2142 2143 2144 2145 2146
            F.softplus(x_fp16)


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


C
chengduo 已提交
2147
class TestSoftsign(TestActivation):
2148 2149
    def setUp(self):
        self.op_type = "softsign"
2150 2151
        self.init_dtype()

2152
        np.random.seed(1024)
2153 2154 2155
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softsign(x)
        self.inputs = {'X': x}
2156
        self.outputs = {'Out': out}
2157 2158

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


2164 2165 2166
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
2167
        np.random.seed(1024)
2168 2169 2170 2171 2172
        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):
2173
        paddle.enable_static()
2174
        with paddle.static.program_guard(paddle.static.Program()):
2175
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
            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):
2197
        paddle.enable_static()
2198 2199 2200 2201 2202 2203 2204 2205 2206
        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):
2207
        paddle.enable_static()
2208 2209 2210 2211
        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.
J
joejiong 已提交
2212 2213
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2214 2215
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
2216 2217
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2218 2219 2220
            F.softsign(x_fp16)


2221 2222 2223 2224 2225
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
2226
class TestThresholdedRelu(TestActivation):
2227 2228
    def setUp(self):
        self.op_type = "thresholded_relu"
2229 2230
        self.init_dtype()

2231
        threshold = 15
2232

2233 2234 2235 2236 2237 2238
        np.random.seed(1024)
        x = np.random.uniform(-20, 20, [10, 12]).astype(self.dtype)
        x[np.abs(x) < 0.005] = 0.02
        out = ref_thresholded_relu(x, threshold)
        self.inputs = {'X': x}
        self.attrs = {"threshold": threshold}
2239
        self.outputs = {'Out': out}
2240 2241

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


2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
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
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2260
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
            out1 = F.thresholded_relu(x, self.threshold)
            thresholded_relu = paddle.nn.ThresholdedReLU(self.threshold)
            out2 = thresholded_relu(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_thresholded_relu(self.x_np, self.threshold)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.thresholded_relu(x, self.threshold)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_thresholded_relu(self.x_np, self.threshold)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

2291
    def test_errors(self):
2292 2293
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2294
            # The input type must be Variable.
2295
            self.assertRaises(TypeError, F.thresholded_relu, 1)
2296
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2297 2298
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2299
            self.assertRaises(TypeError, F.thresholded_relu, x_int32)
2300
            # support the input dtype is float16
J
joejiong 已提交
2301 2302
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2303
            F.thresholded_relu(x_fp16)
2304 2305


2306 2307 2308 2309
def ref_hardsigmoid(x, slope=0.166666666666667, offset=0.5):
    return np.maximum(np.minimum(x * slope + offset, 1.), 0.).astype(x.dtype)


C
chengduo 已提交
2310
class TestHardSigmoid(TestActivation):
2311 2312
    def setUp(self):
        self.op_type = "hard_sigmoid"
2313 2314 2315 2316
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
2317

2318 2319 2320
        x = np.random.uniform(-5, 5, [10, 12]).astype(self.dtype)
        lower_threshold = -self.offset / self.slope
        upper_threshold = (1. - self.offset) / self.slope
Z
zhupengyang 已提交
2321

2322
        # Same reason as TestAbs
2323 2324 2325
        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
2326

2327
        out = ref_hardsigmoid(x, self.slope, self.offset)
2328

2329 2330
        self.attrs = {'slope': self.slope, 'offset': self.offset}
        self.inputs = {'X': x}
2331
        self.outputs = {'Out': out}
2332

2333 2334
    def set_attrs(self):
        pass
2335

2336

2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
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


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)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
2357
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
            out1 = F.hardsigmoid(x)
            m = paddle.nn.Hardsigmoid()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardsigmoid(self.x_np)
        for r in res:
            self.assertTrue(np.allclose(out_ref, r))

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.hardsigmoid(x)
        m = paddle.nn.Hardsigmoid()
        out2 = m(x)
        out_ref = ref_hardsigmoid(self.x_np)
        for r in [out1, out2]:
            self.assertTrue(np.allclose(out_ref, r.numpy()))
2376
        paddle.enable_static()
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394

    def test_fluid_api(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.hard_sigmoid(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_hardsigmoid(self.x_np, 0.2, 0.5)
        self.assertTrue(np.allclose(out_ref, res[0]))

        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out = paddle.fluid.layers.hard_sigmoid(x)
        self.assertTrue(np.allclose(out_ref, out.numpy()))
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
2395
            # The input type must be Variable.
2396
            self.assertRaises(TypeError, F.hardsigmoid, 1)
2397
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2398 2399
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2400
            self.assertRaises(TypeError, F.hardsigmoid, x_int32)
2401
            # support the input dtype is float16
J
joejiong 已提交
2402 2403
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2404
            F.hardsigmoid(x_fp16)
2405 2406


2407 2408 2409 2410 2411
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
2412
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
2413 2414
    def setUp(self):
        self.op_type = "swish"
2415 2416
        self.init_dtype()

2417
        np.random.seed(1024)
2418 2419 2420
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_swish(x)
        self.inputs = {'X': x}
H
hong19860320 已提交
2421
        self.attrs = {'beta': 1.0}
2422
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
2423 2424

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

A
Abhinav Arora 已提交
2429

2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
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)
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2441
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
            out1 = F.swish(x)
            swish = paddle.nn.Swish()
            out2 = swish(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_swish(self.x_np)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

    def test_fluid_api(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):
            x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
            out = fluid.layers.swish(x)
            exe = fluid.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
        out_ref = ref_swish(self.x_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)
2471

2472
    def test_errors(self):
2473 2474
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2475
            # The input type must be Variable.
2476
            self.assertRaises(TypeError, F.swish, 1)
2477
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2478 2479
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2480
            self.assertRaises(TypeError, F.swish, x_int32)
2481
            # support the input dtype is float16
J
joejiong 已提交
2482 2483
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2484
            F.swish(x_fp16)
2485 2486


2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
#------------------ 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')


2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
#------------------ 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 已提交
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
#------------------ 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
2549

C
chengduo 已提交
2550
        def test_check_output(self):
2551
            place = core.CUDAPlace(0)
C
chengduo 已提交
2552 2553 2554
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
2555

C
chengduo 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
        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)
2572
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
2573
create_test_act_fp16_class(TestHardShrink)
2574
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
2575 2576 2577 2578 2579
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)
2580
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
2581
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
2582
create_test_act_fp16_class(TestSin)
2583
create_test_act_fp16_class(TestSinh)
2584 2585
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
C
chengduo 已提交
2586 2587
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
2588
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
2589 2590 2591 2592 2593 2594
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)
J
joejiong 已提交
2595
create_test_act_fp16_class(TestLog2, atol=5e-2)
J
joejiong 已提交
2596
create_test_act_fp16_class(TestLog10, atol=5e-2)
2597
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
2598 2599
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
2600
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
2601 2602 2603 2604 2605 2606
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 已提交
2607
create_test_act_fp16_class(TestHardSwish)
A
Abhinav Arora 已提交
2608

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