test_activation_op.py 91.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
from __future__ import print_function
Q
qijun 已提交
16
import unittest
J
joejiong 已提交
17

Q
qijun 已提交
18
import numpy as np
C
Clementine 已提交
19
from scipy.special import expit, erf
J
joejiong 已提交
20 21

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

29 30
paddle.enable_static()

Q
qijun 已提交
31

32
class TestSqrtOpError(unittest.TestCase):
Z
Zhaolong Xing 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    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 已提交
48
class TestActivation(OpTest):
Q
qijun 已提交
49 50
    def setUp(self):
        self.op_type = "exp"
51
        self.init_dtype()
52
        self.init_kernel_type()
53

54
        np.random.seed(2049)
55 56 57 58 59
        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 已提交
60 61 62 63 64

    def test_check_output(self):
        self.check_output()

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

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

72 73 74
    def init_kernel_type(self):
        pass

Q
qijun 已提交
75

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

    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([0.1])
            x = fluid.dygraph.to_variable(np_x)
            z = eval("paddle.%s(x).numpy()" % self.op_type)
            z_expected = eval("np.%s(np_x)" % self.op_type)
            self.assertEqual(z, z_expected)


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

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

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

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

117

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

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

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

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


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

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

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

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

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


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

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

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

215

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

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

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


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


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

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

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

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

321

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

327
        np.random.seed(1024)
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 398
        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()

399
        np.random.seed(1024)
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 465
        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)


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


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

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

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

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

488

489 490 491
class TestTanhshrinkAPI(unittest.TestCase):
    # test paddle.nn.Tanhshrink, paddle.nn.functional.tanhshrink
    def setUp(self):
492
        np.random.seed(1024)
493
        self.x_np = np.random.uniform(10, 20, [10, 17]).astype(np.float64)
J
joejiong 已提交
494
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
495 496 497
            else paddle.CPUPlace()

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


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


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

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

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

567 568 569
    def set_attrs(self):
        pass

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


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


581 582 583
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
584
        np.random.seed(1024)
585
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
586
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
587 588 589
            else paddle.CPUPlace()

    def test_static_api(self):
590
        paddle.enable_static()
591
        with paddle.static.program_guard(paddle.static.Program()):
592
            x = paddle.fluid.data('X', [10, 12])
593 594 595 596 597 598 599 600 601 602 603
            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 已提交
604
        x = paddle.to_tensor(self.x_np)
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
        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):
621
        paddle.enable_static()
622 623 624 625 626 627 628 629
        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)

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


645 646 647 648 649 650 651 652 653 654 655
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):
656
        np.random.seed(1024)
657
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
J
joejiong 已提交
658
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
659 660 661
            else paddle.CPUPlace()

    def test_static_api(self):
662
        paddle.enable_static()
663
        with paddle.static.program_guard(paddle.static.Program()):
664
            x = paddle.fluid.data('X', [10, 12])
665 666 667 668 669 670 671 672 673 674 675
            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 已提交
676
        x = paddle.to_tensor(self.x_np)
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        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):
693
        paddle.enable_static()
694 695 696 697
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.hardtanh, 1)
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
698 699
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
700 701
            self.assertRaises(TypeError, F.hardtanh, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
702 703
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
704 705 706
            F.hardtanh(x_fp16)


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

719
        threshold = 0.8
720

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

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

733

734 735 736 737
class TestSoftshrinkAPI(unittest.TestCase):
    # test paddle.nn.Softshrink, paddle.nn.functional.softshrink
    def setUp(self):
        self.threshold = 0.8
738
        np.random.seed(1024)
739
        self.x_np = np.random.uniform(0.25, 10, [10, 12]).astype(np.float64)
J
joejiong 已提交
740
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
741 742 743
            else paddle.CPUPlace()

    def test_static_api(self):
744
        paddle.enable_static()
745
        with paddle.static.program_guard(paddle.static.Program()):
746
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
            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):
768
        paddle.enable_static()
769 770 771 772 773 774 775 776
        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)

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


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

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

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

813

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

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

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

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

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

854

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

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

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

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


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

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

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

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


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

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

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

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

908

