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

15 16
from __future__ import print_function

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


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

        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 已提交
56 57 58 59 60

    def test_check_output(self):
        self.check_output()

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

65
    def init_dtype(self):
66
        self.dtype = np.float64
67

68 69 70
    def init_kernel_type(self):
        pass

Q
qijun 已提交
71

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

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

        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 已提交
103

104 105 106
    def init_dtype(self):
        self.dtype = np.float32

107
    def test_check_grad(self):
108 109 110 111
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.01)

112

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

        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = np.log(1 / (1 + np.exp(-x)))

121
        self.inputs = {'X': x}
122
        self.outputs = {'Out': out}
123 124

    def test_check_grad(self):
125 126
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
127
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
128 129


130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
class TestLogSigmoidAPI(unittest.TestCase):
    # test paddle.nn.LogSigmoid, paddle.nn.functional.logsigmoid
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [11, 17])
            out1 = F.logsigmoid(x)
            m = paddle.nn.LogSigmoid()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in res:
            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.logsigmoid(x)
        m = paddle.nn.LogSigmoid()
        out2 = m(x)
        out_ref = np.log(1 / (1 + np.exp(-self.x_np)))
        for r in [out1, out2]:
            self.assertEqual(np.allclose(out_ref, r.numpy()), True)
        paddle.enable_static()

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.logsigmoid, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.data(name='x_int32', shape=[11, 17], dtype='int32')
            self.assertRaises(TypeError, F.logsigmoid, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[11, 17], dtype='float16')
            F.logsigmoid(x_fp16)


172
class TestTanh(TestActivation, TestParameter):
173 174
    def setUp(self):
        self.op_type = "tanh"
175 176 177 178 179 180
        self.init_dtype()
        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}
181 182

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

187 188 189 190 191 192
    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

193

194
class TestAtan(TestActivation, TestParameter):
195 196 197 198 199 200 201 202 203 204 205 206 207
    def setUp(self):
        self.op_type = "atan"
        self.init_dtype()

        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
208
        self.check_grad(['X'], 'Out')
209

W
WuHaobo 已提交
210 211 212 213 214 215 216 217 218 219 220
    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)

221 222 223 224 225 226 227 228
    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)

229

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
class TestSinh(TestActivation):
    def setUp(self):
        self.op_type = "sinh"
        self.init_dtype()

        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()

        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)


C
chengduo 已提交
372
class TestTanhShrink(TestActivation):
K
Kavya Srinet 已提交
373 374
    def setUp(self):
        self.op_type = "tanh_shrink"
375 376 377 378 379 380 381
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [10, 17]).astype(self.dtype)
        out = x - np.tanh(x)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
382 383

    def test_check_grad(self):
384 385
        if self.dtype == np.float16:
            return
386
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
387

388

389 390 391 392 393 394
def ref_hardshrink(x, threshold):
    out = np.copy(x)
    out[(out >= -threshold) & (out <= threshold)] = 0
    return out


C
chengduo 已提交
395
class TestHardShrink(TestActivation):
396 397
    def setUp(self):
        self.op_type = "hard_shrink"
398 399
        self.init_dtype()

400
        threshold = 0.5
Z
zhupengyang 已提交
401
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype) * 10
402
        out = ref_hardshrink(x, threshold)
403

404 405
        self.attrs = {'threshold': threshold}
        self.inputs = {'X': x}
406
        self.outputs = {'Out': out}
407 408

    def test_check_grad(self):
409 410
        if self.dtype == np.float16:
            return
411
        self.check_grad(['X'], 'Out')
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
class TestHardShrinkAPI(unittest.TestCase):
    # test paddle.nn.Hardshrink, paddle.nn.functional.hardshrink
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.hardshrink(x)
            hd = paddle.nn.Hardshrink()
            out2 = hd(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = ref_hardshrink(self.x_np, 0.5)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_variable(self.x_np)
        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):
        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)

460
    def test_errors(self):
