test_activation_op.py 43.5 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 25
import paddle.nn as nn
import paddle.nn.functional as functional
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 75
class TestParameter(object):
    def test_out(self):
        with fluid.program_guard(fluid.Program()):
            data = fluid.layers.data(name="X", shape=[1])
76
            out = eval("fluid.layers.%s(data, out=data)" % self.op_type)
77 78 79 80 81 82 83 84 85
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result = exe.run(feed={"X": np.array([0.1])},
                             fetch_list=[data, out])
            self.assertEqual(result[0], result[1])

    def test_out_name(self):
        with fluid.program_guard(fluid.Program()):
            data = fluid.layers.data(name="X", shape=[1])
86 87
            out = eval("fluid.layers.%s(data, name='Y', out=data)" %
                       self.op_type)
88 89 90 91 92 93 94 95 96 97
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result = exe.run(feed={"X": np.array([0.1])},
                             fetch_list=[data, out])
            self.assertEqual(result[0], result[1])

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


C
chengduo 已提交
103
class TestSigmoid(TestActivation):
Q
qijun 已提交
104 105
    def setUp(self):
        self.op_type = "sigmoid"
106 107 108 109 110 111 112
        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 已提交
113

114 115 116
    def init_dtype(self):
        self.dtype = np.float32

117
    def test_check_grad(self):
118 119 120 121
        if self.dtype == np.float16:
            return
        self.check_grad(['X'], 'Out', max_relative_error=0.01)

122

C
chengduo 已提交
123
class TestLogSigmoid(TestActivation):
124 125
    def setUp(self):
        self.op_type = "logsigmoid"
126 127 128 129 130 131 132
        self.init_dtype()

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

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

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


140
class TestTanh(TestActivation):
141 142
    def setUp(self):
        self.op_type = "tanh"
143 144 145 146 147 148
        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}
149 150

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

155
    def init_dtype(self):
156 157 158
        #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.	
159 160
        self.dtype = np.float32

161

C
chengduo 已提交
162
class TestTanhShrink(TestActivation):
K
Kavya Srinet 已提交
163 164
    def setUp(self):
        self.op_type = "tanh_shrink"
165 166 167 168 169 170 171
        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 已提交
172 173

    def test_check_grad(self):
174 175
        if self.dtype == np.float16:
            return
176
        self.check_grad(['X'], 'Out')
K
Kavya Srinet 已提交
177

178

C
chengduo 已提交
179
class TestHardShrink(TestActivation):
180 181
    def setUp(self):
        self.op_type = "hard_shrink"
182 183
        self.init_dtype()

184
        threshold = 0.5
Z
zhupengyang 已提交
185
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype) * 10
186 187
        out = np.copy(x)
        out[(out >= -threshold) & (out <= threshold)] = 0
188 189

        self.attrs = {'lambda': threshold}
190 191
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
192 193

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


199 200 201 202 203 204 205 206 207 208 209 210 211
class TestHardShrinkOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
            self.assertRaises(TypeError, fluid.layers.hard_shrink, 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_shrink, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.data(name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.hard_shrink(x_fp16)


C
chengduo 已提交
212
class TestSoftShrink(TestActivation):
213 214
    def setUp(self):
        self.op_type = "softshrink"
215 216
        self.init_dtype()

217
        lambda_val = 0.1
Z
zhupengyang 已提交
218
        x = np.random.uniform(0.25, 10, [10, 12]).astype(self.dtype)
219 220 221 222
        out = np.copy(x)
        out = (out < -lambda_val) * (out + lambda_val) + (out > lambda_val) * (
            out - lambda_val)

223
        self.attrs = {'lambda': lambda_val}
224 225
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
226 227

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

232

233 234 235 236 237 238 239 240 241 242 243 244 245
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)


246
class TestSqrt(TestActivation):
247 248
    def setUp(self):
        self.op_type = "sqrt"
249 250 251 252 253 254 255
        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}
256 257

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

262

Z
zhoukunsheng 已提交
263 264 265 266 267
class TestRsqrt(TestActivation):
    def setUp(self):
        self.op_type = "rsqrt"
        self.init_dtype()

Z
zhupengyang 已提交
268
        x = np.random.uniform(0.1, 1, [10, 12]).astype(self.dtype) * 10
Z
zhoukunsheng 已提交
269 270 271 272 273 274 275 276 277 278 279
        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 已提交