J
joejiong 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
class TestTan(TestActivation):
    def setUp(self):
        np.random.seed(1024)
        self.op_type = "tan"
        self.init_dtype()
        self.dtype = 'float32'
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        self.place = paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
            else paddle.CPUPlace()

        out = np.tan(self.x_np)

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

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

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out_test = paddle.tan(x)
        out_ref = np.tan(self.x_np)
        self.assertTrue(np.allclose(out_ref, out_test.numpy()))
        paddle.enable_static()

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

    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 = paddle.to_tensor(input_x)
            var.stop_gradient = False
            loss = paddle.tan(var)
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, input_x.shape)


960 961 962 963 964
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()

965
        np.random.seed(1024)
Z
zhupengyang 已提交
966
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
967 968 969 970 971 972 973 974
        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
975
        self.check_grad(['X'], 'Out')
976 977


978
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
979 980
    def setUp(self):
        self.op_type = "sin"
981 982
        self.init_dtype()

983
        np.random.seed(1024)
Z
zhupengyang 已提交
984
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
985 986 987 988
        out = np.sin(x)

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

    def test_check_grad(self):
991 992
        if self.dtype == np.float16:
            return
993
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
994 995


996 997 998 999 1000
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()

1001
        np.random.seed(2048)
Z
zhupengyang 已提交
1002
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
1003 1004 1005 1006 1007 1008 1009 1010
        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
1011
        self.check_grad(['X'], 'Out')
1012 1013


C
chengduo 已提交
1014
class TestRound(TestActivation):
D
dzhwinter 已提交
1015 1016
    def setUp(self):
        self.op_type = "round"
1017 1018
        self.init_dtype()

1019
        np.random.seed(1024)
Z
zhupengyang 已提交
1020
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
1021 1022 1023 1024
        out = np.round(x)

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

C
chengduo 已提交
1026
    def test_check_grad(self):
1027 1028 1029
        pass


C
chengduo 已提交
1030
class TestRelu(TestActivation):
1031
    def setUp(self):
Q
qijun 已提交
1032
        self.op_type = "relu"
K
Kexin Zhao 已提交
1033 1034
        self.init_dtype()

1035
        np.random.seed(1024)
K
Kexin Zhao 已提交
1036
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
Q
qijun 已提交
1037 1038
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.02
K
Kexin Zhao 已提交
1039 1040
        out = np.maximum(x, 0)

1041
        self.inputs = {'X': x}
K
Kexin Zhao 已提交
1042
        self.outputs = {'Out': out}
1043 1044

    def test_check_grad(self):
K
Kexin Zhao 已提交
1045 1046
        if self.dtype == np.float16:
            return
1047
        self.check_grad(['X'], 'Out')
A
Adam 已提交
1048 1049


1050 1051 1052
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
1053
        np.random.seed(1024)
1054
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
1055
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1056
            else paddle.CPUPlace()
1057 1058 1059 1060
        self.executed_api()

    def executed_api(self):
        self.relu = F.relu
1061 1062

    def test_static_api(self):
1063
        paddle.enable_static()
1064
        with paddle.static.program_guard(paddle.static.Program()):
1065
            x = paddle.fluid.data('X', [10, 12])
1066
            out1 = self.relu(x)
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
            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()
1079 1080
        out1 = m(x)
        out2 = self.relu(x)
1081 1082 1083 1084 1085
        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()

1086
    def test_errors(self):
1087
        paddle.enable_static()
1088
        with paddle.static.program_guard(paddle.static.Program()):
1089
            # The input type must be Variable.
1090
            self.assertRaises(TypeError, self.relu, 1)
1091
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1092 1093
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
1094
            self.assertRaises(TypeError, self.relu, x_int32)
1095
            # support the input dtype is float16
J
joejiong 已提交
1096 1097
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
1098 1099 1100 1101 1102 1103 1104
            self.relu(x_fp16)


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


1107 1108 1109 1110 1111 1112
def ref_leaky_relu(x, alpha=0.01):
    out = np.copy(x)
    out[out < 0] *= alpha
    return out


A
Adam 已提交
1113
class TestLeakyRelu(TestActivation):
1114 1115 1116
    def get_alpha(self):
        return 0.02

A
Adam 已提交
1117 1118 1119
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()
1120
        alpha = self.get_alpha()
A
Adam 已提交
1121

1122
        np.random.seed(1024)
A
Adam 已提交
1123 1124
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        # The same reason with TestAbs
1125 1126
        x[np.abs(x) < 0.005] = 0.05
        out = ref_leaky_relu(x, alpha)
