test_elementwise_sub_op.py 34.7 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

15
import os
G
gongweibao 已提交
16
import unittest
17
import warnings
18

G
gongweibao 已提交
19
import numpy as np
20
from eager_op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
21

C
chentianyu03 已提交
22
import paddle
23
from paddle import fluid
24
from paddle.fluid import core
25
from paddle.fluid.layer_helper import LayerHelper
G
gongweibao 已提交
26 27 28 29 30


class TestElementwiseOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_sub"
31
        self.python_api = paddle.subtract
32
        self.public_python_api = paddle.subtract
33
        self.prim_op_type = "prim"
34
        self.init_dtype()
G
gongweibao 已提交
35
        self.inputs = {
36 37
            'X': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(self.dtype),
            'Y': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(self.dtype),
G
gongweibao 已提交
38 39
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
40
        self.if_check_prim()
41
        self.if_enable_cinn()
G
gongweibao 已提交
42

43 44 45
    def init_dtype(self):
        self.dtype = np.float64

G
gongweibao 已提交
46 47 48 49
    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
50
        self.check_grad(['X', 'Y'], 'Out', check_prim=self.check_prim)
G
gongweibao 已提交
51 52

    def test_check_grad_ingore_x(self):
53
        self.check_grad(
54 55 56 57 58
            ['Y'],
            'Out',
            max_relative_error=0.005,
            no_grad_set=set("X"),
            check_prim=self.check_prim,
59
        )
G
gongweibao 已提交
60 61

    def test_check_grad_ingore_y(self):
62
        self.check_grad(
63 64 65 66 67
            ['X'],
            'Out',
            max_relative_error=0.005,
            no_grad_set=set('Y'),
            check_prim=self.check_prim,
68
        )
G
gongweibao 已提交
69

70 71 72
    def if_check_prim(self):
        self.check_prim = True

73
    def if_enable_cinn(self):
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        self.enable_cinn = False


class TestElementwiseFP16OP(TestElementwiseOp):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.inputs = {
            'X': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(np.float32),
            'Y': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
        self.if_enable_cinn()

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['X', 'Y'], 'Out', max_relative_error=0.1
        )

    def test_check_grad_ingore_x(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['Y'], 'Out', no_grad_set=set("X"), max_relative_error=0.1
        )

    def test_check_grad_ingore_y(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['X'], 'Out', no_grad_set=set('Y'), max_relative_error=0.1
        )
123

G
gongweibao 已提交
124

125 126 127
class TestElementwiseSubOp_ZeroDim1(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
128
        self.python_api = paddle.subtract
129
        self.public_python_api = paddle.subtract
130
        self.prim_op_type = "prim"
131
        self.init_dtype()
132
        self.inputs = {
133 134
            'X': np.random.uniform(0.1, 1, []).astype(self.dtype),
            'Y': np.random.uniform(0.1, 1, []).astype(self.dtype),
135 136
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
137
        self.if_check_prim()
138
        self.if_enable_cinn()
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
class TestElementwiseSubFP16OP_ZeroDim1(TestElementwiseSubOp_ZeroDim1):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseSubBF16OP_ZeroDim1(TestElementwiseBF16OP):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.prim_op_type = "prim"
        self.inputs = {
            'X': np.random.uniform(0.1, 1, []).astype(np.float32),
            'Y': np.random.uniform(0.1, 1, []).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
        self.if_enable_cinn()
170 171 172 173 174


class TestElementwiseSubOp_ZeroDim2(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
175
        self.python_api = paddle.subtract
176
        self.public_python_api = paddle.subtract
177
        self.prim_op_type = "prim"
178
        self.init_dtype()
179
        self.inputs = {
180 181
            'X': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(self.dtype),
            'Y': np.random.uniform(0.1, 1, []).astype(self.dtype),
182 183
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
184
        self.if_check_prim()
185
        self.if_enable_cinn()
186 187


188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
class TestElementwiseSubFP16OP_ZeroDim2(TestElementwiseSubOp_ZeroDim2):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseSubBF16OP_ZeroDim2(TestElementwiseBF16OP):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.prim_op_type = "prim"
        self.inputs = {
            'X': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(np.float32),
            'Y': np.random.uniform(0.1, 1, []).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
        self.if_enable_cinn()
217 218 219 220 221


class TestElementwiseSubOp_ZeroDim3(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
222
        self.python_api = paddle.subtract
223
        self.public_python_api = paddle.subtract
224
        self.prim_op_type = "prim"
225
        self.init_dtype()
226
        self.inputs = {
227 228
            'X': np.random.uniform(0.1, 1, []).astype(self.dtype),
            'Y': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(self.dtype),
229 230
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
231
        self.if_check_prim()
232
        self.if_enable_cinn()
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
class TestElementwiseSubFP16OP_ZeroDim3(TestElementwiseSubOp_ZeroDim3):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_ZeroDim3(TestElementwiseBF16OP):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.prim_op_type = "prim"
        self.inputs = {
            'X': np.random.uniform(0.1, 1, []).astype(np.float32),
            'Y': np.random.uniform(0.1, 1, [2, 3, 4, 5]).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
        self.if_enable_cinn()
264 265


266 267 268 269 270
@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
271 272 273
class TestBF16ElementwiseOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_sub"
274
        self.python_api = paddle.subtract
275
        self.public_python_api = paddle.subtract
276
        self.prim_op_type = "prim"
277 278 279 280 281 282 283
        self.dtype = np.uint16
        x = np.random.uniform(0.1, 1, [13, 17]).astype(np.float32)
        y = np.random.uniform(0.1, 1, [13, 17]).astype(np.float32)
        out = x - y

        self.inputs = {
            'X': convert_float_to_uint16(x),
284
            'Y': convert_float_to_uint16(y),
285 286
        }
        self.outputs = {'Out': convert_float_to_uint16(out)}
287
        self.if_check_prim()
288
        self.if_enable_cinn()
289

290 291 292 293 294 295
    def if_check_prim(self):
        self.check_prim = True

    def if_enable_cinn(self):
        self.enable_cinn = False

296 297 298 299
    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
300
        self.check_grad(['X', 'Y'], 'Out', check_prim=self.check_prim)
301 302

    def test_check_grad_ingore_x(self):
303 304 305
        self.check_grad(
            ['Y'], 'Out', no_grad_set=set("X"), check_prim=self.check_prim
        )
306 307


308
@skip_check_grad_ci(
309 310
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
311 312 313
class TestElementwiseSubOp_scalar(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
314
        self.python_api = paddle.subtract
315
        self.public_python_api = paddle.subtract
316
        self.prim_op_type = "prim"
317
        self.init_dtype()
318
        self.inputs = {
319 320
            'X': np.random.rand(10, 3, 4).astype(self.dtype),
            'Y': np.random.rand(1).astype(self.dtype),
321 322
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
323
        self.if_check_prim()
324 325


G
gongweibao 已提交
326 327 328
class TestElementwiseSubOp_Vector(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
329
        self.python_api = paddle.subtract
330
        self.public_python_api = paddle.subtract
331
        self.prim_op_type = "prim"
332
        self.init_dtype()
G
gongweibao 已提交
333
        self.inputs = {
334 335
            'X': np.random.random((100,)).astype(self.dtype),
            'Y': np.random.random((100,)).astype(self.dtype),
G
gongweibao 已提交
336 337
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
338
        self.if_check_prim()
G
gongweibao 已提交
339 340


341
class TestElementwiseSubOp_broadcast_0(TestElementwiseOp):
G
gongweibao 已提交
342 343
    def setUp(self):
        self.op_type = "elementwise_sub"
344
        self.python_api = paddle.subtract
345
        self.init_dtype()
G
gongweibao 已提交
346
        self.inputs = {
347 348
            'X': np.random.rand(100, 3, 2).astype(self.dtype),
            'Y': np.random.rand(100).astype(self.dtype),
G
gongweibao 已提交
349 350 351 352
        }

        self.attrs = {'axis': 0}
        self.outputs = {
353
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(100, 1, 1)
G
gongweibao 已提交
354 355
        }

356 357 358 359 360
    def test_check_output(self):
        self.check_output(check_dygraph=False)

    def test_check_grad_normal(self):
        self.check_grad(['X', 'Y'], 'Out', check_dygraph=False)
G
gongweibao 已提交
361

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    def test_check_grad_ingore_x(self):
        self.check_grad(
            ['Y'],
            'Out',
            max_relative_error=0.005,
            no_grad_set=set("X"),
            check_dygraph=False,
        )

    def test_check_grad_ingore_y(self):
        self.check_grad(
            ['X'],
            'Out',
            max_relative_error=0.005,
            no_grad_set=set('Y'),
            check_dygraph=False,
        )


381 382 383 384 385 386 387 388 389 390 391
class TestElementwiseSubFP16OP_broadcast_0(TestElementwiseSubOp_broadcast_0):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_broadcast_0(TestElementwiseBF16OP):
G
gongweibao 已提交
392 393
    def setUp(self):
        self.op_type = "elementwise_sub"
394
        self.dtype = np.uint16
395
        self.python_api = paddle.subtract
G
gongweibao 已提交
396
        self.inputs = {
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
            'X': np.random.rand(100, 3, 2).astype(np.float32),
            'Y': np.random.rand(100).astype(np.float32),
        }
        self.outputs = {
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(100, 1, 1)
        }
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.attrs = {'axis': 0}

    def test_check_output(self):
        place = core.CUDAPlace(0)
        self.check_output_with_place(place, check_dygraph=False)

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['X', 'Y'], 'Out', check_dygraph=False
        )

    def test_check_grad_ingore_x(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['Y'], 'Out', no_grad_set=set("X"), check_dygraph=False
        )

    def test_check_grad_ingore_y(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['X'], 'Out', no_grad_set=set('Y'), check_dygraph=False
        )


class TestElementwiseSubOp_broadcast_1(TestElementwiseSubOp_broadcast_0):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.python_api = paddle.subtract
        self.init_dtype()
        self.inputs = {
            'X': np.random.rand(2, 100, 3).astype(self.dtype),
            'Y': np.random.rand(100).astype(self.dtype),
G
gongweibao 已提交
441 442 443 444
        }

        self.attrs = {'axis': 1}
        self.outputs = {
445
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(1, 100, 1)
G
gongweibao 已提交
446 447 448
        }


449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
class TestElementwiseSubFP16OP_broadcast_1(TestElementwiseSubOp_broadcast_1):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_broadcast_1(TestElementwiseBF16OP_broadcast_0):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.inputs = {
            'X': np.random.rand(2, 100, 3).astype(np.float32),
            'Y': np.random.rand(100).astype(np.float32),
        }
        self.outputs = {
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(1, 100, 1)
        }
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.attrs = {'axis': 1}


G
gongweibao 已提交
479 480 481
class TestElementwiseSubOp_broadcast_2(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
482
        self.python_api = paddle.subtract
483
        self.public_python_api = paddle.subtract
484
        self.prim_op_type = "prim"
485
        self.init_dtype()
G
gongweibao 已提交
486
        self.inputs = {
487 488
            'X': np.random.rand(2, 3, 100).astype(self.dtype),
            'Y': np.random.rand(100).astype(self.dtype),
G
gongweibao 已提交
489 490 491
        }

        self.outputs = {
492
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(1, 1, 100)
G
gongweibao 已提交
493
        }
494 495
        self.if_check_prim()

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549

class TestElementwiseSubFP16OP_broadcast_2(TestElementwiseSubOp_broadcast_2):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_broadcast_2(TestElementwiseBF16OP_broadcast_0):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.inputs = {
            'X': np.random.rand(2, 3, 100).astype(np.float32),
            'Y': np.random.rand(100).astype(np.float32),
        }
        self.outputs = {
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(1, 1, 100)
        }
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_broadcast_3(TestElementwiseBF16OP_broadcast_0):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.inputs = {
            'X': np.random.rand(2, 10, 12, 3).astype(np.float32),
            'Y': np.random.rand(10, 12).astype(np.float32),
        }
        self.outputs = {
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(1, 10, 12, 1)
        }
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.attrs = {'axis': 1}
G
gongweibao 已提交
550 551


552
class TestElementwiseSubOp_broadcast_3(TestElementwiseSubOp_broadcast_0):
G
gongweibao 已提交
553 554
    def setUp(self):
        self.op_type = "elementwise_sub"
555
        self.python_api = paddle.subtract
556
        self.init_dtype()
G
gongweibao 已提交
557
        self.inputs = {
558 559
            'X': np.random.rand(2, 10, 12, 3).astype(self.dtype),
            'Y': np.random.rand(10, 12).astype(self.dtype),
G
gongweibao 已提交
560 561 562 563
        }

        self.attrs = {'axis': 1}
        self.outputs = {
564
            'Out': self.inputs['X'] - self.inputs['Y'].reshape(1, 10, 12, 1)
G
gongweibao 已提交
565 566 567
        }


568 569 570 571 572
class TestElementwiseSubFP16OP_broadcast_3(TestElementwiseSubOp_broadcast_3):
    def init_dtype(self):
        self.dtype = np.float16


573 574 575
class TestElementwiseSubOp_broadcast_4(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
576
        self.python_api = paddle.subtract
577
        self.public_python_api = paddle.subtract
578
        self.prim_op_type = "prim"
579
        self.init_dtype()
580
        self.inputs = {
581 582
            'X': np.random.rand(2, 5, 3, 12).astype(self.dtype),
            'Y': np.random.rand(2, 5, 1, 12).astype(self.dtype),
583 584
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
585 586
        self.if_check_prim()

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_broadcast_4(TestElementwiseBF16OP_broadcast_0):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.inputs = {
            'X': np.random.rand(2, 5, 3, 12).astype(np.float32),
            'Y': np.random.rand(2, 5, 1, 12).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()


class TestElementwiseSubFP16OP_broadcast_4(TestElementwiseSubOp_broadcast_4):
    def init_dtype(self):
        self.dtype = np.float16
614 615


616 617 618
class TestElementwiseSubOp_commonuse_1(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
619
        self.python_api = paddle.subtract
620
        self.public_python_api = paddle.subtract
621
        self.prim_op_type = "prim"
622
        self.init_dtype()
623
        self.inputs = {
624 625
            'X': np.random.rand(2, 3, 100).astype(self.dtype),
            'Y': np.random.rand(1, 1, 100).astype(self.dtype),
626 627
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
628 629
        self.if_check_prim()

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

class TestElementwiseSubFP16OP_commonuse_1(TestElementwiseSubOp_commonuse_1):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_commonuse_1(TestElementwiseBF16OP):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.prim_op_type = "prim"
        self.inputs = {
            'X': np.random.rand(2, 3, 100).astype(np.float32),
            'Y': np.random.rand(1, 1, 100).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
659 660 661 662 663


class TestElementwiseSubOp_commonuse_2(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
664
        self.python_api = paddle.subtract
665
        self.public_python_api = paddle.subtract
666
        self.prim_op_type = "prim"
667
        self.init_dtype()
668
        self.inputs = {
669 670
            'X': np.random.rand(10, 3, 1, 4).astype(self.dtype),
            'Y': np.random.rand(10, 1, 12, 1).astype(self.dtype),
671 672
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
673 674
        self.if_check_prim()

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

class TestElementwiseSubFP16OP_commonuse_2(TestElementwiseSubOp_commonuse_2):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_commonuse_2(TestElementwiseBF16OP):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.prim_op_type = "prim"
        self.inputs = {
            'X': np.random.rand(10, 3, 1, 4).astype(np.float32),
            'Y': np.random.rand(10, 1, 12, 1).astype(np.float32),
        }
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
704 705 706 707 708


class TestElementwiseSubOp_xsize_lessthan_ysize(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
709
        self.python_api = paddle.subtract
710
        self.public_python_api = paddle.subtract
711
        self.prim_op_type = "prim"
712
        self.init_dtype()
713
        self.inputs = {
714 715
            'X': np.random.rand(10, 12).astype(self.dtype),
            'Y': np.random.rand(2, 3, 10, 12).astype(self.dtype),
716 717 718 719
        }
        self.attrs = {'axis': 2}

        self.outputs = {
720
            'Out': self.inputs['X'].reshape(1, 1, 10, 12) - self.inputs['Y']
721
        }
722 723
        self.if_check_prim()

724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

class TestElementwiseSubFP16OP_xsize_lessthan_ysize(
    TestElementwiseSubOp_xsize_lessthan_ysize
):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestElementwiseBF16OP_xsize_lessthan_ysize(TestElementwiseBF16OP):
    def setUp(self):
        self.op_type = "elementwise_sub"
        self.dtype = np.uint16
        self.python_api = paddle.subtract
        self.public_python_api = paddle.subtract
        self.prim_op_type = "prim"
        self.inputs = {
            'X': np.random.rand(10, 12).astype(np.float32),
            'Y': np.random.rand(2, 3, 10, 12).astype(np.float32),
        }
        self.attrs = {'axis': 2}
        self.outputs = {'Out': self.inputs['X'] - self.inputs['Y']}
        self.inputs = {
            'X': convert_float_to_uint16(self.inputs['X']),
            'Y': convert_float_to_uint16(self.inputs['Y']),
        }
        self.outputs = {'Out': convert_float_to_uint16(self.outputs['Out'])}
        self.if_check_prim()
756 757


C
chentianyu03 已提交
758 759 760
class TestComplexElementwiseSubOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_sub"
761
        self.python_api = paddle.subtract
762
        self.public_python_api = paddle.subtract
763
        self.prim_op_type = "prim"
C
chentianyu03 已提交
764 765 766 767 768 769 770
        self.dtype = np.float64
        self.shape = (2, 3, 4, 5)
        self.init_input_output()
        self.init_grad_input_output()

        self.inputs = {
            'X': OpTest.np_dtype_to_fluid_dtype(self.x),
771
            'Y': OpTest.np_dtype_to_fluid_dtype(self.y),
C
chentianyu03 已提交
772 773 774
        }
        self.attrs = {'axis': -1, 'use_mkldnn': False}
        self.outputs = {'Out': self.out}
775
        self.if_check_prim()
776
        self.if_enable_cinn()
C
chentianyu03 已提交
777 778 779 780 781 782

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

    def init_input_output(self):
        self.x = np.random.random(self.shape).astype(
783 784
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
C
chentianyu03 已提交
785
        self.y = np.random.random(self.shape).astype(
786 787
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
C
chentianyu03 已提交
788 789 790
        self.out = self.x - self.y

    def init_grad_input_output(self):
791 792 793
        self.grad_out = np.ones(self.shape, self.dtype) + 1j * np.ones(
            self.shape, self.dtype
        )
C
chentianyu03 已提交
794 795 796 797 798 799 800
        self.grad_x = self.grad_out
        self.grad_y = -self.grad_out

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
801 802 803 804 805
        self.check_grad(
            ['X', 'Y'],
            'Out',
            user_defined_grads=[self.grad_x, self.grad_y],
            user_defined_grad_outputs=[self.grad_out],
806
            check_prim=self.check_prim,
807
        )
C
chentianyu03 已提交
808 809

    def test_check_grad_ingore_x(self):
810 811 812 813 814 815
        self.check_grad(
            ['Y'],
            'Out',
            no_grad_set=set("X"),
            user_defined_grads=[self.grad_y],
            user_defined_grad_outputs=[self.grad_out],
816
            check_prim=self.check_prim,
817
        )
C
chentianyu03 已提交
818 819

    def test_check_grad_ingore_y(self):
820 821 822 823 824 825
        self.check_grad(
            ['X'],
            'Out',
            no_grad_set=set('Y'),
            user_defined_grads=[self.grad_x],
            user_defined_grad_outputs=[self.grad_out],
826
            check_prim=self.check_prim,
827
        )
C
chentianyu03 已提交
828

829
    def if_enable_cinn(self):
830 831 832 833 834
        self.enable_cinn = False

    def if_check_prim(self):
        self.check_prim = True

C
chentianyu03 已提交
835 836 837 838 839

class TestRealComplexElementwiseSubOp(TestComplexElementwiseSubOp):
    def init_input_output(self):
        self.x = np.random.random(self.shape).astype(self.dtype)
        self.y = np.random.random(self.shape).astype(
840 841
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
C
chentianyu03 已提交
842 843 844
        self.out = self.x - self.y

    def init_grad_input_output(self):
845 846 847
        self.grad_out = np.ones(self.shape, self.dtype) + 1j * np.ones(
            self.shape, self.dtype
        )
C
chentianyu03 已提交
848 849 850
        self.grad_x = np.real(self.grad_out)
        self.grad_y = -self.grad_out

851
    def if_enable_cinn(self):
852 853 854 855 856
        self.enable_cinn = False

    def if_check_prim(self):
        self.check_prim = False

C
chentianyu03 已提交
857

858 859 860 861 862 863
class TestSubtractApi(unittest.TestCase):
    def _executed_api(self, x, y, name=None):
        return paddle.subtract(x, y, name)

    def test_name(self):
        with fluid.program_guard(fluid.Program()):
864
            x = paddle.static.data(name="x", shape=[2, 3], dtype="float32")
865
            y = paddle.static.data(name='y', shape=[2, 3], dtype=np.float32)
866 867 868 869 870 871 872 873 874

            y_1 = self._executed_api(x, y, name='subtract_res')
            self.assertEqual(('subtract_res' in y_1.name), True)

    def test_declarative(self):
        with fluid.program_guard(fluid.Program()):

            def gen_data():
                return {
875 876
                    "x": np.array([2, 3, 4]).astype(np.float32),
                    "y": np.array([1, 5, 2]).astype(np.float32),
877 878
                }

879 880
            x = paddle.static.data(name="x", shape=[3], dtype=np.float32)
            y = paddle.static.data(name="y", shape=[3], dtype=np.float32)
881 882 883 884
            z = self._executed_api(x, y)
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            z_value = exe.run(feed=gen_data(), fetch_list=[z.name])
885
            z_expected = np.array([1.0, -2.0, 2.0])
886 887 888 889 890 891 892 893 894 895
            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)
            z = self._executed_api(x, y)
            np_z = z.numpy()
896
            z_expected = np.array([1.0, -2.0, 2.0])
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
            self.assertEqual((np_z == z_expected).all(), True)


class TestSubtractInplaceApi(TestSubtractApi):
    def _executed_api(self, x, y, name=None):
        return x.subtract_(y, name)


class TestSubtractInplaceBroadcastSuccess(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.subtract_(y)
        numpy_result = self.x_numpy - self.y_numpy
        self.assertEqual((inplace_result.numpy() == numpy_result).all(), True)
        paddle.enable_static()


class TestSubtractInplaceBroadcastSuccess2(TestSubtractInplaceBroadcastSuccess):
    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 TestSubtractInplaceBroadcastSuccess3(TestSubtractInplaceBroadcastSuccess):
    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 TestSubtractInplaceBroadcastError(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.subtract_(y)

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


class TestSubtractInplaceBroadcastError2(TestSubtractInplaceBroadcastError):
    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 TestSubtractInplaceBroadcastError3(TestSubtractInplaceBroadcastError):
    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')


963
class TestFloatElementwiseSubop(unittest.TestCase):
964
    def test_dygraph_sub(self):
965 966 967 968 969 970 971 972 973 974 975
        paddle.disable_static()

        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
976 977 978
        np.testing.assert_allclose(
            actual_out, expect_out, rtol=1e-07, atol=1e-07
        )
979 980 981 982

        # normal case: tensor - scalar
        expect_out = np_a - 1
        actual_out = tensor_a - 1
983 984 985
        np.testing.assert_allclose(
            actual_out, expect_out, rtol=1e-07, atol=1e-07
        )
986 987 988 989

        # normal case: scalar - tenor
        expect_out = 1 - np_a
        actual_out = 1 - tensor_a
990 991 992
        np.testing.assert_allclose(
            actual_out, expect_out, rtol=1e-07, atol=1e-07
        )
993 994 995 996

        paddle.enable_static()


997
class TestFloatElementwiseSubop1(unittest.TestCase):
998
    def test_dygraph_sub(self):
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        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, rtol=1e-07, atol=1e-07
        )

        # normal case: tenor - nparray
        actual_out = tensor_a - np_b
        np.testing.assert_allclose(
            actual_out, expect_out, rtol=1e-07, atol=1e-07
        )

        paddle.enable_static()


1023 1024 1025 1026 1027 1028 1029 1030 1031
class TestTensorSubAPIWarnings(unittest.TestCase):
    def test_warnings(self):

        with warnings.catch_warnings(record=True) as context:
            warnings.simplefilter("always")

            paddle.enable_static()
            helper = LayerHelper("elementwise_sub")
            data = paddle.static.data(
1032
                name='data', shape=[None, 3, 32, 32], dtype=np.float32
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
            )
            out = helper.create_variable_for_type_inference(dtype=data.dtype)
            os.environ['FLAGS_print_extra_attrs'] = "1"
            helper.append_op(
                type="elementwise_sub",
                inputs={'X': data, 'Y': data},
                outputs={'Out': out},
                attrs={'axis': 1, 'use_mkldnn': False},
            )
            self.assertTrue(
                "op elementwise_sub's attr axis = 1 is not the default value: -1"
                in str(context[-1].message)
            )
            os.environ['FLAGS_print_extra_attrs'] = "0"


G
gongweibao 已提交
1049
if __name__ == '__main__':
C
chentianyu03 已提交
1050
    paddle.enable_static()
G
gongweibao 已提交
1051
    unittest.main()