280
class TestAbs(TestActivation):
281 282
    def setUp(self):
        self.op_type = "abs"
283 284
        self.init_dtype()

285
        x = np.random.uniform(-1, 1, [4, 25]).astype(self.dtype)
C
chengduo 已提交
286
        # Because we set delta = 0.005 in calculating numeric gradient,
Q
qijun 已提交
287
        # if x is too small, such as 0.002, x_neg will be -0.003
C
chengduo 已提交
288
        # x_pos will be 0.007, so the numeric gradient is inaccurate.
Q
qijun 已提交
289 290
        # we should avoid this
        x[np.abs(x) < 0.005] = 0.02
291 292 293 294
        out = np.abs(x)

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

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

301

C
chengduo 已提交
302
class TestCeil(TestActivation):
D
dzhwinter 已提交
303 304
    def setUp(self):
        self.op_type = "ceil"
305 306
        self.init_dtype()

Z
zhupengyang 已提交
307
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
308 309 310 311
        out = np.ceil(x)

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

D
dzhwinter 已提交
313
    # The same reason with TestFloor
C
chengduo 已提交
314
    def test_check_grad(self):
315 316 317
        pass


C
chengduo 已提交
318
class TestFloor(TestActivation):
D
dzhwinter 已提交
319 320
    def setUp(self):
        self.op_type = "floor"
321 322
        self.init_dtype()

Z
zhupengyang 已提交
323
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
324 325 326 327
        out = np.floor(x)

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

D
dzhwinter 已提交
329
    # the gradient on floor, ceil, round is undefined.
330
    # we return zero as gradient, but the numpy return nan
C
chengduo 已提交
331 332
    # The same reason with TestFloor
    def test_check_grad(self):
333 334 335
        pass


C
chengduo 已提交
336
class TestCos(TestActivation):
C
add cos  
chengduoZH 已提交
337 338
    def setUp(self):
        self.op_type = "cos"
339 340
        self.init_dtype()

Z
zhupengyang 已提交
341
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
342 343 344 345
        out = np.cos(x)

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

    def test_check_grad(self):
348 349
        if self.dtype == np.float16:
            return
350
        self.check_grad(['X'], 'Out')
C
add sin  
chengduoZH 已提交
351

352

353 354 355 356 357
class TestAcos(TestActivation):
    def setUp(self):
        self.op_type = "acos"
        self.init_dtype()

Z
zhupengyang 已提交
358
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
359 360 361 362 363 364 365 366
        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
367
        self.check_grad(['X'], 'Out')
368 369


370
class TestSin(TestActivation):
C
add sin  
chengduoZH 已提交
371 372
    def setUp(self):
        self.op_type = "sin"
373 374
        self.init_dtype()

Z
zhupengyang 已提交
375
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
376 377 378 379
        out = np.sin(x)

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

    def test_check_grad(self):
382 383
        if self.dtype == np.float16:
            return
384
        self.check_grad(['X'], 'Out')
C
add cos  
chengduoZH 已提交
385 386


387 388 389 390 391
class TestAsin(TestActivation):
    def setUp(self):
        self.op_type = "asin"
        self.init_dtype()

Z
zhupengyang 已提交
392
        x = np.random.uniform(-0.95, 0.95, [10, 12]).astype(self.dtype)
393 394 395 396 397 398 399 400
        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
401
        self.check_grad(['X'], 'Out')
402 403


C
chengduo 已提交
404
class TestRound(TestActivation):
D
dzhwinter 已提交
405 406
    def setUp(self):
        self.op_type = "round"
407 408
        self.init_dtype()

Z
zhupengyang 已提交
409
        x = np.random.uniform(-1, 1, [10, 12]).astype(self.dtype)
410 411 412 413
        out = np.round(x)

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

C
chengduo 已提交
415
    def test_check_grad(self):
416 417 418
        pass


C
chengduo 已提交
419
class TestRelu(TestActivation):
420
    def setUp(self):
Q
qijun 已提交
421
        self.op_type = "relu"
K
Kexin Zhao 已提交
422 423 424
        self.init_dtype()

        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
Q
qijun 已提交
425 426
        # The same reason with TestAbs
        x[np.abs(x) < 0.005] = 0.02
K
Kexin Zhao 已提交
427 428 429 430
        out = np.maximum(x, 0)

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

    def test_check_grad(self):
K
Kexin Zhao 已提交
433 434
        if self.dtype == np.float16:
            return