A
Adam 已提交
1127

1128
        self.inputs = {'X': x}
A
Adam 已提交
1129
        self.outputs = {'Out': out}
1130
        self.attrs = {'alpha': alpha}
A
Adam 已提交
1131 1132 1133 1134

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


1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
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):
1157
        np.random.seed(1024)
1158
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
J
joejiong 已提交
1159
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1160 1161 1162
            else paddle.CPUPlace()

    def test_static_api(self):
1163
        paddle.enable_static()
1164
        with paddle.static.program_guard(paddle.static.Program()):
1165
            x = paddle.fluid.data('X', [10, 12])
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
            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 已提交
1177
        x = paddle.to_tensor(self.x_np)
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
        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):
1194
        paddle.enable_static()
1195 1196 1197 1198 1199 1200 1201 1202
        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)

1203
    def test_errors(self):
1204
        paddle.enable_static()
1205
        with paddle.static.program_guard(paddle.static.Program()):
1206
            # The input type must be Variable.
1207
            self.assertRaises(TypeError, F.leaky_relu, 1)
1208
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1209 1210
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1211 1212
            self.assertRaises(TypeError, F.leaky_relu, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
1213 1214
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1215
            F.leaky_relu(x_fp16)
1216 1217


1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
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 已提交
1228 1229 1230
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
1231
        approximate = True
1232
        np.random.seed(1024)
1233 1234
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
1235

1236
        self.inputs = {'X': x}
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
        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
1251
        np.random.seed(2048)
C
Clementine 已提交
1252
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1253
        out = gelu(x, approximate)
C
Clementine 已提交
1254

1255
        self.inputs = {'X': x}
C
Clementine 已提交
1256
        self.outputs = {'Out': out}
1257
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
1258 1259 1260 1261

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


1265 1266 1267
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
1268
        np.random.seed(1024)
1269
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
J
joejiong 已提交
1270
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1271 1272 1273
            else paddle.CPUPlace()

    def test_static_api(self):
1274
        paddle.enable_static()
1275
        with paddle.static.program_guard(paddle.static.Program()):
1276
            x = paddle.fluid.data('X', [11, 17])
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
            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):
1305
        paddle.enable_static()
1306 1307 1308 1309
        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 已提交
1310 1311
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[11, 17], dtype='int32')
1312 1313
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
1314 1315
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[11, 17], dtype='float16')
1316 1317 1318
            F.gelu(x_fp16)


C
chengduo 已提交
1319
class TestBRelu(TestActivation):
1320 1321
    def setUp(self):
        self.op_type = "brelu"
1322 1323
        self.init_dtype()

1324
        np.random.seed(1024)
Z
zhupengyang 已提交
1325
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1326 1327
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
1328 1329
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
1330
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
1331 1332 1333
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
1334 1335 1336

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

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

1344

1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
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')
J
joejiong 已提交
1356
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
            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()

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    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)


1386 1387 1388 1389 1390 1391 1392
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 已提交
1393
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
1394
    def setUp(self):
1395
        self.op_type = "relu6"
1396 1397
        self.init_dtype()

1398
        np.random.seed(1024)
Z
zhupengyang 已提交
1399
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
1400
        x[np.abs(x) < 0.005] = 0.02
1401
        out = ref_relu6(x)
1402

1403 1404
        self.inputs = {'X': x}
        self.attrs = {'threshold': 6.0}
1405
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
1406

1407 1408 1409
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
1410
        self.check_grad(['X'], 'Out')
1411 1412


1413 1414 1415
class TestRelu6API(unittest.TestCase):
    # test paddle.nn.ReLU6, paddle.nn.functional.relu6
    def setUp(self):
1416
        np.random.seed(1024)
1417 1418
        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
J
joejiong 已提交
1419
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1420 1421 1422
            else paddle.CPUPlace()

    def test_static_api(self):
1423
        paddle.enable_static()
1424
        with paddle.static.program_guard(paddle.static.Program()):
1425
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
            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):
1447
        paddle.enable_static()
1448 1449 1450 1451 1452 1453 1454 1455
        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)

1456
    def test_errors(self):
1457
        paddle.enable_static()
1458
        with paddle.static.program_guard(paddle.static.Program()):
1459
            # The input type must be Variable.
1460
            self.assertRaises(TypeError, F.relu6, 1)