461
        with paddle.static.program_guard(paddle.static.Program()):
462
            # The input type must be Variable.
463
            self.assertRaises(TypeError, F.hardshrink, 1)
464
            # The input dtype must be float16, float32, float64.
465 466
            x_int32 = paddle.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, F.hardshrink, x_int32)
467
            # support the input dtype is float16
468 469
            x_fp16 = paddle.data(name='x_fp16', shape=[12, 10], dtype='float16')
            F.hardshrink(x_fp16)
470 471


C
chengduo 已提交
472
class TestSoftShrink(TestActivation):
473 474
    def setUp(self):
        self.op_type = "softshrink"
475 476
        self.init_dtype()

477
        lambda_val = 0.1
Z
zhupengyang 已提交
478
        x = np.random.uniform(0.25, 10, [10, 12]).astype(self.dtype)
479 480 481 482
        out = np.copy(x)
        out = (out < -lambda_val) * (out + lambda_val) + (out > lambda_val) * (
            out - lambda_val)

483
        self.attrs = {'lambda': lambda_val}
484 485
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
486 487

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

492

493 494 495 496 497 498 499 500 501 502 503 504 505
class TestSoftShrinkOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.softshrink, 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.softshrink, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.softshrink(x_fp16)


506
class TestSqrt(TestActivation, TestParameter):
507 508
    def setUp(self):
        self.op_type = "sqrt"
509 510 511 512 513 514 515
        self.init_dtype()

        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}
516 517

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

522

Z
zhoukunsheng 已提交
523 524 525 526 527
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
        self.init_dtype()

Z
zhupengyang 已提交
528
        x = np.random.uniform(0.1, 1, [10, 12]).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
529 530 531 532 533 534 535 536 537 538 539
        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 已提交
540
class TestAbs(TestActivation):
541 542
    def setUp(self):
        self.op_type = "abs"
543 544
        self.init_dtype()

545
        x = np.random.uniform(-1, 1, [4, 25]).astype(self.dtype)
C
chengduo 已提交
546
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
547
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
548
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
549 550
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
551 552 553 554
        out = np.abs(x)

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

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

561

C
chengduo 已提交
562
class TestCeil(TestActivation):
D
dzhwinter 已提交
563 564
    def setUp(self):
        self.op_type = "ceil"
565 566
        self.init_dtype()

Z
zhupengyang 已提交
567
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
568 569 570 571
        out = np.ceil(x)

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

D
dzhwinter 已提交
573
    # The same reason with TestFloor
C
chengduo 已提交
574
    def test_check_grad(self):
575 576 577
        pass


C
chengduo 已提交
578
class TestFloor(TestActivation):
D
dzhwinter 已提交
579 580
    def setUp(self):
        self.op_type = "floor"
581 582
        self.init_dtype()

Z
zhupengyang 已提交
583
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
584 585 586 587
        out = np.floor(x)

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

D
dzhwinter 已提交
589
    # the gradient on floor, ceil, round is undefined.
590
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
591 592
    # The same reason with TestFloor
    def test_check_grad(self):
593 594 595
        pass


C
chengduo 已提交
596
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
597 598
    def setUp(self):
        self.op_type = "cos"
599 600
        self.init_dtype()

Z
zhupengyang 已提交
601
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
602 603 604 605
        out = np.cos(x)

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

    def test_check_grad(self):
608 609
        if self.dtype == np.float16:
            return
610
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
611

612

613 614 615 616 617
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()

Z
zhupengyang 已提交
618
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
619 620 621 622 623 624 625 626
        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
627
        self.check_grad(['X'], 'Out')
628 629


630
class TestSin(TestActivation, TestParameter):
C
add sin  
chengduoZH 已提交
631 632
    def setUp(self):
        self.op_type = "sin"
633 634
        self.init_dtype()

Z
zhupengyang 已提交
635
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
636 637 638 639
        out = np.sin(x)

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

    def test_check_grad(self):
642 643
        if self.dtype == np.float16:
            return