435
        self.check_grad(['X'], 'Out')
A
Adam 已提交
436 437


438 439 440 441
class TestReluOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program()):
            # The input type must be Variable.
442
            self.assertRaises(TypeError, fluid.layers.relu, 1)
443 444 445 446 447 448 449 450 451
            # 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.relu, x_int32)
            # support the input dtype is float16
            x_fp16 = fluid.layers.data(
                name='x_fp16', shape=[12, 10], dtype='float16')
            fluid.layers.relu(x_fp16)


A
Adam 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
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
468
        self.check_grad(['X'], 'Out')
469 470


471 472 473 474 475 476 477 478 479 480 481 482 483 484
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)


485 486 487 488 489 490 491 492 493 494
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 已提交
495 496 497
    def setUp(self):
        self.op_type = "gelu"
        self.init_dtype()
498 499 500
        approximate = True
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
        out = gelu(x, approximate)
C
Clementine 已提交
501

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        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 已提交
517
        x = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
518
        out = gelu(x, approximate)
C
Clementine 已提交
519 520 521

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
        self.outputs = {'Out': out}
522
        self.attrs = {"approximate": approximate}
C
Clementine 已提交
523 524 525 526

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


C
chengduo 已提交
530
class TestBRelu(TestActivation):
531 532
    def setUp(self):
        self.op_type = "brelu"
533 534
        self.init_dtype()

Z
zhupengyang 已提交
535
        x = np.random.uniform(-5, 10, [10, 12]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
536 537
        t_min = 1.0
        t_max = 4.0
Q
qijun 已提交
538 539
        # The same with TestAbs
        x[np.abs(x - t_min) < 0.005] = t_min + 0.02
Q
qijun 已提交
540
        x[np.abs(x - t_max) < 0.005] = t_max + 0.02
541 542 543
        t = np.copy(x)
        t[t < t_min] = t_min
        t[t > t_max] = t_max
544 545 546

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

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

554

555 556 557 558 559 560 561 562 563 564 565 566 567 568
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 已提交
569
class TestRelu6(TestActivation):
K
Kavya Srinet 已提交
570
    def setUp(self):
571
        self.op_type = "relu6"
572 573
        self.init_dtype()

Z
zhupengyang 已提交
574
        x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)
575 576 577 578
        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
579
        out = np.minimum(np.maximum(x, 0), threshold)
580

581
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
582
        self.attrs = {'threshold': threshold}
583
        self.outputs = {'Out': out}
K
Kavya Srinet 已提交
584

585 586 587
    def test_check_grad(self):
        if self.dtype == np.float16:
            return
588
        self.check_grad(['X'], 'Out')
589 590


591 592 593 594 595 596 597 598 599 600 601 602 603
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 已提交
604 605 606 607 608
class TestHardSwish(TestActivation):
    def setUp(self):
        self.op_type = 'hard_swish'
        self.init_dtype()

Z
zhupengyang 已提交
609
        x = np.random.uniform(-6, 6, [10, 12]).astype(self.dtype)
H
huangjun12 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
        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
625
        self.check_grad(['X'], 'Out')
H
huangjun12 已提交
626 627


628 629 630 631 632 633 634 635 636 637 638 639 640
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 已提交
641
class TestSoftRelu(TestActivation):
642 643
    def setUp(self):
        self.op_type = "soft_relu"
644 645 646
        self.init_dtype()

        x = np.random.uniform(-3, 3, [4, 4]).astype(self.dtype)
Y
Yang Yang(Tony) 已提交
647
        threshold = 2.0
Q
qijun 已提交
648 649
        # The same reason with TestAbs
        x[np.abs(x - threshold) < 0.005] = threshold + 0.02
Z
zhupengyang 已提交
650
        x[np.abs(x + threshold) < 0.005] = -threshold - 0.02
651 652 653
        t = np.copy(x)
        t[t < -threshold] = -threshold
        t[t > threshold] = threshold
654 655 656 657 658
        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}
659 660

    def test_check_grad(self):
661 662
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
663
        self.check_grad(['X'], 'Out', max_relative_error=0.02)
664

665

666 667 668 669 670 671 672 673 674 675 676 677 678
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)


C
chengduo 已提交
679
class TestELU(TestActivation):
680 681
    def setUp(self):
        self.op_type = "elu"
682 683
        self.init_dtype()

