test_elementwise_add_op.py 24.0 KB
Newer Older
1
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
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 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# 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.
14

G
gongweibao 已提交
15
import unittest
16

G
gongweibao 已提交
17
import numpy as np
18

19
import paddle
20
import paddle.fluid as fluid
K
Kexin Zhao 已提交
21
import paddle.fluid.core as core
22 23 24
from paddle.fluid.tests.unittests.op_test import (
    OpTest,
    convert_float_to_uint16,
25
    skip_check_grad_ci,
26
)
G
gongweibao 已提交
27 28


K
Kexin Zhao 已提交
29
class TestElementwiseAddOp(OpTest):
30 31 32
    def init_kernel_type(self):
        self.use_mkldnn = False

G
gongweibao 已提交
33 34
    def setUp(self):
        self.op_type = "elementwise_add"
H
hong 已提交
35
        self.python_api = paddle.add
K
Kexin Zhao 已提交
36 37
        self.init_dtype()
        self.init_input_output()
38
        self.init_kernel_type()
K
Kexin Zhao 已提交
39
        self.init_axis()
K
Kexin Zhao 已提交
40

G
gongweibao 已提交
41
        self.inputs = {
K
Kexin Zhao 已提交
42
            'X': OpTest.np_dtype_to_fluid_dtype(self.x),
43
            'Y': OpTest.np_dtype_to_fluid_dtype(self.y),
G
gongweibao 已提交
44
        }
45
        self.attrs = {'axis': self.axis, 'use_mkldnn': self.use_mkldnn}
K
Kexin Zhao 已提交
46
        self.outputs = {'Out': self.out}
G
gongweibao 已提交
47

H
hong 已提交
48
    def check_eager(self):
49
        return not self.use_mkldnn and self.axis == -1
H
hong 已提交
50

G
gongweibao 已提交
51
    def test_check_output(self):
52
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
53
        self.check_output(
54
            check_dygraph=(not self.use_mkldnn),
55 56
            check_eager=self.check_eager(),
        )
G
gongweibao 已提交
57 58

    def test_check_grad_normal(self):
59
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
K
Kexin Zhao 已提交
60 61
        if self.dtype == np.float16:
            return
62 63 64
        self.check_grad(
            ['X', 'Y'],
            'Out',
65
            check_dygraph=(not self.use_mkldnn),
66 67
            check_eager=self.check_eager(),
        )
G
gongweibao 已提交
68 69

    def test_check_grad_ingore_x(self):
70
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
K
Kexin Zhao 已提交
71 72
        if self.dtype == np.float16:
            return
73 74 75 76
        self.check_grad(
            ['Y'],
            'Out',
            no_grad_set=set("X"),
77
            check_dygraph=(not self.use_mkldnn),
78 79
            check_eager=self.check_eager(),
        )
G
gongweibao 已提交
80 81

    def test_check_grad_ingore_y(self):
82
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
K
Kexin Zhao 已提交
83 84
        if self.dtype == np.float16:
            return
85 86 87 88
        self.check_grad(
            ['X'],
            'Out',
            no_grad_set=set('Y'),
89
            check_dygraph=(not self.use_mkldnn),
90 91
            check_eager=self.check_eager(),
        )
G
gongweibao 已提交
92

K
Kexin Zhao 已提交
93 94 95 96 97 98
    def init_input_output(self):
        self.x = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.y = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.out = np.add(self.x, self.y)

    def init_dtype(self):
99
        self.dtype = np.float64
K
Kexin Zhao 已提交
100 101

    def init_axis(self):
102
        self.axis = -1
K
Kexin Zhao 已提交
103 104