1461
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1462 1463
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1464
            self.assertRaises(TypeError, F.relu6, x_int32)
1465
            # support the input dtype is float16
J
joejiong 已提交
1466 1467
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1468
            F.relu6(x_fp16)
1469 1470


1471 1472 1473 1474 1475
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 已提交
1476 1477 1478 1479 1480
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()

J
jakpiase 已提交
1481 1482 1483
        from op_test import skip_check_grad_ci
        skip_check_grad_ci(reason="not implemented yet")

1484
        np.random.seed(1024)
Z
zhupengyang 已提交
1485
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
1486 1487 1488 1489 1490 1491
        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
1492
        out = ref_hardswish(x, threshold, scale, offset)
H
huangjun12 已提交
1493

1494
        self.inputs = {'X': x}
H
huangjun12 已提交
1495 1496 1497 1498 1499 1500
        self.attrs = {'threshold': threshold, 'scale': scale, 'offset': offset}
        self.outputs = {'Out': out}

    def test_check_grad(self):
        if self.dtype == np.float16:
            return
J
jakpiase 已提交
1501 1502

        return  # not implemented yet
1503
        self.check_grad(['X'], 'Out')
H
huangjun12 已提交
1504 1505


1506 1507 1508 1509
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)
J
joejiong 已提交
1510
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1511 1512 1513 1514
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
1515
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
            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()))
1534
        paddle.enable_static()
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552

    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()):
1553
            # The input type must be Variable.
1554
            self.assertRaises(TypeError, F.hardswish, 1)
1555
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1556 1557
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
1558
            self.assertRaises(TypeError, F.hardswish, x_int32)
1559
            # support the input dtype is float16
J
joejiong 已提交
1560 1561
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
1562
            F.hardswish(x_fp16)
1563 1564


C
chengduo 已提交
1565
class TestSoftRelu(TestActivation):
1566 1567
    def setUp(self):
        self.op_type = "soft_relu"
1568 1569
        self.init_dtype()

1570
        np.random.seed(4096)
1571
        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
1572
        threshold = 2.0
Q
qijun 已提交
1573 1574
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
1575
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
1576 1577 1578
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
1579 1580 1581 1582 1583
        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}
1584 1585

    def test_check_grad(self):
1586 1587
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1588
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
1589

1590

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
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)


1604 1605 1606 1607 1608
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 已提交
1609
class TestELU(TestActivation):
1610 1611
    def setUp(self):
        self.op_type = "elu"
1612 1613
        self.init_dtype()

1614
        np.random.seed(1024)
Z
zhupengyang 已提交
1615
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
1616
        alpha = 1.
1617
        out = elu(x, alpha)
1618 1619 1620 1621
        # 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}
1622
        self.outputs = {'Out': out}
1623 1624

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


1630 1631 1632
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
1633
        np.random.seed(1024)
1634
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
J
joejiong 已提交
1635
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
1636
            else paddle.CPUPlace()
1637 1638 1639 1640
        self.executed_api()

    def executed_api(self):
        self.elu = F.elu
1641 1642

    def test_static_api(self):
1643
        paddle.enable_static()
1644
        with paddle.static.program_guard(paddle.static.Program()):
1645
            x = paddle.fluid.data('X', [10, 12])
1646
            out1 = self.elu(x)
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
            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)
1658 1659
        out1 = self.elu(x)
        x = paddle.to_tensor(self.x_np)
1660 1661 1662 1663 1664 1665
        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)

1666 1667
        out1 = self.elu(x, 0.2)
        x = paddle.to_tensor(self.x_np)
1668 1669 1670 1671 1672 1673 1674
        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()

1675
    def test_errors(self):
1676
        paddle.enable_static()
1677 1678
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
1679
            self.assertRaises(TypeError, self.elu, 1)
1680
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
1681 1682
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[10, 12], dtype='int32')
1683
            self.assertRaises(TypeError, self.elu, x_int32)
1684
            # support the input dtype is float16
J
joejiong 已提交
1685 1686
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[10, 12], dtype='float16')
1687 1688 1689 1690 1691 1692 1693
            self.elu(x_fp16)


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


C
chengduo 已提交
1696
class TestReciprocal(TestActivation):
Q
qijun 已提交
1697 1698
    def setUp(self):
        self.op_type = "reciprocal"
1699 1700
        self.init_dtype()