Z
zhupengyang 已提交
684
        x = np.random.uniform(-3, 3, [10, 12]).astype(self.dtype)
685
        alpha = 1.
686
        out = np.maximum(0, x) + np.minimum(0, alpha * (np.exp(x) - 1))
687 688 689 690
        # 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}
691
        self.outputs = {'Out': out}
692 693

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


699
class TestELUOpError(unittest.TestCase):
700 701 702 703 704 705 706 707 708 709 710
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of elu_op must be Variable.
            x1 = fluid.create_lod_tensor(
                np.array([[-1]]), [[1]], fluid.CPUPlace())
            self.assertRaises(TypeError, fluid.layers.elu, x1)
            # The input dtype of elu_op must be float16 float32 or float64.
            x2 = fluid.layers.data(name='x2', shape=[4], dtype="int32")
            self.assertRaises(TypeError, fluid.layers.elu, x2)


C
chengduo 已提交
711
class TestReciprocal(TestActivation):
Q
qijun 已提交
712 713
    def setUp(self):
        self.op_type = "reciprocal"
714 715 716 717 718 719 720
        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 已提交
721 722

    def test_check_grad(self):
723 724
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
725
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Q
qijun 已提交
726 727


C
chengduo 已提交
728
class TestLog(TestActivation):
Q
qijun 已提交
729 730
    def setUp(self):
        self.op_type = "log"
731 732 733 734 735 736 737
        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 已提交
738 739

    def test_check_grad(self):
740 741
        if self.dtype == np.float16:
            return
742
        self.check_grad(['X'], 'Out')
Q
qijun 已提交
743

744 745 746 747 748 749 750 751 752
    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)

753

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
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")
            res_log1p = fluid.layers.data(
                name="res_log1p",
                shape=[11, 17],
                append_batch_size=False,
                dtype="float64")

784 785
            out1 = fluid.layers.log1p(data_x)
            out2 = fluid.layers.log1p(data_x, out=res_log1p)
786 787 788 789 790 791 792 793 794 795 796 797 798
            exe = fluid.Executor(place=fluid.CPUPlace())
            exe.run(fluid.default_startup_program())
            res1, res_in = exe.run(fluid.default_main_program(),
                                   feed={"data_x": input_x},
                                   fetch_list=[out1, res_log1p])
        expected_res = np.log1p(input_x)
        np.testing.assert_allclose(res1, expected_res)
        np.testing.assert_allclose(res_in, expected_res)

        # 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)
799
            z = fluid.layers.log1p(data_x)
800 801 802 803 804
            np_z = z.numpy()
            z_expected = np.array(np.log1p(np_x))
        np.testing.assert_allclose(np_z, z_expected)


C
chengduo 已提交
805
class TestSquare(TestActivation):
Q
qijun 已提交
806 807
    def setUp(self):
        self.op_type = "square"
808 809 810 811 812 813 814
        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 已提交
815 816

    def test_check_grad(self):
817 818
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
819
        self.check_grad(['X'], 'Out', max_relative_error=0.007)
Q
qijun 已提交
820

821

C
chengduo 已提交
822
class TestPow(TestActivation):
823 824
    def setUp(self):
        self.op_type = "pow"
825 826 827 828 829 830
        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) 已提交
831
        self.attrs = {'factor': 3.0}
832
        self.outputs = {'Out': out}
833 834

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

839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
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
862
        self.check_grad(['X'], 'Out')
863 864 865 866 867

    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")
868 869 870 871 872
        res = fluid.layers.data(
            name="res",
            shape=[11, 17],
            append_batch_size=False,
            dtype="float32")
873 874 875 876 877 878 879

        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)

        exe = fluid.Executor(place=fluid.CPUPlace())
880 881 882
        res_1, res_2 = exe.run(fluid.default_main_program(),
                               feed={"x": input},
                               fetch_list=[out_1, out_2])
883 884 885 886

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

887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
    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)

910

C
chengduo 已提交
911
class TestSTanh(TestActivation):
912 913
    def setUp(self):
        self.op_type = "stanh"
914 915 916
        self.init_dtype()

        x = np.random.uniform(0.1, 1, [11, 17]).astype(self.dtype)
917 918
        scale_a = 2.0 / 3.0
        scale_b = 1.7159
919 920 921
        out = scale_b * np.tanh(x * scale_a)

        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}
922
        self.attrs = {'scale_a': scale_a, 'scale_b': scale_b}