105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
class TestElementwiseAddOp_ZeroDim1(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.uniform(0.1, 1, []).astype(self.dtype)
        self.y = np.random.uniform(0.1, 1, []).astype(self.dtype)
        self.out = np.add(self.x, self.y)


class TestElementwiseAddOp_ZeroDim2(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.uniform(0.1, 1, []).astype(self.dtype)
        self.y = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.out = np.add(self.x, self.y)


class TestElementwiseAddOp_ZeroDim3(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.y = np.random.uniform(0.1, 1, []).astype(self.dtype)
        self.out = np.add(self.x, self.y)


126 127 128
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
K
Kexin Zhao 已提交
129
class TestFP16ElementwiseAddOp(TestElementwiseAddOp):
K
Kexin Zhao 已提交
130
    def init_dtype(self):
K
Kexin Zhao 已提交
131 132 133
        self.dtype = np.float16

    def test_check_output(self):
134
        # TODO(wangzhongpu): support mkldnn op in dygraph mode
K
Kexin Zhao 已提交
135 136 137
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
            if core.is_float16_supported(place):
138
                self.check_output_with_place(
139
                    place, atol=1e-3, check_dygraph=(not self.use_mkldnn)
140
                )
K
Kexin Zhao 已提交
141

G
gongweibao 已提交
142

143
@unittest.skipIf(
144 145
    not core.is_compiled_with_cuda()
    or core.cudnn_version() < 8100
146
    or paddle.device.cuda.get_device_capability()[0] < 8,
147
    "only support compiled with CUDA and cudnn version need larger than 8.1.0 and device's compute capability is at least 8.0",
148
)
149 150 151 152 153 154 155 156 157 158 159 160
class TestBF16ElementwiseAddOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_add"
        self.dtype = np.uint16

        self.x = np.random.uniform(0.1, 1, [13, 17]).astype(np.float32)
        self.y = np.random.uniform(0.1, 1, [13, 17]).astype(np.float32)
        self.out = np.add(self.x, self.y)

        self.axis = -1

        self.inputs = {
161 162 163 164 165 166
            'X': OpTest.np_dtype_to_fluid_dtype(
                convert_float_to_uint16(self.x)
            ),
            'Y': OpTest.np_dtype_to_fluid_dtype(
                convert_float_to_uint16(self.y)
            ),
167 168 169 170 171 172
        }
        self.attrs = {'axis': self.axis, 'use_mkldnn': False}
        self.outputs = {'Out': convert_float_to_uint16(self.out)}

    def test_check_output(self):
        place = core.CUDAPlace(0)
H
hong 已提交
173
        self.check_output_with_place(place, check_eager=False)
174 175 176

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
H
hong 已提交
177
        self.check_grad_with_place(place, ['X', 'Y'], 'Out', check_eager=False)
178 179 180

    def test_check_grad_ingore_x(self):
        place = core.CUDAPlace(0)
181 182 183
        self.check_grad_with_place(
            place, ['Y'], 'Out', no_grad_set=set("X"), check_eager=False
        )
184 185 186

    def test_check_grad_ingore_y(self):
        place = core.CUDAPlace(0)
187 188 189
        self.check_grad_with_place(
            place, ['X'], 'Out', no_grad_set=set('Y'), check_eager=False
        )
190 191


192
@skip_check_grad_ci(
193 194
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
K
Kexin Zhao 已提交
195
class TestElementwiseAddOp_scalar(TestElementwiseAddOp):
K
Kexin Zhao 已提交
196 197 198 199 200 201
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y


202
@skip_check_grad_ci(
203 204
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
K
Kexin Zhao 已提交
205 206 207 208 209
class TestFP16ElementwiseAddOp_scalar(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y
210 211


212
@skip_check_grad_ci(
213 214
    reason="[skip shape check] Use y_shape(1,1) to test broadcast."
)
K
Kexin Zhao 已提交
215
class TestElementwiseAddOp_scalar2(TestElementwiseAddOp):
K
Kexin Zhao 已提交
216 217 218 219 220 221
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1, 1).astype(self.dtype)
        self.out = self.x + self.y


222
@skip_check_grad_ci(
223 224
    reason="[skip shape check] Use y_shape(1,1) to test broadcast."
)
K
Kexin Zhao 已提交
225 226 227 228 229
class TestFP16ElementwiseAddOp_scalar2(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1, 1).astype(self.dtype)
        self.out = self.x + self.y
230 231


K
Kexin Zhao 已提交
232
class TestElementwiseAddOp_Vector(TestElementwiseAddOp):
K
Kexin Zhao 已提交
233
    def init_input_output(self):
234 235
        self.x = np.random.random((100,)).astype(self.dtype)
        self.y = np.random.random((100,)).astype(self.dtype)
K
Kexin Zhao 已提交
236 237 238 239 240
        self.out = np.add(self.x, self.y)


class TestFP16ElementwiseAddOp_Vector(TestFP16ElementwiseAddOp):
    def init_input_output(self):
241 242
        self.x = np.random.random((100,)).astype(self.dtype)
        self.y = np.random.random((100,)).astype(self.dtype)
K
Kexin Zhao 已提交
243
        self.out = np.add(self.x, self.y)
G
gongweibao 已提交
244 245


K
Kexin Zhao 已提交
246
class TestElementwiseAddOp_broadcast_0(TestElementwiseAddOp):
K
Kexin Zhao 已提交
247
    def init_input_output(self):
248 249 250
        self.x = np.random.rand(100, 2, 3).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(100, 1, 1)
G
gongweibao 已提交
251

K
Kexin Zhao 已提交
252 253 254 255 256 257
    def init_axis(self):
        self.axis = 0


class TestFP16ElementwiseAddOp_broadcast_0(TestFP16ElementwiseAddOp):
    def init_input_output(self):
258 259 260
        self.x = np.random.rand(100, 2, 3).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(100, 1, 1)
K
Kexin Zhao 已提交
261 262 263

    def init_axis(self):
        self.axis = 0
G
gongweibao 已提交
264 265


K
Kexin Zhao 已提交
266
class TestElementwiseAddOp_broadcast_1(TestElementwiseAddOp):
K
Kexin Zhao 已提交
267
    def init_input_output(self):
268 269 270
        self.x = np.random.rand(2, 100, 3).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 100, 1)
G
gongweibao 已提交
271

K
Kexin Zhao 已提交
272 273 274 275 276 277
    def init_axis(self):
        self.axis = 1


class TestFP16ElementwiseAddOp_broadcast_1(TestFP16ElementwiseAddOp):
    def init_input_output(self):
278 279 280
        self.x = np.random.rand(2, 100, 3).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 100, 1)
K
Kexin Zhao 已提交
281 282 283

    def init_axis(self):
        self.axis = 1
G
gongweibao 已提交
284 285


K
Kexin Zhao 已提交
286
class TestElementwiseAddOp_broadcast_2(TestElementwiseAddOp):
K
Kexin Zhao 已提交
287
    def init_input_output(self):
288 289 290
        self.x = np.random.rand(2, 3, 100).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1, 100)
G
gongweibao 已提交
291

K
Kexin Zhao 已提交
292 293 294

class TestFP16ElementwiseAddOp_broadcast_2(TestFP16ElementwiseAddOp):
    def init_input_output(self):
295 296 297
        self.x = np.random.rand(2, 3, 100).astype(self.dtype)
        self.y = np.random.rand(100).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1, 100)
G
gongweibao 已提交
298 299


K
Kexin Zhao 已提交
300
class TestElementwiseAddOp_broadcast_3(TestElementwiseAddOp):
K
Kexin Zhao 已提交
301
    def init_input_output(self):
302
        self.x = np.random.rand(2, 10, 12, 1).astype(self.dtype)
303 304
        self.y = np.random.rand(10, 12).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 10, 12, 1)