1701
        np.random.seed(1024)
1702 1703 1704 1705 1706
        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 已提交
1707 1708

    def test_check_grad(self):
1709 1710
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1711
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Q
qijun 已提交
1712 1713


C
chengduo 已提交
1714
class TestLog(TestActivation):
Q
qijun 已提交
1715 1716
    def setUp(self):
        self.op_type = "log"
1717 1718
        self.init_dtype()

1719
        np.random.seed(1024)
1720 1721 1722 1723 1724
        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 已提交
1725 1726

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

1731 1732 1733 1734 1735 1736 1737 1738 1739
    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)

1740

J
joejiong 已提交
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 1782 1783 1784 1785 1786 1787 1788 1789
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 已提交
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
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))


1839 1840 1841 1842 1843
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
        self.init_dtype()

1844
        np.random.seed(1024)
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
        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())
1868 1869 1870
            res1 = exe.run(fluid.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
1871
        expected_res = np.log1p(input_x)
1872
        self.assertTrue(np.allclose(res1, expected_res))
1873 1874 1875 1876 1877 1878 1879 1880

        # 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))
1881
        self.assertTrue(np.allclose(np_z, z_expected))
1882 1883


C
chengduo 已提交
1884
class TestSquare(TestActivation):
Q
qijun 已提交
1885 1886
    def setUp(self):
        self.op_type = "square"
1887 1888
        self.init_dtype()

1889
        np.random.seed(1024)
1890 1891 1892 1893 1894
        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 已提交
1895 1896

    def test_check_grad(self):
1897 1898
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1899
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
Q
qijun 已提交
1900

1901

C
chengduo 已提交
1902
class TestPow(TestActivation):
1903 1904
    def setUp(self):
        self.op_type = "pow"
1905 1906
        self.init_dtype()

1907
        np.random.seed(1024)
1908 1909 1910 1911
        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) 已提交
1912
        self.attrs = {'factor': 3.0}
1913
        self.outputs = {'Out': out}
1914 1915

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

1920

1921 1922 1923 1924 1925
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
        self.init_dtype()

1926
        np.random.seed(1024)
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
        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
1944
        self.check_grad(['X'], 'Out')
1945 1946 1947 1948 1949

    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")
1950 1951 1952 1953 1954
        res = fluid.layers.data(
            name="res",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
1955 1956 1957 1958 1959

        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)
1960 1961 1962
        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)
1963 1964

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
1965
        res_1, res_2, res, res_6 = exe.run(
1966 1967
            fluid.default_main_program(),
            feed={"x": input},
W
WuHaobo 已提交
1968
            fetch_list=[out_1, out_2, res, out_6])
1969 1970 1971

        assert np.array_equal(res_1, np.power(input, 2))
        assert np.array_equal(res_2, np.power(input, 3))
1972
        assert np.array_equal(res_6, np.power(input, 3))
1973

1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
    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)

1997

1998 1999 2000 2001 2002
def ref_stanh(x, scale_a=0.67, scale_b=1.7159):
    out = scale_b * np.tanh(x * scale_a)
    return out


C
chengduo 已提交
2003
class TestSTanh(TestActivation):
2004 2005 2006 2007 2008 2009
    def get_scale_a(self):
        return 0.67

    def get_scale_b(self):
        return 1.7159

2010 2011
    def setUp(self):
        self.op_type = "stanh"
2012
        self.init_dtype()
2013 2014
        scale_a = self.get_scale_a()
        scale_b = self.get_scale_b()
2015

2016
        np.random.seed(1024)
2017
        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
2018 2019
        # The same reason with TestAbs
        out = ref_stanh(x, scale_a, scale_b)
2020

2021
        self.inputs = {'X': x}
2022
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
2023
        self.outputs = {'Out': out}
2024

Q
qijun 已提交
2025
    def test_check_grad(self):
2026 2027
        if self.dtype == np.float16:
            return
2028
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
2029

2030

2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
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)

2087
    def test_errors(self):
2088 2089
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2090
            # The input type must be Variable.
2091
            self.assertRaises(TypeError, paddle.stanh, 1)
2092
            # The input dtype must be float16, float32, float64.
2093 2094 2095
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, paddle.stanh, x_int32)
2096
            # support the input dtype is float16
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
            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
2110 2111


