test_elementwise_sub_op.py 34.6 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 138 139
        self.if_check_prim()


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
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()
169 170 171 172 173


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


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
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()
215 216 217 218 219


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


232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
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()
261 262


263 264 265 266 267
@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",
)
268 269 270
class TestBF16ElementwiseOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_sub"
271
        self.python_api = paddle.subtract
272
        self.public_python_api = paddle.subtract
273
        self.prim_op_type = "prim"
274 275 276 277 278 279 280
        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),
281
            'Y': convert_float_to_uint16(y),
282 283
        }
        self.outputs = {'Out': convert_float_to_uint16(out)}
284
        self.if_check_prim()
285
        self.if_enable_cinn()
286

287 288 289 290 291 292
    def if_check_prim(self):
        self.check_prim = True

    def if_enable_cinn(self):
        self.enable_cinn = False

293 294 295 296
    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
297
        self.check_grad(['X', 'Y'], 'Out', check_prim=self.check_prim)
298 299

    def test_check_grad_ingore_x(self):
300 301 302
        self.check_grad(
            ['Y'], 'Out', no_grad_set=set("X"), check_prim=self.check_prim
        )
303 304


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


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


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

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

353 354 355 356 357
    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 已提交
358

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    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,
        )


378 379 380 381 382 383 384 385 386 387 388
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 已提交
389 390
    def setUp(self):
        self.op_type = "elementwise_sub"
391
        self.dtype = np.uint16
392
        self.python_api = paddle.subtract
G
gongweibao 已提交
393
        self.inputs = {
394 395 396 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
            '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 已提交
438 439 440 441
        }

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


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
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 已提交
476 477 478
class TestElementwiseSubOp_broadcast_2(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_sub"
479
        self.python_api = paddle.subtract
480
        self.public_python_api = paddle.subtract
481
        self.prim_op_type = "prim"
482
        self.init_dtype()
G
gongweibao 已提交
483
        self.inputs = {
484 485
            'X': np.random.rand(2, 3, 100).astype(self.dtype),
            'Y': np.random.rand(100).astype(self.dtype),
G
gongweibao 已提交
486 487 488
        }

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

493 494 495 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

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 已提交
547 548


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

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


565 566 567 568 569
class TestElementwiseSubFP16OP_broadcast_3(TestElementwiseSubOp_broadcast_3):
    def init_dtype(self):
        self.dtype = np.float16


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

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

@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
611 612


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

627 628 629 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

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()
656 657 658 659 660


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

672 673 674 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

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()
701 702 703 704 705


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

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

721 722 723 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

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


C
chentianyu03 已提交
755 756 757
class TestComplexElementwiseSubOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_sub"
758
        self.python_api = paddle.subtract
759
        self.public_python_api = paddle.subtract
760
        self.prim_op_type = "prim"
C
chentianyu03 已提交
761 762 763 764 765 766 767
        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),
768
            'Y': OpTest.np_dtype_to_fluid_dtype(self.y),
C
chentianyu03 已提交
769 770 771
        }
        self.attrs = {'axis': -1, 'use_mkldnn': False}
        self.outputs = {'Out': self.out}
772
        self.if_check_prim()
773
        self.if_enable_cinn()
C
chentianyu03 已提交
774 775 776 777 778 779

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

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

    def init_grad_input_output(self):
788 789 790
        self.grad_out = np.ones(self.shape, self.dtype) + 1j * np.ones(
            self.shape, self.dtype
        )
C
chentianyu03 已提交
791 792 793 794 795 796 797
        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):
798 799 800 801 802
        self.check_grad(
            ['X', 'Y'],
            'Out',
            user_defined_grads=[self.grad_x, self.grad_y],
            user_defined_grad_outputs=[self.grad_out],
803
            check_prim=self.check_prim,
804
        )
C
chentianyu03 已提交
805 806

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

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

826
    def if_enable_cinn(self):
827 828 829 830 831
        self.enable_cinn = False

    def if_check_prim(self):
        self.check_prim = True

C
chentianyu03 已提交
832 833 834 835 836

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(
837 838
            self.dtype
        ) + 1j * np.random.random(self.shape).astype(self.dtype)
C
chentianyu03 已提交
839 840 841
        self.out = self.x - self.y

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

848
    def if_enable_cinn(self):
849 850 851 852 853
        self.enable_cinn = False

    def if_check_prim(self):
        self.check_prim = False

C
chentianyu03 已提交
854

855 856 857 858 859 860
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()):
861
            x = paddle.static.data(name="x", shape=[2, 3], dtype="float32")
862
            y = paddle.static.data(name='y', shape=[2, 3], dtype=np.float32)
863 864 865 866 867 868 869 870 871

            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 {
872 873
                    "x": np.array([2, 3, 4]).astype(np.float32),
                    "y": np.array([1, 5, 2]).astype(np.float32),
874 875
                }

876 877
            x = paddle.static.data(name="x", shape=[3], dtype=np.float32)
            y = paddle.static.data(name="y", shape=[3], dtype=np.float32)
878 879 880 881
            z = self._executed_api(x, y)
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            z_value = exe.run(feed=gen_data(), fetch_list=[z.name])
882
            z_expected = np.array([1.0, -2.0, 2.0])
883 884 885 886 887 888 889 890 891
            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)
892
            np_z = z.numpy(False)
893
            z_expected = np.array([1.0, -2.0, 2.0])
894 895 896 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
            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')


960
class TestFloatElementwiseSubop(unittest.TestCase):
961
    def test_dygraph_sub(self):
962 963 964 965 966 967 968 969 970 971 972
        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
973 974 975
        np.testing.assert_allclose(
            actual_out, expect_out, rtol=1e-07, atol=1e-07
        )
976 977 978 979

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

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

        paddle.enable_static()


994
class TestFloatElementwiseSubop1(unittest.TestCase):
995
    def test_dygraph_sub(self):
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        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()


1020 1021 1022 1023 1024 1025 1026 1027 1028
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(
1029
                name='data', shape=[None, 3, 32, 32], dtype=np.float32
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
            )
            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 已提交
1046
if __name__ == '__main__':
C
chentianyu03 已提交
1047
    paddle.enable_static()
G
gongweibao 已提交
1048
    unittest.main()