G
gongweibao 已提交
305

K
Kexin Zhao 已提交
306 307 308 309 310 311
    def init_axis(self):
        self.axis = 1


class TestFP16ElementwiseAddOp_broadcast_3(TestFP16ElementwiseAddOp):
    def init_input_output(self):
312 313 314
        self.x = np.random.rand(2, 10, 12, 3).astype(self.dtype)
        self.y = np.random.rand(10, 12).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 10, 12, 1)
K
Kexin Zhao 已提交
315 316 317

    def init_axis(self):
        self.axis = 1
G
gongweibao 已提交
318 319


K
Kexin Zhao 已提交
320
class TestElementwiseAddOp_broadcast_4(TestElementwiseAddOp):
K
Kexin Zhao 已提交
321
    def init_input_output(self):
322
        self.x = np.random.rand(100, 2, 1, 2).astype(self.dtype)
323 324
        self.y = np.random.rand(100, 1).astype(self.dtype)
        self.out = self.x + self.y.reshape(100, 1, 1, 1)
K
Kexin Zhao 已提交
325 326 327

    def init_axis(self):
        self.axis = 0
328

K
Kexin Zhao 已提交
329 330 331

class TestFP16ElementwiseAddOp_broadcast_4(TestFP16ElementwiseAddOp):
    def init_input_output(self):