2112 2113 2114 2115 2116 2117 2118
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 已提交
2119
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
2120 2121
    def setUp(self):
        self.op_type = "softplus"
2122 2123
        self.init_dtype()

2124 2125
        beta = 2
        threshold = 15
2126

2127
        np.random.seed(1024)
2128 2129 2130 2131
        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}
2132
        self.outputs = {'Out': out}
K
kexinzhao 已提交
2133 2134

    def test_check_grad(self):
2135 2136
        if self.dtype == np.float16:
            return
2137
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
2138

2139

2140 2141 2142 2143 2144
class TestSoftplusAPI(unittest.TestCase):
    # test paddle.nn.Softplus, paddle.nn.functional.softplus
    def setUp(self):
        self.beta = 2
        self.threshold = 15
2145
        np.random.seed(1024)
2146
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2147
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2148 2149 2150
            else paddle.CPUPlace()

    def test_static_api(self):
2151
        paddle.enable_static()
2152
        with paddle.static.program_guard(paddle.static.Program()):
2153
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
            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):
2175
        paddle.enable_static()
2176 2177 2178 2179 2180 2181 2182 2183 2184
        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):
2185
        paddle.enable_static()
2186 2187 2188 2189
        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 已提交
2190 2191
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2192 2193
            self.assertRaises(TypeError, F.softplus, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
2194 2195
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2196 2197 2198 2199 2200 2201 2202 2203
            F.softplus(x_fp16)


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


C
chengduo 已提交
2204
class TestSoftsign(TestActivation):
2205 2206
    def setUp(self):
        self.op_type = "softsign"
2207 2208
        self.init_dtype()

2209
        np.random.seed(1024)
2210 2211 2212
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_softsign(x)
        self.inputs = {'X': x}
2213
        self.outputs = {'Out': out}
2214 2215

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


2221 2222 2223
class TestSoftsignAPI(unittest.TestCase):
    # test paddle.nn.Softsign, paddle.nn.functional.softsign
    def setUp(self):
2224
        np.random.seed(1024)
2225
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype(np.float64)
J
joejiong 已提交
2226
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2227 2228 2229
            else paddle.CPUPlace()

    def test_static_api(self):
2230
        paddle.enable_static()
2231
        with paddle.static.program_guard(paddle.static.Program()):
2232
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
            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):
2254
        paddle.enable_static()
2255 2256 2257 2258 2259 2260 2261 2262 2263
        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):
2264
        paddle.enable_static()
2265 2266 2267 2268
        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 已提交
2269 2270
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2271 2272
            self.assertRaises(TypeError, F.softsign, x_int32)
            # support the input dtype is float16
J
joejiong 已提交
2273 2274
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2275 2276 2277
            F.softsign(x_fp16)


2278 2279 2280 2281 2282
def ref_thresholded_relu(x, threshold=1.0):
    out = (x > threshold) * x
    return out


C
chengduo 已提交
2283
class TestThresholdedRelu(TestActivation):
2284 2285
    def setUp(self):
        self.op_type = "thresholded_relu"
2286 2287
        self.init_dtype()

2288
        threshold = 15
2289

2290 2291 2292 2293 2294 2295
        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}
2296
        self.outputs = {'Out': out}
2297 2298

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


2304 2305 2306 2307 2308 2309 2310
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
J
joejiong 已提交
2311
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2312 2313 2314 2315 2316
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2317
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
            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)

2348
    def test_errors(self):
2349 2350
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2351
            # The input type must be Variable.
2352
            self.assertRaises(TypeError, F.thresholded_relu, 1)
2353
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2354 2355
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2356
            self.assertRaises(TypeError, F.thresholded_relu, x_int32)
2357
            # support the input dtype is float16
J
joejiong 已提交
2358 2359
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2360
            F.thresholded_relu(x_fp16)
2361 2362


2363 2364 2365 2366
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 已提交
2367
class TestHardSigmoid(TestActivation):
2368 2369
    def setUp(self):
        self.op_type = "hard_sigmoid"
2370 2371 2372 2373
        self.dtype = 'float64'
        self.slope = 0.166666666666667
        self.offset = 0.5
        self.set_attrs()
2374

2375 2376 2377
        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 已提交
2378

2379
        # Same reason as TestAbs
2380 2381 2382
        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
2383

2384
        out = ref_hardsigmoid(x, self.slope, self.offset)
2385