923
        self.outputs = {'Out': out}
924

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

930

931 932 933 934 935 936 937 938 939 940 941 942 943
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 已提交
944
class TestSoftplus(TestActivation):
K
kexinzhao 已提交
945 946
    def setUp(self):
        self.op_type = "softplus"
947
        self.init_dtype()
C
chengduo 已提交
948
        self.dtype = np.float64
949 950 951 952 953 954

        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 已提交
955 956

    def test_check_grad(self):
957 958
        if self.dtype == np.float16:
            return
959
        self.check_grad(['X'], 'Out')
K
kexinzhao 已提交
960

961

C
chengduo 已提交
962
class TestSoftsign(TestActivation):
963 964
    def setUp(self):
        self.op_type = "softsign"
965 966 967 968 969 970 971
        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}
972 973

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


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

984
        threshold = 0.25
Z
zhupengyang 已提交
985
        self.delta = 0.005
986
        X = np.random.uniform(-1, 1, [11, 17]).astype(self.dtype)
987 988

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

992
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(X)}
993
        self.attrs = {'threshold': threshold}
994
        self.outputs = {'Out': out}
995 996

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


1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
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 已提交
1015
class TestHardSigmoid(TestActivation):
1016 1017
    def setUp(self):
        self.op_type = "hard_sigmoid"
1018 1019
        self.init_dtype()

Z
zhupengyang 已提交
1020
        X = np.random.uniform(-5, 5, [10, 12]).astype("float32")
1021 1022 1023 1024 1025
        slope = 0.2
        offset = 0.5
        lower_threshold = -offset / slope
        upper_threshold = (1 - offset) / slope

Z
zhupengyang 已提交
1026 1027
        self.delta = 0.005

1028
        # Same reason as TestAbs
Z
zhupengyang 已提交
1029 1030
        X[(X - lower_threshold) < self.delta] = lower_threshold - 0.02
        X[(X - upper_threshold) < self.delta] = upper_threshold + 0.02
1031 1032

        temp = X * slope + offset
1033 1034 1035 1036
        out = np.maximum(0.0, np.minimum(1.0, temp))

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

    def test_check_grad(self):
1039 1040
        if self.dtype == np.float16:
            return
Z
zhupengyang 已提交
1041
        self.check_grad(['X'], 'Out')
1042

1043

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
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 已提交
1057
class TestSwish(TestActivation):
A
Abhinav Arora 已提交
1058 1059
    def setUp(self):
        self.op_type = "swish"
1060 1061 1062 1063 1064 1065 1066 1067 1068
        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 已提交
1069 1070

    def test_check_grad(self):
1071 1072
        if self.dtype == np.float16:
            return
F
fengjiayi 已提交
1073
        self.check_grad(['X'], 'Out', max_relative_error=0.008)
A
Abhinav Arora 已提交
1074

1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
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)


1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
#------------------ 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')


1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
#------------------ 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 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
#------------------ 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
1151

C
chengduo 已提交
1152
        def test_check_output(self):
1153
            place = core.CUDAPlace(0)
C
chengduo 已提交
1154 1155 1156
            support_fp16 = core.is_float16_supported(place)
            if support_fp16:
                self.check_output_with_place(place, atol=atol)
1157

C
chengduo 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        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)
1182
create_test_act_fp16_class(TestAcos, grad_atol=0.85)
C
chengduo 已提交
1183
create_test_act_fp16_class(TestSin)
1184
create_test_act_fp16_class(TestAsin)
C
chengduo 已提交
1185 1186
create_test_act_fp16_class(TestRound, grad_check=False)
create_test_act_fp16_class(TestRelu)
C
Clementine 已提交
1187
create_test_act_fp16_class(TestGelu)
C
chengduo 已提交
1188 1189 1190 1191 1192 1193
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)
1194
create_test_act_fp16_class(TestLog1p, grad_atol=0.9)
C
chengduo 已提交
1195 1196
create_test_act_fp16_class(TestSquare)
create_test_act_fp16_class(TestPow, atol=5e-2)
1197
create_test_act_fp16_class(TestPow_factor_tensor, atol=5e-2)
C
chengduo 已提交
1198 1199 1200 1201 1202 1203
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 已提交
1204
create_test_act_fp16_class(TestHardSwish)
A
Abhinav Arora 已提交
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