332
        self.x = np.random.rand(100, 2, 1, 2).astype(self.dtype)
333 334
        self.y = np.random.rand(100, 1).astype(self.dtype)
        self.out = self.x + self.y.reshape(100, 1, 1, 1)
K
Kexin Zhao 已提交
335 336 337

    def init_axis(self):
        self.axis = 0
338 339


340 341
class TestElementwiseAddOp_broadcast_5(TestElementwiseAddOp):
    def init_input_output(self):
342 343
        self.x = np.random.rand(10, 3, 12).astype(self.dtype)
        self.y = np.random.rand(10, 1, 12).astype(self.dtype)
344 345 346 347 348
        self.out = self.x + self.y


class TestFP16ElementwiseAddOp_broadcast_5(TestFP16ElementwiseAddOp):
    def init_input_output(self):
349 350
        self.x = np.random.rand(10, 3, 12).astype(self.dtype)
        self.y = np.random.rand(10, 1, 12).astype(self.dtype)
351 352 353 354 355
        self.out = self.x + self.y


class TestElementwiseAddOp_broadcast_6(TestElementwiseAddOp):
    def init_input_output(self):
356 357
        self.x = np.random.rand(2, 12, 3, 5).astype(self.dtype)
        self.y = np.random.rand(2, 12, 1, 5).astype(self.dtype)
358 359 360 361 362 363 364
        self.out = self.x + self.y


class TestElementwiseAddOp_broadcast_7(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(1, 1, 20, 5).astype(self.dtype)
        self.y = np.random.rand(20, 5, 1, 1).astype(self.dtype)
365 366 367 368 369
        self.out = self.x + self.y


class TestFP16ElementwiseAddOp_broadcast_6(TestFP16ElementwiseAddOp):
    def init_input_output(self):
370 371
        self.x = np.random.rand(2, 12, 3, 5).astype(self.dtype)
        self.y = np.random.rand(2, 12, 1, 5).astype(self.dtype)
372 373 374
        self.out = self.x + self.y


K
Kexin Zhao 已提交
375
class TestElementwiseAddOp_rowwise_add_0(TestElementwiseAddOp):
K
Kexin Zhao 已提交
376
    def init_input_output(self):
377 378 379
        self.x = np.random.rand(2, 10, 12).astype(self.dtype)
        self.y = np.random.rand(10, 12).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 10, 12)
Q
qijun 已提交
380

K
Kexin Zhao 已提交
381 382 383 384 385 386
    def init_axis(self):
        self.axis = 1


class TestFP16ElementwiseAddOp_rowwise_add_0(TestFP16ElementwiseAddOp):
    def init_input_output(self):
387 388 389
        self.x = np.random.rand(2, 10, 12).astype(self.dtype)
        self.y = np.random.rand(10, 12).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 10, 12)
K
Kexin Zhao 已提交
390 391 392

    def init_axis(self):
        self.axis = 1
Q
qijun 已提交
393 394


395
@skip_check_grad_ci(
396 397
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
K
Kexin Zhao 已提交
398
class TestElementwiseAddOp_rowwise_add_1(TestElementwiseAddOp):
K
Kexin Zhao 已提交
399
    def init_input_output(self):
400
        self.x = np.random.rand(100, 1).astype(self.dtype)
K
Kexin Zhao 已提交
401 402
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1)
Q
qijun 已提交
403