644
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
645 646


647 648 649 650 651
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()

Z
zhupengyang 已提交
652
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
653 654 655 656 657 658 659 660
        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
661
        self.check_grad(['X'], 'Out')
662 663


C
chengduo 已提交
664
class TestRound(TestActivation):
D
dzhwinter 已提交
665 666
    def setUp(self):
        self.op_type = "round"
667 668
        self.init_dtype()

Z
zhupengyang 已提交
669
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
670 671 672 673
        out = np.round(x)

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

C
chengduo 已提交
675
    def test_check_grad(self):
676 677 678
        pass


C
chengduo 已提交
679
class TestRelu(TestActivation):
680
    def setUp(self):
Q
qijun 已提交
681
        self.op_type = "relu"
K
Kexin Zhao 已提交
682 683 684
        self.init_dtype()

        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
Q
qijun 已提交
685 686
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.02
K
Kexin Zhao 已提交
687 688
        out = np.maximum(x, 0)

689
        self.inputs = {'X': x}
K
Kexin Zhao 已提交
690
        self.outputs = {'Out': out}
691 692

    def test_check_grad(self):
K
Kexin Zhao 已提交
693 694
        if self.dtype == np.float16:
            return
695
        self.check_grad(['X'], 'Out')
A
Adam 已提交
696 697


698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
class TestReluAPI(unittest.TestCase):
    # test paddle.nn.ReLU, paddle.nn.functional.relu
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.relu(x)
            m = paddle.nn.ReLU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = np.maximum(self.x_np, 0)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

728
    def test_errors(self):
729
        with paddle.static.program_guard(paddle.static.Program()):
730
            # The input type must be Variable.
731
            self.assertRaises(TypeError, F.relu, 1)
732
            # The input dtype must be float16, float32, float64.
733 734
            x_int32 = paddle.data(name='x_int32', shape=[10, 12], dtype='int32')
            self.assertRaises(TypeError, F.relu, x_int32)
735
            # support the input dtype is float16
736 737
            x_fp16 = paddle.data(name='x_fp16', shape=[10, 12], dtype='float16')
            F.relu(x_fp16)
738 739


A
Adam 已提交
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
class TestLeakyRelu(TestActivation):
    def setUp(self):
        self.op_type = "leaky_relu"
        self.init_dtype()

        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.02
        out = np.maximum(x, 0.02 * 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
756
        self.check_grad(['X'], 'Out')
757 758


759 760 761 762 763 764 765 766 767 768 769 770 771 772
class TestLeakyReluOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.leaky_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.leaky_relu, x_int32)
            # support the input dtype is float32
            x_fp16 = fluid.layers.data(
                name='x_fp16', shape=[12, 10], dtype='float32')
            fluid.layers.leaky_relu(x_fp16)


773 774 775 776 777 778 779 780 781 782
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 已提交
783 784 785
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
786 787 788
        approximate = True
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
789

790
        self.inputs = {'X': x}
791 792 793 794 795 796 797 798 799 800 801 802 803 804
        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
C
Clementine 已提交
805
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
806
        out = gelu(x, approximate)
C
Clementine 已提交
807

808
        self.inputs = {'X': x}
C
Clementine 已提交
809
        self.outputs = {'Out': out}
810
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
811 812 813 814

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


818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
class TestGELUAPI(unittest.TestCase):
    # test paddle.nn.GELU, paddle.nn.functional.gelu
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [11, 17]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [11, 17])
            out1 = F.gelu(x)
            m = paddle.nn.GELU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = gelu(self.x_np, False)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

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

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.gelu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.data(name='x_int32', shape=[11, 17], dtype='int32')
            self.assertRaises(TypeError, F.gelu, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[11, 17], dtype='float16')
            F.gelu(x_fp16)


C
chengduo 已提交
867
class TestBRelu(TestActivation):
868 869
    def setUp(self):
        self.op_type = "brelu"
870 871
        self.init_dtype()