class TestNNReluAPI(unittest.TestCase):
    def setUp(self):
        self.init_data()

    def init_data(self):
        self.x_shape = [10, 12]
        self.x = np.random.uniform(-1, 1, self.x_shape).astype(np.float32)
        self.y = self.ref_forward(self.x)

    def ref_forward(self, x):
        return np.maximum(x, 0)

    def ref_backward(self, y, dy):
        y_t = y.copy()
        y_t[y_t > 0] = 1
        return y_t * dy

    def check_api(self, place=fluid.CPUPlace(), inplace=False):
        main_program = Program()
        myrelu = nn.ReLU(inplace)
        with fluid.program_guard(main_program):
            x = fluid.data(name='x', shape=self.x_shape)
            x.stop_gradient = False
            y = myrelu(x)
            fluid.backward.append_backward(fluid.layers.mean(y))
        exe = fluid.Executor(place)
        out = exe.run(main_program,
                      feed={'x': self.x},
                      fetch_list=[y, y.grad_name, x.grad_name])
        self.assertTrue(np.allclose(out[0], self.y))
        self.assertTrue(np.allclose(out[2], self.ref_backward(self.y, out[1])))

        with fluid.dygraph.guard(place):
            x = fluid.dygraph.to_variable(self.x)
            y = myrelu(x)
        self.assertTrue(np.allclose(y.numpy(), self.y))

    def test_check_api(self):
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
            for inplace in [True, False]:
                self.check_api(place, inplace)


class TestNNFunctionalReluAPI(unittest.TestCase):
    def setUp(self):
        self.init_data()

    def init_data(self):
        self.x_shape = [10, 12]
        self.x = np.random.uniform(-1, 1, self.x_shape).astype(np.float32)
        self.y = self.ref_forward(self.x)

    def ref_forward(self, x):
        return np.maximum(x, 0)

    def test_check_api(self):
        main_program = Program()
        with fluid.program_guard(main_program):
            x = fluid.data(name='x', shape=self.x_shape)
            y = functional.relu(x)
        exe = fluid.Executor(fluid.CPUPlace())
        out = exe.run(main_program, feed={'x': self.x}, fetch_list=[y])
        self.assertTrue(np.allclose(out[0], self.y))


1275 1276 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 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
class TestNNSigmoidAPI(unittest.TestCase):
    def setUp(self):
        self.init_data()

    def init_data(self):
        self.x_shape = [10, 15]
        self.x = np.random.uniform(-1, 1, self.x_shape).astype(np.float32)
        self.y = self.ref_forward(self.x)

    def ref_forward(self, x):
        return 1 / (1 + np.exp(-x))

    def ref_backward(self, y, dy):
        return dy * y * (1 - y)

    def check_api(self, place=fluid.CPUPlace(), inplace=False):
        main_program = Program()
        mysigmoid = nn.Sigmoid(inplace)
        with fluid.program_guard(main_program):
            x = fluid.data(name='x', shape=self.x_shape)
            x.stop_gradient = False
            y = mysigmoid(x)
            fluid.backward.append_backward(fluid.layers.mean(y))
        exe = fluid.Executor(place)
        out = exe.run(main_program,
                      feed={'x': self.x},
                      fetch_list=[y, y.grad_name, x.grad_name])
        self.assertTrue(np.allclose(out[0], self.y))
        self.assertTrue(np.allclose(out[2], self.ref_backward(self.y, out[1])))

        with fluid.dygraph.guard(place):
            x = fluid.dygraph.to_variable(self.x)
            y = mysigmoid(x)
        self.assertTrue(np.allclose(y.numpy(), self.y))

    def test_check_api(self):
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
            for inplace in [True, False]:
                self.check_api(place, inplace)


class TestNNFunctionalSigmoidAPI(unittest.TestCase):
    def setUp(self):
        self.init_data()

    def init_data(self):
        self.x_shape = [10, 15]
        self.x = np.random.uniform(-1, 1, self.x_shape).astype(np.float32)
        self.y = self.ref_forward(self.x)

    def ref_forward(self, x):
        return 1 / (1 + np.exp(-x))

    def test_check_api(self):
        main_program = Program()
        with fluid.program_guard(main_program):
            x = fluid.data(name='x', shape=self.x_shape)
            y = functional.sigmoid(x)
        exe = fluid.Executor(fluid.CPUPlace())
        out = exe.run(main_program, feed={'x': self.x}, fetch_list=[y])
        self.assertTrue(np.allclose(out[0], self.y))


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