K
Kexin Zhao 已提交
404 405 406 407
    def init_axis(self):
        self.axis = 1


408
@skip_check_grad_ci(
409 410
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
K
Kexin Zhao 已提交
411 412
class TestFP16ElementwiseAddOp_rowwise_add_1(TestFP16ElementwiseAddOp):
    def init_input_output(self):
413
        self.x = np.random.rand(100, 1).astype(self.dtype)
K
Kexin Zhao 已提交
414 415 416 417 418
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1)

    def init_axis(self):
        self.axis = 1
Q
qijun 已提交
419 420


421 422
class TestElementwiseAddOp_channelwise_add(TestElementwiseAddOp):
    def init_input_output(self):
423 424
        self.x = np.random.rand(100, 2, 3).astype(self.dtype)
        self.y = np.random.rand(100, 1, 1).astype(self.dtype)
425 426 427 428 429 430 431 432
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1


class TestFP16ElementwiseAddOp_channelwise_add(TestFP16ElementwiseAddOp):
    def init_input_output(self):
433 434
        self.x = np.random.rand(100, 2, 3).astype(self.dtype)
        self.y = np.random.rand(100, 1, 1).astype(self.dtype)
435 436 437 438 439 440
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1


441 442
class TestElementwiseAddOp_commonuse_add1(TestElementwiseAddOp):
    def init_input_output(self):
443 444
        self.x = np.random.rand(2, 3, 100).astype(self.dtype)
        self.y = np.random.rand(1, 1, 100).astype(self.dtype)
445 446 447 448 449 450
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1


451 452
class TestElementwiseFP16AddOp_commonuse_add1(TestFP16ElementwiseAddOp):
    def init_input_output(self):
453
        self.x = np.random.rand(2, 3, 100).astype(self.dtype)
454 455 456 457 458 459 460
        self.y = np.random.rand(1, 1, 100).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1


461 462
class TestElementwiseAddOp_commonuse_add2(TestElementwiseAddOp):
    def init_input_output(self):
463 464
        self.x = np.random.rand(10, 3, 1, 4).astype(self.dtype)
        self.y = np.random.rand(10, 1, 12, 1).astype(self.dtype)
465 466 467 468 469 470 471 472
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1


class TestElementwiseAddOp_xsize_lessthan_ysize_add(TestElementwiseAddOp):
    def init_input_output(self):
473
        self.x = np.random.rand(10, 12).astype(self.dtype)
474
        self.y = np.random.rand(2, 2, 10, 12).astype(self.dtype)
475 476 477 478 479 480
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = 2