2386 2387
        self.attrs = {'slope': self.slope, 'offset': self.offset}
        self.inputs = {'X': x}
2388
        self.outputs = {'Out': out}
2389

2390 2391
    def set_attrs(self):
        pass
2392

2393

2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
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)
J
joejiong 已提交
2409
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2410 2411 2412 2413
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
2414
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
            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()))
2433
        paddle.enable_static()
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451

    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()):
2452
            # The input type must be Variable.
2453
            self.assertRaises(TypeError, F.hardsigmoid, 1)
2454
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2455 2456
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2457
            self.assertRaises(TypeError, F.hardsigmoid, x_int32)
2458
            # support the input dtype is float16
J
joejiong 已提交
2459 2460
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2461
            F.hardsigmoid(x_fp16)
2462 2463


2464 2465 2466 2467 2468
def ref_swish(x):
    out = x * expit(x)
    return out


C
chengduo 已提交
2469
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
2470 2471
    def setUp(self):
        self.op_type = "swish"
2472 2473
        self.init_dtype()

2474
        np.random.seed(1024)
2475 2476 2477
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
        out = ref_swish(x)
        self.inputs = {'X': x}
H
hong19860320 已提交
2478
        self.attrs = {'beta': 1.0}
2479
        self.outputs = {'Out': out}
A
Abhinav Arora 已提交
2480 2481

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

A
Abhinav Arora 已提交
2486

2487 2488 2489 2490 2491
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)
J
joejiong 已提交
2492
        self.place=paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \
2493 2494 2495 2496 2497
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
J
joejiong 已提交
2498
            x = paddle.static.data('X', self.x_np.shape, self.x_np.dtype)
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
            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)
2528

2529
    def test_errors(self):
2530 2531
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
2532
            # The input type must be Variable.
2533
            self.assertRaises(TypeError, F.swish, 1)
2534
            # The input dtype must be float16, float32, float64.
J
joejiong 已提交
2535 2536
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[12, 10], dtype='int32')
2537
            self.assertRaises(TypeError, F.swish, x_int32)
2538
            # support the input dtype is float16
J
joejiong 已提交
2539 2540
            x_fp16 = paddle.fluid.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
2541
            F.swish(x_fp16)
2542 2543


2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
#------------------ 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')
J
joejiong 已提交
2575
create_test_error_class('tan')
2576 2577


2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
#------------------ 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 已提交
2597 2598 2599 2600 2601
#------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(parent,
                               atol=1e-3,
                               grad_check=True,
                               grad_atol=0.80):
J
joejiong 已提交
2602
    @unittest.skipIf(not paddle.is_compiled_with_cuda(),
C
chengduo 已提交
2603 2604 2605 2606
                     "core is not compiled with CUDA")
    class TestActFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16
2607

C
chengduo 已提交
2608
        def test_check_output(self):
2609
            place = core.CUDAPlace(0)
C
chengduo 已提交
2610 2611 2612
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
2613

C
chengduo 已提交
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
        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)
2630
create_test_act_fp16_class(TestTanhshrink)
C
chengduo 已提交
2631
create_test_act_fp16_class(TestHardShrink)
2632
create_test_act_fp16_class(TestSoftshrink)
C
chengduo 已提交
2633 2634 2635 2636 2637
create_test_act_fp16_class(TestSqrt)
create_test_act_fp16_class(TestAbs)
create_test_act_fp16_class(TestCeil, grad_check=False)
create_test_act_fp16_class(TestFloor, grad_check=False)
create_test_act_fp16_class(TestCos, grad_atol=0.85)
J
joejiong 已提交
2638
create_test_act_fp16_class(TestTan, grad_atol=0.85)
2639
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
2640
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
2641
create_test_act_fp16_class(TestSin)
2642
create_test_act_fp16_class(TestSinh)
2643 2644
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
C
chengduo 已提交
2645 2646
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
2647
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
2648 2649 2650 2651 2652 2653
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 已提交
2654
create_test_act_fp16_class(TestLog2, atol=5e-2)
J
joejiong 已提交
2655
create_test_act_fp16_class(TestLog10, atol=5e-2)
2656
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
2657 2658
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
2659
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
2660 2661 2662 2663 2664 2665
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 已提交
2666
create_test_act_fp16_class(TestHardSwish)
A
Abhinav Arora 已提交
2667

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