Z
zhupengyang 已提交
872
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
873 874
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
875 876
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
877
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
878 879 880
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
881 882 883

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

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

891

892 893 894 895 896 897 898 899 900 901 902 903 904 905
class TestBReluOpError(unittest.TestCase):
    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)


C
chengduo 已提交
906
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
907
    def setUp(self):
908
        self.op_type = "relu6"
909 910
        self.init_dtype()

Z
zhupengyang 已提交
911
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
912 913 914 915
        threshold = 6.0
        # The same with TestAbs
        x[np.abs(x) < 0.005] = 0.02
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
916
        out = np.minimum(np.maximum(x, 0), threshold)
917

918
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
919
        self.attrs = {'threshold': threshold}
920
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
921

922 923 924
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
925
        self.check_grad(['X'], 'Out')
926 927


928 929 930 931 932 933 934 935 936 937 938 939 940
class TestRelu6OpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.relu6, 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.relu6, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.relu6(x_fp16)


H
huangjun12 已提交
941 942 943 944 945
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()

Z
zhupengyang 已提交
946
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
        threshold = 6.0
        scale = 6.0
        offset = 3.0
        #the same with TestAbs
        x[np.abs(x + offset) < 0.005] = 0.02
        x[np.abs(x - threshold + offset) < 0.005] = threshold - offset + 0.02
        out = x * np.minimum(np.maximum(x + offset, 0), threshold) / scale

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

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


965 966 967 968 969 970 971 972 973 974 975 976 977
class TestHardSwishOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hard_swish, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.hard_swish, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.hard_swish(x_fp16)


C
chengduo 已提交
978
class TestSoftRelu(TestActivation):
979 980
    def setUp(self):
        self.op_type = "soft_relu"
981 982 983
        self.init_dtype()

        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
984
        threshold = 2.0
Q
qijun 已提交
985 986
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
987
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
988 989 990
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
991 992 993 994 995
        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}
996 997

    def test_check_grad(self):
998 999
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1000
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
1001

1002

1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
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)


1016 1017 1018 1019 1020
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 已提交
1021
class TestELU(TestActivation):
1022 1023
    def setUp(self):
        self.op_type = "elu"
1024 1025
        self.init_dtype()

Z
zhupengyang 已提交
1026
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
1027
        alpha = 1.
1028
        out = elu(x, alpha)
1029 1030 1031 1032
        # 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}
1033
        self.outputs = {'Out': out}
1034 1035

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


1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
class TestELUAPI(unittest.TestCase):
    # test paddle.nn.ELU, paddle.nn.functional.elu
    def setUp(self):
        self.x_np = np.random.uniform(-3, 3, [10, 12]).astype('float32')
        self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.data('X', [10, 12])
            out1 = F.elu(x)
            m = paddle.nn.ELU()
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = elu(self.x_np, 1.0)
        for r in res:
            self.assertEqual(np.allclose(out_ref, r), True)

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

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

1078
    def test_errors(self):
1079 1080 1081 1082 1083 1084 1085 1086 1087
        with paddle.static.program_guard(paddle.static.Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, F.elu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = paddle.data(name='x_int32', shape=[10, 12], dtype='int32')
            self.assertRaises(TypeError, F.elu, x_int32)
            # support the input dtype is float16
            x_fp16 = paddle.data(name='x_fp16', shape=[10, 12], dtype='float16')
            F.elu(x_fp16)
1088 1089


C
chengduo 已提交
1090
class TestReciprocal(TestActivation):
Q
qijun 已提交
1091 1092
    def setUp(self):
        self.op_type = "reciprocal"
1093 1094 1095 1096 1097 1098 1099
        self.init_dtype()

        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 已提交
1100 1101

    def test_check_grad(self):
1102 1103
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1104
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Q
qijun 已提交
1105 1106


C
chengduo 已提交
1107
class TestLog(TestActivation):
Q
qijun 已提交
1108 1109
    def setUp(self):
        self.op_type = "log"
1110 1111 1112 1113 1114 1115 1116
        self.init_dtype()

        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 已提交
1117 1118

    def test_check_grad(self):
1119 1120
        if self.dtype == np.float16:
            return
1121
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1122

1123 1124 1125 1126 1127 1128 1129 1130 1131
    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)