481 482 483
class TestElementwiseAddOp_same_shape_ysize_large(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(10, 1, 12).astype(self.dtype)
484
        self.y = np.random.rand(10, 2, 12).astype(self.dtype)
485 486 487 488 489 490
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = 0


491 492 493 494
class TestAddApi(unittest.TestCase):
    def _executed_api(self, x, y, name=None):
        return paddle.add(x, y, name)

495 496 497 498 499
    def test_name(self):
        with fluid.program_guard(fluid.Program()):
            x = fluid.data(name="x", shape=[2, 3], dtype="float32")
            y = fluid.data(name='y', shape=[2, 3], dtype='float32')

500
            y_1 = self._executed_api(x, y, name='add_res')
501 502
            self.assertEqual(('add_res' in y_1.name), True)

Y
Yang Zhang 已提交
503
    def test_declarative(self):
504 505 506 507 508
        with fluid.program_guard(fluid.Program()):

            def gen_data():
                return {
                    "x": np.array([2, 3, 4]).astype('float32'),
509
                    "y": np.array([1, 5, 2]).astype('float32'),
510 511 512 513
                }

            x = fluid.data(name="x", shape=[3], dtype='float32')
            y = fluid.data(name="y", shape=[3], dtype='float32')
514
            z = self._executed_api(x, y)
515 516 517 518

            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            z_value = exe.run(feed=gen_data(), fetch_list=[z.name])
519
            z_expected = np.array([3.0, 8.0, 6.0])
520 521 522 523 524 525 526 527
            self.assertEqual((z_value == z_expected).all(), True)

    def test_dygraph(self):
        with fluid.dygraph.guard():
            np_x = np.array([2, 3, 4]).astype('float64')
            np_y = np.array([1, 5, 2]).astype('float64')
            x = fluid.dygraph.to_variable(np_x)
            y = fluid.dygraph.to_variable(np_y)
528
            z = self._executed_api(x, y)
529
            np_z = z.numpy()
530
            z_expected = np.array([3.0, 8.0, 6.0])
531 532 533
            self.assertEqual((np_z == z_expected).all(), True)


534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
class TestAddInplaceApi(TestAddApi):
    def _executed_api(self, x, y, name=None):
        return x.add_(y, name)


class TestAddInplaceBroadcastSuccess(unittest.TestCase):
    def init_data(self):
        self.x_numpy = np.random.rand(2, 3, 4).astype('float')
        self.y_numpy = np.random.rand(3, 4).astype('float')

    def test_broadcast_success(self):
        paddle.disable_static()
        self.init_data()
        x = paddle.to_tensor(self.x_numpy)
        y = paddle.to_tensor(self.y_numpy)
        inplace_result = x.add_(y)
        numpy_result = self.x_numpy + self.y_numpy
        self.assertEqual((inplace_result.numpy() == numpy_result).all(), True)
        paddle.enable_static()


class TestAddInplaceBroadcastSuccess2(TestAddInplaceBroadcastSuccess):
    def init_data(self):
        self.x_numpy = np.random.rand(1, 2, 3, 1).astype('float')
        self.y_numpy = np.random.rand(3, 1).astype('float')


class TestAddInplaceBroadcastSuccess3(TestAddInplaceBroadcastSuccess):
    def init_data(self):
        self.x_numpy = np.random.rand(2, 3, 1, 5).astype('float')
        self.y_numpy = np.random.rand(1, 3, 1, 5).astype('float')


class TestAddInplaceBroadcastError(unittest.TestCase):
    def init_data(self):
        self.x_numpy = np.random.rand(3, 4).astype('float')
        self.y_numpy = np.random.rand(2, 3, 4).astype('float')

    def test_broadcast_errors(self):
        paddle.disable_static()
        self.init_data()
        x = paddle.to_tensor(self.x_numpy)
        y = paddle.to_tensor(self.y_numpy)

        def broadcast_shape_error():
            x.add_(y)

        self.assertRaises(ValueError, broadcast_shape_error)
        paddle.enable_static()


class TestAddInplaceBroadcastError2(TestAddInplaceBroadcastError):
    def init_data(self):
        self.x_numpy = np.random.rand(2, 1, 4).astype('float')
        self.y_numpy = np.random.rand(2, 3, 4).astype('float')


class TestAddInplaceBroadcastError3(TestAddInplaceBroadcastError):
    def init_data(self):
        self.x_numpy = np.random.rand(5, 2, 1, 4).astype('float')
        self.y_numpy = np.random.rand(2, 3, 4).astype('float')


597 598 599
class TestComplexElementwiseAddOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_add"
600 601
        self.dtype = np.float64
        self.shape = (2, 3, 4, 5)
602 603 604 605 606
        self.init_input_output()
        self.init_grad_input_output()

        self.inputs = {
            'X': OpTest.np_dtype_to_fluid_dtype(self.x),
607
            'Y': OpTest.np_dtype_to_fluid_dtype(self.y),
608 609 610 611 612 613 614 615
        }
        self.attrs = {'axis': -1, 'use_mkldnn': False}
        self.outputs = {'Out': self.out}

    def init_base_dtype(self):
        self.dtype = np.float64

    def init_input_output(self):
616
        self.x = np.random.random(self.shape).astype(
617 618
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
619
        self.y = np.random.random(self.shape).astype(
620 621
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
622 623 624
        self.out = self.x + self.y

    def init_grad_input_output(self):
625 626 627
        self.grad_out = np.ones(self.shape, self.dtype) + 1j * np.ones(
            self.shape, self.dtype
        )
628 629 630 631
        self.grad_x = self.grad_out
        self.grad_y = self.grad_out

    def test_check_output(self):
H
hong 已提交
632
        self.check_output(check_eager=False)
633 634

    def test_check_grad_normal(self):
635 636 637 638 639 640
        self.check_grad(
            ['X', 'Y'],
            'Out',
            user_defined_grads=[self.grad_x, self.grad_y],
            user_defined_grad_outputs=[self.grad_out],
        )
641 642

    def test_check_grad_ingore_x(self):
643 644 645 646 647 648 649
        self.check_grad(
            ['Y'],
            'Out',
            no_grad_set=set("X"),
            user_defined_grads=[self.grad_y],
            user_defined_grad_outputs=[self.grad_out],
        )
650 651

    def test_check_grad_ingore_y(self):
652 653 654 655 656 657 658
        self.check_grad(
            ['X'],
            'Out',
            no_grad_set=set('Y'),
            user_defined_grads=[self.grad_x],
            user_defined_grad_outputs=[self.grad_out],
        )
659 660


661 662 663 664
class TestRealComplexElementwiseAddOp(TestComplexElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.random(self.shape).astype(self.dtype)
        self.y = np.random.random(self.shape).astype(
665 666
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
667 668 669
        self.out = self.x + self.y

    def init_grad_input_output(self):
670 671 672
        self.grad_out = np.ones(self.shape, self.dtype) + 1j * np.ones(
            self.shape, self.dtype
        )
673 674 675 676
        self.grad_x = np.real(self.grad_out)
        self.grad_y = self.grad_out


677 678 679 680 681 682 683 684 685
class TestBoolAddFloatElementwiseAddop(unittest.TestCase):
    def test_static_add(self):
        paddle.enable_static()
        a = 1.5
        b = paddle.full([4, 5, 6], True, dtype='bool')
        c = a + b
        self.assertTrue(c.dtype == core.VarDesc.VarType.FP32)
        paddle.enable_static()

686
    def test_dygraph_add(self):
687 688
        paddle.disable_static()
        a = 1.5
689 690
        b = paddle.full([2], True, dtype='bool')
        # special case: scalar + tensor(bool)
691 692 693
        c = a + b
        self.assertTrue(c.dtype == core.VarDesc.VarType.FP32)

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
        np_a = np.random.random((2, 3, 4)).astype(np.float64)
        np_b = np.random.random((2, 3, 4)).astype(np.float64)

        tensor_a = paddle.to_tensor(np_a, dtype="float32")
        tensor_b = paddle.to_tensor(np_b, dtype="float32")

        # normal case: tensor + tensor
        expect_out = np_a + np_b
        actual_out = tensor_a + tensor_b
        np.testing.assert_allclose(actual_out, expect_out)

        # normal case: tensor + scalar
        expect_out = np_a + 1
        actual_out = tensor_a + 1
        np.testing.assert_allclose(actual_out, expect_out)

        # normal case: scalar + tenor
        expect_out = 1 + np_a
        actual_out = 1 + tensor_a
        np.testing.assert_allclose(actual_out, expect_out)

        paddle.enable_static()

717

718
class TestElementwiseAddop1(unittest.TestCase):
719
    def test_dygraph_add(self):
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
        paddle.disable_static()

        np_a = np.random.random((2, 3, 4)).astype(np.float32)
        np_b = np.random.random((2, 3, 4)).astype(np.float32)

        tensor_a = paddle.to_tensor(np_a, dtype="float32")
        tensor_b = paddle.to_tensor(np_b, dtype="float32")

        # normal case: nparray + tenor
        expect_out = np_a + np_b
        actual_out = np_a + tensor_b
        np.testing.assert_allclose(actual_out, expect_out)

        # normal case: tensor + nparray
        actual_out = tensor_a + np_b
        np.testing.assert_allclose(actual_out, expect_out)

        paddle.enable_static()


G
gongweibao 已提交
740
if __name__ == '__main__':
741
    paddle.enable_static()
G
gongweibao 已提交
742
    unittest.main()