1132

1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
class TestLog1p(TestActivation):
    def setUp(self):
        self.op_type = "log1p"
        self.init_dtype()

        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())
1161 1162 1163
            res1 = exe.run(fluid.default_main_program(),
                           feed={"data_x": input_x},
                           fetch_list=[out1])
1164
        expected_res = np.log1p(input_x)
1165
        self.assertTrue(np.allclose(res1, expected_res))
1166 1167 1168 1169 1170 1171 1172 1173

        # 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))
1174
        self.assertTrue(np.allclose(np_z, z_expected))
1175 1176


C
chengduo 已提交
1177
class TestSquare(TestActivation):
Q
qijun 已提交
1178 1179
    def setUp(self):
        self.op_type = "square"
1180 1181 1182 1183 1184 1185 1186
        self.init_dtype()

        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 已提交
1187 1188

    def test_check_grad(self):
1189 1190
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1191
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
Q
qijun 已提交
1192

1193

C
chengduo 已提交
1194
class TestPow(TestActivation):
1195 1196
    def setUp(self):
        self.op_type = "pow"
1197 1198 1199 1200 1201 1202
        self.init_dtype()

        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) 已提交
1203
        self.attrs = {'factor': 3.0}
1204
        self.outputs = {'Out': out}
1205 1206

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

1211

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
class TestPow_factor_tensor(TestActivation):
    def setUp(self):
        self.op_type = "pow"
        self.init_dtype()

        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
1234
        self.check_grad(['X'], 'Out')
1235 1236 1237 1238 1239

    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")
1240 1241 1242 1243 1244
        res = fluid.layers.data(
            name="res",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
1245 1246 1247 1248 1249

        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)
1250 1251 1252
        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)
1253 1254

        exe = fluid.Executor(place=fluid.CPUPlace())
W
WuHaobo 已提交
1255
        res_1, res_2, res, res_6 = exe.run(
1256 1257
            fluid.default_main_program(),
            feed={"x": input},
W
WuHaobo 已提交
1258
            fetch_list=[out_1, out_2, res, out_6])
1259 1260 1261

        assert np.array_equal(res_1, np.power(input, 2))
        assert np.array_equal(res_2, np.power(input, 3))
1262
        assert np.array_equal(res_6, np.power(input, 3))
1263

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
    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)

1287

C
chengduo 已提交
1288
class TestSTanh(TestActivation):
1289 1290
    def setUp(self):
        self.op_type = "stanh"
1291 1292 1293
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
1294 1295
        scale_a = 2.0 / 3.0
        scale_b = 1.7159
1296 1297 1298
        out = scale_b * np.tanh(x * scale_a)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
1299
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
1300
        self.outputs = {'Out': out}
1301

Q
qijun 已提交
1302
    def test_check_grad(self):
1303 1304
        if self.dtype == np.float16:
            return
1305
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
1306

1307

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
class TestSTanhOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.stanh, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.stanh, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.stanh(x_fp16)


C
chengduo 已提交
1321
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
1322 1323
    def setUp(self):
        self.op_type = "softplus"
1324
        self.init_dtype()
C
chengduo 已提交
1325
        self.dtype = np.float64
1326 1327 1328 1329 1330 1331

        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = np.log(1 + np.exp(x))

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
K
kexinzhao 已提交
1332 1333

    def test_check_grad(self):
1334 1335
        if self.dtype == np.float16:
            return
1336
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
1337

1338

C
chengduo 已提交
1339
class TestSoftsign(TestActivation):
1340 1341
    def setUp(self):
        self.op_type = "softsign"
1342 1343 1344 1345 1346 1347 1348
        self.init_dtype()

        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = np.divide(x, 1 + np.abs(x))

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

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


C
chengduo 已提交
1356
class TestThresholdedRelu(TestActivation):
1357 1358
    def setUp(self):
        self.op_type = "thresholded_relu"
1359 1360
        self.init_dtype()

1361
        threshold = 0.25
Z
zhupengyang 已提交
1362
        self.delta = 0.005
1363
        X = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
1364 1365

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

1369
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(X)}
1370
        self.attrs = {'threshold': threshold}
1371
        self.outputs = {'Out': out}
1372 1373

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


1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
class TestThresholdedReluOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.thresholded_relu, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.thresholded_relu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.thresholded_relu(x_fp16)


C
chengduo 已提交
1392
class TestHardSigmoid(TestActivation):
1393 1394
    def setUp(self):
        self.op_type = "hard_sigmoid"
1395 1396
        self.init_dtype()

Z
zhupengyang 已提交
1397
        X = np.random.uniform(-5, 5, [10, 12]).astype("float32")
1398 1399 1400 1401 1402
        slope = 0.2
        offset = 0.5
        lower_threshold = -offset / slope
        upper_threshold = (1 - offset) / slope

Z
zhupengyang 已提交
1403 1404
        self.delta = 0.005

1405
        # Same reason as TestAbs
Z
zhupengyang 已提交
1406 1407
        X[(X - lower_threshold) < self.delta] = lower_threshold - 0.02
        X[(X - upper_threshold) < self.delta] = upper_threshold + 0.02
1408 1409

        temp = X * slope + offset
1410 1411 1412 1413
        out = np.maximum(0.0, np.minimum(1.0, temp))

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

    def test_check_grad(self):
1416 1417
        if self.dtype == np.float16:
            return
Z
zhupengyang 已提交
1418
        self.check_grad(['X'], 'Out')
1419

1420

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
class TestHardSigmoidOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hard_sigmoid, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.hard_sigmoid, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.hard_sigmoid(x_fp16)


C
chengduo 已提交
1434
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
1435 1436
    def setUp(self):
        self.op_type = "swish"
1437 1438 1439 1440 1441 1442 1443 1444 1445
        self.init_dtype()

        X = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
        beta = 2.3
        out = X * expit(beta * X)

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

    def test_check_grad(self):
1448 1449
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1450
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
A
Abhinav Arora 已提交
1451

1452

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
class TestSwishOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.swish, 1)
            # The input dtype must be float16, float32, float64.
            x_int32 = fluid.data(name='x_int32', shape=[12, 10], dtype='int32')
            self.assertRaises(TypeError, fluid.layers.swish, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.swish(x_fp16)


1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
#------------------ 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')


1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
#------------------ 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 已提交
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
#------------------ Test Fp16 ----------------------
def create_test_act_fp16_class(parent,
                               atol=1e-3,
                               grad_check=True,
                               grad_atol=0.80):
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestActFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16
1528

C
chengduo 已提交
1529
        def test_check_output(self):
1530
            place = core.CUDAPlace(0)
C
chengduo 已提交
1531 1532 1533
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
1534

C
chengduo 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
        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)
create_test_act_fp16_class(TestTanhShrink)
create_test_act_fp16_class(TestHardShrink)
create_test_act_fp16_class(TestSoftShrink)
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)
1559
create_test_act_fp16_class(TestCosh, grad_atol=0.85)
1560
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
1561
create_test_act_fp16_class(TestSin)
1562
create_test_act_fp16_class(TestSinh)
1563 1564
create_test_act_fp16_class(TestAsin)
create_test_act_fp16_class(TestAtan)
C
chengduo 已提交
1565 1566
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
1567
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
1568 1569 1570 1571 1572 1573
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)
1574
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
1575 1576
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
1577
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
1578 1579 1580 1581 1582 1583
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 已提交
1584
create_test_act_fp16_class(TestHardSwish)
A
Abhinav Arora 已提交
1585

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