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

G
guosheng 已提交
15
import unittest
16

G
guosheng 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
19

20
import paddle
21 22
from paddle import fluid
from paddle.fluid import Program, core, program_guard
23
from paddle.fluid.framework import convert_np_dtype_to_dtype_
G
guosheng 已提交
24 25


26
class TestSumOp(OpTest):
G
guosheng 已提交
27
    def setUp(self):
W
Wilber 已提交
28 29 30 31 32
        self.init_dtype()
        self.init_input()
        self.init_attrs()
        self.calc_output()

F
From00 已提交
33
        self.python_api = paddle.sum
34
        self.public_python_api = paddle.sum
35
        self.op_type = "reduce_sum"
36
        self.prim_op_type = "prim"
W
Wilber 已提交
37 38
        self.inputs = {'X': self.x}
        self.outputs = {'Out': self.out}
39
        self.enable_cinn = True
40

W
Wilber 已提交
41 42
    def init_dtype(self):
        self.dtype = np.float64
43

W
Wilber 已提交
44 45
    def init_input(self):
        self.x = np.random.random((5, 6, 10)).astype(self.dtype)
46

W
Wilber 已提交
47 48
    def init_attrs(self):
        self.attrs = {'dim': [0]}
49

W
Wilber 已提交
50 51
    def calc_output(self):
        self.out = self.x.sum(axis=tuple(self.attrs['dim']))
52 53

    def test_check_output(self):
W
wanghuancoder 已提交
54
        self.check_output()
55 56

    def test_check_grad(self):
W
Wilber 已提交
57
        self.check_grad(['X'], 'Out', check_prim=True)
58 59


60 61 62 63 64 65 66 67 68 69 70 71 72 73
class TestComplexSumOP(TestSumOp):
    def init_dtype(self):
        self.dtype = np.complex128

    def init_input(self):
        self.x = np.random.random((3, 4)).astype(self.dtype)

    def init_attrs(self):
        self.attrs = {'dim': [0]}

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', check_prim=False)


W
Wilber 已提交
74 75
class TestSumOp_ZeroDim(TestSumOp):
    def init_attrs(self):
76
        self.attrs = {'dim': []}
77

W
Wilber 已提交
78 79 80 81 82
    def init_input(self):
        self.x = np.random.random([]).astype(self.dtype)

    def calc_output(self):
        self.out = self.x.sum(axis=None)
83 84

    def test_check_grad(self):
W
wanghuancoder 已提交
85
        self.check_grad(['X'], 'Out')
86 87


W
Wilber 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101
class TestSumOp5D(TestSumOp):
    def init_input(self):
        self.x = np.random.random((1, 2, 5, 6, 10)).astype(self.dtype)

    def init_attrs(self):
        self.attrs = {'dim': [0]}


class TestSumOp6D(TestSumOp):
    def init_input(self):
        self.x = np.random.random((1, 1, 2, 5, 6, 10)).astype(self.dtype)

    def init_attrs(self):
        self.attrs = {'dim': [0]}
102

W
Wilber 已提交
103 104 105 106 107 108 109

class TestSumOp8D(TestSumOp):
    def init_input(self):
        self.x = np.random.random((1, 3, 1, 2, 1, 4, 3, 10)).astype(self.dtype)

    def init_attrs(self):
        self.attrs = {'dim': (0, 3)}
110 111

    def test_check_output(self):
W
Wilber 已提交
112
        self.check_output()
113 114

    def test_check_grad(self):
W
Wilber 已提交
115
        self.check_grad(['X'], 'Out')
116 117


W
Wilber 已提交
118 119 120 121 122
class TestSumOp_withInt(TestSumOp):
    def init_input(self):
        # ref to https://en.wikipedia.org/wiki/Half-precision_floating-point_format
        # Precision limitations on integer values between 0 and 2048 can be exactly represented
        self.x = np.random.randint(0, 30, (10, 10)).astype(self.dtype)
123

W
Wilber 已提交
124 125
    def init_attrs(self):
        self.attrs = {'dim': (0, 1)}
126 127

    def test_check_output(self):
W
wanghuancoder 已提交
128
        self.check_output()
129 130 131 132

    def calc_gradient(self):
        x = self.inputs["X"]
        grad = np.ones(x.shape, dtype=x.dtype)
133
        return (grad,)
134 135

    def test_check_grad(self):
136
        self.check_grad(
137 138
            ['X'],
            'Out',
W
Wilber 已提交
139
            user_defined_grads=self.calc_gradient(),
140
            check_prim=True,
141
        )
142 143


W
Wilber 已提交
144 145 146
class TestSumOp3Dim(TestSumOp):
    def init_input(self):
        self.x = np.random.uniform(0, 0.1, (5, 6, 10)).astype(self.dtype)
147

W
Wilber 已提交
148 149
    def init_attrs(self):
        self.attrs = {'dim': (0, 1, 2)}
G
guosheng 已提交
150

151
    def test_check_output(self):
W
wanghuancoder 已提交
152
        self.check_output()
G
guosheng 已提交
153

W
Wilber 已提交
154 155 156 157
    def calc_gradient(self):
        x = self.inputs["X"]
        grad = np.ones(x.shape, dtype=x.dtype)
        return (grad,)
G
guosheng 已提交
158

W
Wilber 已提交
159 160 161 162 163 164 165
    def test_check_grad(self):
        self.check_grad(
            ['X'],
            'Out',
            user_defined_grads=self.calc_gradient(),
            check_prim=True,
        )
166 167


W
Wilber 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
def create_test_fp16_class(parent):
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
    class TestSumOpFp16(parent):
        def init_dtype(self):
            self.dtype = np.float16

        def test_check_output(self):
            self.check_output()

        def test_check_grad(self):
            self.check_grad(
                ['X'],
                'Out',
                check_prim=True,
            )


create_test_fp16_class(TestSumOp)
create_test_fp16_class(TestSumOp_ZeroDim)
create_test_fp16_class(TestSumOp5D)
create_test_fp16_class(TestSumOp6D)
create_test_fp16_class(TestSumOp8D)
create_test_fp16_class(TestSumOp_withInt)
create_test_fp16_class(TestSumOp3Dim)


def create_test_bf16_class(parent):
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
    class TestSumOpBf16(parent):
        def setUp(self):
            self.inputs = {'X': convert_float_to_uint16(self.x)}
            self.outputs = {'Out': convert_float_to_uint16(self.out)}
            self.enable_cinn = False

        def init_dtype(self):
            self.dtype = np.uint16

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

        def test_check_grad(self):
            place = core.CUDAPlace(0)
            self.check_grad_with_place(
                place,
                ['X'],
                'Out',
                user_defined_grads=self.gradient,
                check_prim=True,
            )

        def calc_gradient(self):
            x = self.x
            grad = np.ones(x.shape, dtype=x.dtype)
            return [grad]


create_test_bf16_class(TestSumOp)
create_test_bf16_class(TestSumOp_ZeroDim)
create_test_bf16_class(TestSumOp5D)
create_test_bf16_class(TestSumOp6D)
create_test_bf16_class(TestSumOp8D)
create_test_bf16_class(TestSumOp_withInt)
create_test_bf16_class(TestSumOp3Dim)
236 237


238 239
@skip_check_grad_ci(
    reason="reduce_max is discontinuous non-derivable function,"
240 241
    " its gradient check is not supported by unittest framework."
)
242 243
class TestMaxOp(OpTest):
    """Remove Max with subgradient from gradient check to confirm the success of CI."""
G
guosheng 已提交
244 245

    def setUp(self):
246
        self.op_type = "reduce_max"
247
        self.prim_op_type = "prim"
248
        self.python_api = paddle.max
249
        self.public_python_api = paddle.max
250
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
W
whs 已提交
251 252 253 254
        self.attrs = {'dim': [-1]}
        self.outputs = {
            'Out': self.inputs['X'].max(axis=tuple(self.attrs['dim']))
        }
255 256

    def test_check_output(self):
W
wanghuancoder 已提交
257
        self.check_output()
G
guosheng 已提交
258

259 260 261 262 263 264 265 266 267
    def test_check_grad(self):
        # only composite op support gradient check of reduce_max
        self.check_grad(
            ['X'],
            'Out',
            check_prim=True,
            only_check_prim=True,
        )

G
guosheng 已提交
268

269 270 271 272 273
class TestMaxOp_ZeroDim(OpTest):
    """Remove Max with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_max"
274
        self.prim_op_type = "prim"
275
        self.python_api = paddle.max
276 277
        self.public_python_api = paddle.max
        self.enable_cinn = False
278 279 280 281 282 283 284
        self.inputs = {'X': np.random.random([]).astype("float64")}
        self.attrs = {'dim': []}
        self.outputs = {
            'Out': self.inputs['X'].max(axis=tuple(self.attrs['dim']))
        }

    def test_check_output(self):
W
wanghuancoder 已提交
285
        self.check_output()
286

287 288 289 290 291 292 293 294 295 296
    def test_check_grad(self):
        # only composite op support gradient check of reduce_max
        self.check_grad(
            ['X'],
            'Out',
            check_prim=True,
            only_check_prim=True,
        )


297
class TestMaxFP32Op(OpTest):
298 299 300 301 302 303 304
    """Remove Max with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_max"
        self.prim_op_type = "prim"
        self.python_api = paddle.max
        self.public_python_api = paddle.max
305
        self.init_dtype()
306
        self.if_enable_cinn()
307 308 309 310 311 312
        if self.dtype == np.uint16:
            x = np.random.random((5, 6, 10)).astype(np.float32)
            self.inputs = {'X': convert_float_to_uint16(x)}
        else:
            x = np.random.random((5, 6, 10)).astype(self.dtype)
            self.inputs = {'X': x}
313
        self.attrs = {'dim': [-1], 'keep_dim': True}
314 315 316 317 318
        out = x.max(axis=tuple(self.attrs['dim']), keepdims=True)
        if self.dtype == np.uint16:
            self.outputs = {'Out': convert_float_to_uint16(out)}
        else:
            self.outputs = {'Out': out}
319

320 321 322
    def if_enable_cinn(self):
        pass

323
    def test_check_output(self):
W
wanghuancoder 已提交
324
        self.check_output()
325 326 327 328 329 330 331 332 333 334

    def test_check_grad(self):
        # only composite op support gradient check of reduce_max
        self.check_grad(
            ['X'],
            'Out',
            check_prim=True,
            only_check_prim=True,
        )

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    def init_dtype(self):
        self.dtype = np.float32


class TestMaxFP16Op(TestMaxFP32Op):
    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 or not support the bfloat16",
)
class TestMaxBF16Op(TestMaxFP32Op):
    def init_dtype(self):
        self.dtype = np.uint16

353 354 355
    def if_enable_cinn(self):
        self.enable_cinn = False

356 357 358 359 360 361 362 363 364 365 366 367 368
    def test_check_output(self):
        self.check_output_with_place(core.CUDAPlace(0))

    def test_check_grad(self):
        # only composite op support gradient check of reduce_max
        self.check_grad_with_place(
            core.CUDAPlace(0),
            ['X'],
            'Out',
            check_prim=True,
            only_check_prim=True,
        )

369

370 371
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
372 373
    " its gradient check is not supported by unittest framework."
)
374 375
class TestMinOp(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""
G
guosheng 已提交
376

377 378
    def setUp(self):
        self.op_type = "reduce_min"
379
        self.python_api = paddle.min
380
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
W
whs 已提交
381 382 383 384
        self.attrs = {'dim': [2]}
        self.outputs = {
            'Out': self.inputs['X'].min(axis=tuple(self.attrs['dim']))
        }
G
guosheng 已提交
385

386
    def test_check_output(self):
W
wanghuancoder 已提交
387
        self.check_output()
G
guosheng 已提交
388 389


390 391 392 393 394 395 396 397 398 399 400 401 402
class TestMinOp_ZeroDim(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
        self.python_api = paddle.min
        self.inputs = {'X': np.random.random([]).astype("float64")}
        self.attrs = {'dim': []}
        self.outputs = {
            'Out': self.inputs['X'].min(axis=tuple(self.attrs['dim']))
        }

    def test_check_output(self):
W
wanghuancoder 已提交
403
        self.check_output()
404 405


406 407 408 409 410
class TestMin6DOp(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
411
        self.python_api = paddle.min
412 413 414 415 416 417 418 419 420
        self.inputs = {
            'X': np.random.random((2, 4, 3, 5, 6, 10)).astype("float64")
        }
        self.attrs = {'dim': [2, 4]}
        self.outputs = {
            'Out': self.inputs['X'].min(axis=tuple(self.attrs['dim']))
        }

    def test_check_output(self):
W
wanghuancoder 已提交
421
        self.check_output()
422 423 424 425 426 427 428


class TestMin8DOp(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
429
        self.python_api = paddle.min
430 431 432 433 434 435 436 437 438
        self.inputs = {
            'X': np.random.random((2, 4, 3, 5, 6, 3, 2, 4)).astype("float64")
        }
        self.attrs = {'dim': [2, 3, 4]}
        self.outputs = {
            'Out': self.inputs['X'].min(axis=tuple(self.attrs['dim']))
        }

    def test_check_output(self):
W
wanghuancoder 已提交
439
        self.check_output()
440 441


442 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 476 477 478 479 480 481 482 483 484 485 486
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
    " its gradient check is not supported by unittest framework."
)
class TestMinFP16Op(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
        self.python_api = paddle.min
        self.public_python_api = paddle.min
        self.init_dtype()
        if self.dtype == np.uint16:
            x = np.random.random((5, 6, 10)).astype(np.float32)
            self.inputs = {'X': convert_float_to_uint16(x)}
        else:
            x = np.random.random((5, 6, 10)).astype(self.dtype)
            self.inputs = {'X': x}
        self.attrs = {'dim': [2], 'keep_dim': True}
        out = x.min(axis=tuple(self.attrs['dim']), keepdims=True)
        if self.dtype == np.uint16:
            self.outputs = {'Out': convert_float_to_uint16(out)}
        else:
            self.outputs = {'Out': out}

    def init_dtype(self):
        self.dtype = np.float16

    def test_check_output(self):
        self.check_output()


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support the bfloat16",
)
class TestMinBF16Op(TestMinFP16Op):
    def init_dtype(self):
        self.dtype = np.uint16

    def test_check_output(self):
        self.check_output_with_place(core.CUDAPlace(0))


H
hong 已提交
487 488 489 490
def raw_reduce_prod(x, dim=[0], keep_dim=False):
    return paddle.prod(x, dim, keep_dim)


491 492 493
class TestProdOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
494
        self.python_api = raw_reduce_prod
495 496
        self.public_python_api = raw_reduce_prod
        self.prim_op_type = "prim"
497
        self.init_data_type()
498 499 500 501
        self.init_inputs_and_outputs()
        self.if_enable_cinn()

    def init_inputs_and_outputs(self):
502
        self.inputs = {'X': np.random.random((5, 6, 10)).astype(self.data_type)}
503 504
        self.outputs = {'Out': self.inputs['X'].prod(axis=0)}

505
    def init_data_type(self):
506 507 508
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
509

510 511 512
    def if_enable_cinn(self):
        pass

513
    def test_check_output(self):
W
wanghuancoder 已提交
514
        self.check_output()
515 516

    def test_check_grad(self):
517 518 519
        self.check_grad(['X'], 'Out', check_prim=True)


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 550 551 552 553 554 555 556 557 558 559 560 561 562
@unittest.skipIf(
    not paddle.is_compiled_with_cuda(), "FP16 test runs only on GPU"
)
class TestProdFP16OP(TestProdOp):
    def init_data_type(self):
        self.data_type = "float16"

    def test_check_output(self):
        self.check_output_with_place(place=paddle.CUDAPlace(0))

    def test_check_grad(self):
        self.check_grad_with_place(
            paddle.CUDAPlace(0), ['X'], 'Out', check_prim=True
        )


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support the bfloat16",
)
class TestProdBFP16OP(TestProdOp):
    def init_data_type(self):
        self.data_type = np.uint16

    def init_inputs_and_outputs(self):
        x = np.random.random((5, 6, 10)).astype("float32")
        out = x.prod(axis=0)
        self.inputs = {'X': convert_float_to_uint16(x)}
        self.outputs = {'Out': convert_float_to_uint16(out)}

    def if_enable_cinn(self):
        self.enable_cinn = False

    def test_check_output(self):
        self.check_output_with_place(place=paddle.CUDAPlace(0))

    def test_check_grad(self):
        self.check_grad_with_place(
            paddle.CUDAPlace(0), ['X'], 'Out', check_prim=True
        )


563 564 565
class TestProdOpFp64(TestProdOp):
    def init_data_type(self):
        self.data_type = "float64"
566 567


568 569
class TestProdOp_ZeroDim(OpTest):
    def setUp(self):
570 571
        self.python_api = raw_reduce_prod
        self.public_python_api = raw_reduce_prod
572
        self.op_type = "reduce_prod"
573
        self.prim_op_type = "prim"
574 575 576 577
        self.inputs = {'X': np.random.random([]).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].prod()}
        self.attrs = {'dim': [], 'reduce_all': True}

578 579 580
        # 0-D tensor doesn't support in cinn
        self.enable_cinn = False

581 582 583 584 585
    def init_inputs_and_outputs(self):
        self.inputs = {'X': np.random.random([]).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].prod()}
        self.attrs = {'dim': [], 'reduce_all': True}

586
    def test_check_output(self):
W
wanghuancoder 已提交
587
        self.check_output()
588 589

    def test_check_grad(self):
590
        self.check_grad(['X'], 'Out', check_prim=True)
591 592


593 594 595
class TestProd6DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
596
        self.python_api = raw_reduce_prod
597 598
        self.public_python_api = raw_reduce_prod
        self.prim_op_type = "prim"
599
        self.init_data_type()
600 601 602 603 604 605 606 607 608
        self.init_inputs_and_outputs()
        self.if_enable_cinn()

    def init_data_type(self):
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )

    def init_inputs_and_outputs(self):
609
        self.inputs = {
610
            'X': np.random.random((5, 6, 2, 3, 4, 2)).astype(self.data_type)
611 612 613 614 615 616
        }
        self.attrs = {'dim': [2, 3, 4]}
        self.outputs = {
            'Out': self.inputs['X'].prod(axis=tuple(self.attrs['dim']))
        }

617 618
    def if_enable_cinn(self):
        pass
619

620
    def test_check_output(self):
W
wanghuancoder 已提交
621
        self.check_output()
622 623

    def test_check_grad(self):
624
        self.check_grad(['X'], 'Out', check_prim=True)
625 626


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 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
@unittest.skipIf(
    not paddle.is_compiled_with_cuda(), "FP16 test runs only on GPU"
)
class TestProd6DFP16OP(TestProd6DOp):
    def init_data_type(self):
        self.data_type = "float16"

    def test_check_output(self):
        self.check_output_with_place(place=paddle.CUDAPlace(0))

    def test_check_grad(self):
        self.check_grad_with_place(
            paddle.CUDAPlace(0), ['X'], 'Out', check_prim=True
        )


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support the bfloat16",
)
class TestProd6DBFP16OP(TestProd6DOp):
    def init_data_type(self):
        self.data_type = np.uint16

    def init_inputs_and_outputs(self):
        x = np.random.random((5, 6, 2, 3, 4, 2)).astype("float32")
        self.attrs = {'dim': [2, 3, 4]}
        out = x.prod(axis=tuple(self.attrs['dim']))
        self.inputs = {'X': convert_float_to_uint16(x)}
        self.outputs = {'Out': convert_float_to_uint16(out)}

    def if_enable_cinn(self):
        self.enable_cinn = False

    def test_check_output(self):
        self.check_output_with_place(place=paddle.CUDAPlace(0))

    def test_check_grad(self):
        self.check_grad_with_place(
            paddle.CUDAPlace(0), ['X'], 'Out', check_prim=True
        )


671 672 673
class TestProd8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
674
        self.python_api = raw_reduce_prod
675
        self.public_python_api = raw_reduce_prod
676
        self.init_data_type()
677 678 679
        self.init_inputs_and_outputs()

    def init_inputs_and_outputs(self):
680
        self.inputs = {
681 682 683
            'X': np.random.random((2, 5, 3, 2, 2, 3, 4, 2)).astype(
                self.data_type
            )
684 685 686 687 688 689
        }
        self.attrs = {'dim': [2, 3, 4]}
        self.outputs = {
            'Out': self.inputs['X'].prod(axis=tuple(self.attrs['dim']))
        }

690
    def init_data_type(self):
691 692 693
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
694

695
    def test_check_output(self):
W
wanghuancoder 已提交
696
        self.check_output()
697 698

    def test_check_grad(self):
W
wanghuancoder 已提交
699
        self.check_grad(['X'], 'Out')
700 701


702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
@unittest.skipIf(
    not paddle.is_compiled_with_cuda(), "FP16 test runs only on GPU"
)
class TestProd8DFP16OP(TestProd8DOp):
    def init_data_type(self):
        self.data_type = "float16"

    def test_check_output(self):
        self.check_output_with_place(place=paddle.CUDAPlace(0))

    def test_check_grad(self):
        self.check_grad_with_place(paddle.CUDAPlace(0), ['X'], 'Out')


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support the bfloat16",
)
class TestProd8DBFP16OP(TestProd8DOp):
    def init_data_type(self):
        self.data_type = np.uint16

    def init_inputs_and_outputs(self):
        x = np.random.random((2, 5, 3, 2, 2, 3, 4, 2)).astype("float32")
        self.attrs = {'dim': [2, 3, 4]}
        out = x.prod(axis=tuple(self.attrs['dim']))
        self.inputs = {'X': convert_float_to_uint16(x)}
        self.outputs = {'Out': convert_float_to_uint16(out)}

    def test_check_output(self):
        self.check_output_with_place(place=paddle.CUDAPlace(0))

    def test_check_grad(self):
        self.check_grad_with_place(paddle.CUDAPlace(0), ['X'], 'Out')


739 740 741 742
def reduce_all_wrapper(x, axis=None, keepdim=False, reduce_all=True, name=None):
    return paddle.all(x, axis, keepdim, name)


Z
zhoukunsheng 已提交
743 744 745
class TestAllOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
746
        self.python_api = reduce_all_wrapper
Z
zhoukunsheng 已提交
747 748 749 750 751
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
        self.outputs = {'Out': self.inputs['X'].all()}
        self.attrs = {'reduce_all': True}

    def test_check_output(self):
W
wanghuancoder 已提交
752
        self.check_output()
Z
zhoukunsheng 已提交
753 754


755 756 757 758 759 760
class TestAllOp_ZeroDim(OpTest):
    def setUp(self):
        self.python_api = paddle.all
        self.op_type = "reduce_all"
        self.inputs = {'X': np.random.randint(0, 2, []).astype("bool")}
        self.outputs = {'Out': self.inputs['X'].all()}
761
        self.attrs = {'dim': []}
762 763

    def test_check_output(self):
W
wanghuancoder 已提交
764
        self.check_output()
765 766


767 768 769
class TestAll8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
770
        self.python_api = paddle.all
771
        self.inputs = {
772 773 774
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
775
        }
776
        self.attrs = {'dim': (2, 3, 4)}
777 778 779
        self.outputs = {'Out': self.inputs['X'].all(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
780
        self.check_output()
781 782


Z
zhoukunsheng 已提交
783 784 785
class TestAllOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
786
        self.python_api = paddle.all
Z
zhoukunsheng 已提交
787
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
788
        self.attrs = {'dim': (1,)}
789 790 791
        self.outputs = {'Out': self.inputs['X'].all(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
792
        self.check_output()
793 794 795 796 797


class TestAll8DOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
798
        self.python_api = paddle.all
799
        self.inputs = {
800 801 802
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
803 804 805
        }
        self.attrs = {'dim': (1, 3, 4)}
        self.outputs = {'Out': self.inputs['X'].all(axis=self.attrs['dim'])}
Z
zhoukunsheng 已提交
806 807

    def test_check_output(self):
W
wanghuancoder 已提交
808
        self.check_output()
Z
zhoukunsheng 已提交
809 810 811 812 813


class TestAllOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
814
        self.python_api = paddle.all
Z
zhoukunsheng 已提交
815 816 817
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
        self.attrs = {'dim': [1], 'keep_dim': True}
        self.outputs = {
818
            'Out': np.expand_dims(self.inputs['X'].all(axis=1), axis=1)
Z
zhoukunsheng 已提交
819 820 821
        }

    def test_check_output(self):
W
wanghuancoder 已提交
822
        self.check_output()
Z
zhoukunsheng 已提交
823 824


825 826 827
class TestAll8DOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
828
        self.python_api = paddle.all
829
        self.inputs = {
830 831 832
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
833
        }
834
        self.attrs = {'dim': (5,), 'keep_dim': True}
835
        self.outputs = {
836 837 838
            'Out': np.expand_dims(
                self.inputs['X'].all(axis=self.attrs['dim']), axis=5
            )
839 840 841
        }

    def test_check_output(self):
W
wanghuancoder 已提交
842
        self.check_output()
843 844


845 846 847 848 849
class TestAllOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of reduce_all_op must be Variable.
            input1 = 12
850
            self.assertRaises(TypeError, paddle.all, input1)
851
            # The input dtype of reduce_all_op must be bool.
G
GGBond8488 已提交
852 853
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
854
            )
855
            self.assertRaises(TypeError, paddle.all, input2)
856 857


858 859 860 861
def reduce_any_wrapper(x, axis=None, keepdim=False, reduce_all=True, name=None):
    return paddle.any(x, axis, keepdim, name)


Z
zhoukunsheng 已提交
862 863 864
class TestAnyOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
865
        self.python_api = reduce_any_wrapper
Z
zhoukunsheng 已提交
866 867 868 869 870
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
        self.outputs = {'Out': self.inputs['X'].any()}
        self.attrs = {'reduce_all': True}

    def test_check_output(self):
W
wanghuancoder 已提交
871
        self.check_output()
Z
zhoukunsheng 已提交
872 873


874 875 876 877 878 879
class TestAnyOp_ZeroDim(OpTest):
    def setUp(self):
        self.python_api = paddle.any
        self.op_type = "reduce_any"
        self.inputs = {'X': np.random.randint(0, 2, []).astype("bool")}
        self.outputs = {'Out': self.inputs['X'].any()}
880
        self.attrs = {'dim': []}
881 882

    def test_check_output(self):
W
wanghuancoder 已提交
883
        self.check_output()
884 885


886 887 888
class TestAny8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
889
        self.python_api = paddle.any
890
        self.inputs = {
891 892 893
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
894
        }
895
        self.attrs = {'dim': (3, 5, 4)}
896 897 898
        self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
899
        self.check_output()
900 901


Z
zhoukunsheng 已提交
902 903 904
class TestAnyOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
905
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
906 907 908 909 910
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
        self.attrs = {'dim': [1]}
        self.outputs = {'Out': self.inputs['X'].any(axis=1)}

    def test_check_output(self):
W
wanghuancoder 已提交
911
        self.check_output()
Z
zhoukunsheng 已提交
912 913


914 915 916
class TestAny8DOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
917
        self.python_api = paddle.any
918
        self.inputs = {
919 920 921
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
922 923 924 925 926
        }
        self.attrs = {'dim': (3, 6)}
        self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
927
        self.check_output()
928 929


Z
zhoukunsheng 已提交
930 931 932
class TestAnyOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
933
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
934
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
935
        self.attrs = {'dim': (1,), 'keep_dim': True}
936
        self.outputs = {
937 938 939
            'Out': np.expand_dims(
                self.inputs['X'].any(axis=self.attrs['dim']), axis=1
            )
940 941 942
        }

    def test_check_output(self):
W
wanghuancoder 已提交
943
        self.check_output()
944 945 946 947 948


class TestAny8DOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
949
        self.python_api = paddle.any
950
        self.inputs = {
951 952 953
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
954
        }
955
        self.attrs = {'dim': (1,), 'keep_dim': True}
Z
zhoukunsheng 已提交
956
        self.outputs = {
957 958 959
            'Out': np.expand_dims(
                self.inputs['X'].any(axis=self.attrs['dim']), axis=1
            )
Z
zhoukunsheng 已提交
960 961 962
        }

    def test_check_output(self):
W
wanghuancoder 已提交
963
        self.check_output()
Z
zhoukunsheng 已提交
964 965


966 967 968 969 970
class TestAnyOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The input type of reduce_any_op must be Variable.
            input1 = 12
971
            self.assertRaises(TypeError, paddle.any, input1)
972
            # The input dtype of reduce_any_op must be bool.
G
GGBond8488 已提交
973 974
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
975
            )
976
            self.assertRaises(TypeError, paddle.any, input2)
977 978


Q
qiaolongfei 已提交
979
class Test1DReduce(OpTest):
G
guosheng 已提交
980
    def setUp(self):
981
        self.op_type = "reduce_sum"
982
        self.python_api = paddle.sum
983
        self.public_python_api = paddle.sum
984
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
985
        self.inputs = {'X': np.random.random(120).astype("float64")}
Q
qiaolongfei 已提交
986
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
987
        self.enable_cinn = True
988 989 990

    def test_check_output(self):
        self.check_output()
G
guosheng 已提交
991

992
    def test_check_grad(self):
993
        self.check_grad(['X'], 'Out', check_prim=True)
G
guosheng 已提交
994 995


Q
qiaolongfei 已提交
996
class Test2DReduce0(Test1DReduce):
G
guosheng 已提交
997
    def setUp(self):
998
        self.op_type = "reduce_sum"
999
        self.python_api = paddle.sum
1000
        self.public_python_api = paddle.sum
1001
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1002 1003
        self.attrs = {'dim': [0]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
1004 1005 1006
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}


Q
qiaolongfei 已提交
1007 1008 1009
class Test2DReduce1(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1010
        self.python_api = paddle.sum
1011
        self.public_python_api = paddle.sum
1012
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1013 1014
        self.attrs = {'dim': [1]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
Q
qiaolongfei 已提交
1015 1016 1017 1018 1019 1020 1021 1022
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }


class Test3DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1023
        self.python_api = paddle.sum
1024
        self.public_python_api = paddle.sum
1025
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        self.attrs = {'dim': [1]}
        self.inputs = {'X': np.random.random((5, 6, 7)).astype("float64")}
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }


class Test3DReduce1(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1036
        self.python_api = paddle.sum
1037
        self.public_python_api = paddle.sum
1038
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        self.attrs = {'dim': [2]}
        self.inputs = {'X': np.random.random((5, 6, 7)).astype("float64")}
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }


class Test3DReduce2(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1049
        self.python_api = paddle.sum
1050
        self.public_python_api = paddle.sum
1051
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        self.attrs = {'dim': [-2]}
        self.inputs = {'X': np.random.random((5, 6, 7)).astype("float64")}
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }


class Test3DReduce3(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1062
        self.python_api = paddle.sum
1063
        self.public_python_api = paddle.sum
1064
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1065 1066 1067 1068 1069
        self.attrs = {'dim': [1, 2]}
        self.inputs = {'X': np.random.random((5, 6, 7)).astype("float64")}
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }
G
guosheng 已提交
1070 1071


W
wanghuancoder 已提交
1072 1073 1074 1075
def reduce_sum_wrapper2(x, axis=[0], dtype=None, keepdim=False):
    return paddle._C_ops.sum(x, axis, dtype, keepdim)


1076 1077 1078
class Test8DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
1079
        self.python_api = reduce_sum_wrapper2
1080 1081 1082 1083 1084 1085 1086 1087
        self.attrs = {'dim': (4, 2, 3)}
        self.inputs = {
            'X': np.random.random((2, 5, 3, 2, 2, 3, 4, 2)).astype("float64")
        }
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }

1088 1089 1090 1091 1092 1093
    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')

1094

Q
qiaolongfei 已提交
1095 1096 1097
class TestKeepDimReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1098
        self.python_api = paddle.sum
1099
        self.public_python_api = paddle.sum
1100
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1101
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
Q
qiaolongfei 已提交
1102
        self.attrs = {'dim': [1], 'keep_dim': True}
Q
qiaolongfei 已提交
1103
        self.outputs = {
1104 1105 1106
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
Q
qiaolongfei 已提交
1107 1108 1109
        }


W
wanghuancoder 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
class TestKeepDimReduceForEager(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
        self.python_api = reduce_sum_wrapper2
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [1], 'keep_dim': True}
        self.outputs = {
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
        }

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


1126 1127 1128
class TestKeepDim8DReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
1129
        self.python_api = reduce_sum_wrapper2
1130 1131 1132 1133 1134
        self.inputs = {
            'X': np.random.random((2, 5, 3, 2, 2, 3, 4, 2)).astype("float64")
        }
        self.attrs = {'dim': (3, 4, 5), 'keep_dim': True}
        self.outputs = {
1135 1136 1137
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
1138 1139
        }

1140 1141 1142 1143 1144 1145
    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')

1146

1147 1148
@skip_check_grad_ci(
    reason="reduce_max is discontinuous non-derivable function,"
1149 1150
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1151 1152 1153 1154 1155
class TestReduceMaxOpMultiAxises(OpTest):
    """Remove Max with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_max"
1156
        self.prim_op_type = "prim"
1157
        self.python_api = paddle.max
1158
        self.public_python_api = paddle.max
W
whs 已提交
1159 1160 1161 1162 1163 1164 1165
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [-2, -1]}
        self.outputs = {
            'Out': self.inputs['X'].max(axis=tuple(self.attrs['dim']))
        }

    def test_check_output(self):
W
wanghuancoder 已提交
1166
        self.check_output()
W
whs 已提交
1167

1168 1169 1170 1171 1172 1173 1174 1175 1176
    def test_check_grad(self):
        # only composite op support gradient check of reduce_max
        self.check_grad(
            ['X'],
            'Out',
            check_prim=True,
            only_check_prim=True,
        )

W
whs 已提交
1177

1178 1179
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
1180 1181
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1182 1183 1184 1185 1186
class TestReduceMinOpMultiAxises(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
1187
        self.python_api = paddle.min
W
whs 已提交
1188 1189 1190 1191 1192 1193 1194
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [1, 2]}
        self.outputs = {
            'Out': self.inputs['X'].min(axis=tuple(self.attrs['dim']))
        }

    def test_check_output(self):
W
wanghuancoder 已提交
1195
        self.check_output()
W
whs 已提交
1196 1197 1198 1199 1200


class TestKeepDimReduceSumMultiAxises(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1201
        self.python_api = paddle.sum
1202
        self.public_python_api = paddle.sum
1203
        self.prim_op_type = "prim"
W
whs 已提交
1204 1205 1206
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [-2, -1], 'keep_dim': True}
        self.outputs = {
1207 1208 1209
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
W
whs 已提交
1210 1211 1212 1213 1214 1215
        }

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1216
        self.check_grad(['X'], 'Out', check_prim=True)
W
whs 已提交
1217 1218


W
wanghuancoder 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
class TestKeepDimReduceSumMultiAxisesForEager(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
        self.python_api = reduce_sum_wrapper2
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [-2, -1], 'keep_dim': True}
        self.outputs = {
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
        }

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


1238 1239 1240
class TestReduceSumWithDimOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1241
        self.python_api = paddle.sum
1242
        self.public_python_api = paddle.sum
1243
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1244
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1245 1246
        self.attrs = {'dim': [1, 2], 'keep_dim': True}
        self.outputs = {
1247 1248 1249
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
1250
        }
1251
        self.enable_cinn = True
1252 1253 1254 1255 1256

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1257
        self.check_grad(['X'], 'Out', check_prim=True)
1258 1259


W
wanghuancoder 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
class TestReduceSumWithDimOneForEager(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
        self.python_api = reduce_sum_wrapper2
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
        self.attrs = {'dim': [1, 2], 'keep_dim': True}
        self.outputs = {
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
        }
        self.enable_cinn = True

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


1280 1281 1282
class TestReduceSumWithNumelOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1283
        self.python_api = paddle.sum
1284
        self.public_python_api = paddle.sum
1285
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1286
        self.inputs = {'X': np.random.random((100, 1)).astype("float64")}
1287 1288
        self.attrs = {'dim': [1], 'keep_dim': False}
        self.outputs = {
1289 1290 1291
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=False
            )
1292
        }
1293
        self.enable_cinn = True
1294 1295 1296 1297 1298

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1299
        self.check_grad(['X'], 'Out', check_prim=False)
1300 1301


1302 1303 1304 1305 1306 1307
def reduce_sum_wrapper(
    x, axis=None, keepdim=False, reduce_all=True, out_dtype=None, name=None
):
    return paddle.sum(x, axis, out_dtype, keepdim, name)


1308 1309 1310
class TestReduceAll(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1311 1312
        self.python_api = reduce_sum_wrapper
        self.public_python_api = reduce_sum_wrapper
1313
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1314
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1315 1316
        self.attrs = {'reduce_all': True, 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum()}
1317
        self.enable_cinn = True
1318 1319 1320 1321 1322

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1323 1324 1325 1326 1327 1328
        self.check_grad(['X'], 'Out', check_prim=True)


class TestReduceAllFp32(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1329 1330
        self.python_api = reduce_sum_wrapper
        self.public_python_api = reduce_sum_wrapper
1331 1332 1333 1334
        self.prim_op_type = "prim"
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float32")}
        self.attrs = {'reduce_all': True, 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum()}
1335
        self.enable_cinn = True
1336 1337 1338 1339 1340 1341

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', check_prim=True)
1342 1343


1344 1345 1346
class Test1DReduceWithAxes1(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1347
        self.python_api = paddle.sum
1348
        self.public_python_api = paddle.sum
1349
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1350
        self.inputs = {'X': np.random.random(100).astype("float64")}
1351 1352
        self.attrs = {'dim': [0], 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
1353
        self.enable_cinn = True
1354 1355

    def test_check_output(self):
1356
        self.check_output()
1357 1358

    def test_check_grad(self):
1359
        self.check_grad(['X'], 'Out', check_prim=True)
1360 1361


1362 1363 1364 1365
def reduce_sum_wrapper_fp64(
    x, axis=None, keepdim=False, reduce_all=True, out_dtype=None, name=None
):
    return paddle.sum(x, axis, 'float64', keepdim, name)
1366 1367


1368 1369 1370
class TestReduceWithDtype(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1371 1372
        self.python_api = reduce_sum_wrapper_fp64
        self.public_python_api = reduce_sum_wrapper_fp64
1373
        self.prim_op_type = "prim"
1374 1375 1376
        self.inputs = {'X': np.random.random((6, 2, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].sum().astype('float64')}
        self.attrs = {'reduce_all': True}
1377 1378 1379 1380 1381 1382
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1383 1384

    def test_check_output(self):
1385
        self.check_output()
1386 1387

    def test_check_grad(self):
1388 1389 1390
        self.check_grad(['X'], 'Out', check_prim=True)


1391 1392 1393
class TestReduceWithDtype1(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1394 1395
        self.python_api = paddle.sum
        self.public_python_api = paddle.sum
1396
        self.prim_op_type = "prim"
1397 1398 1399
        self.inputs = {'X': np.random.random((6, 2, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].sum(axis=1)}
        self.attrs = {'dim': [1]}
1400 1401 1402 1403 1404 1405
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1406
        # cinn op_mapper not support in_dtype/out_dtype attr
1407 1408 1409 1410 1411 1412 1413
        self.enable_cinn = False

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', check_prim=True)
1414 1415 1416 1417 1418


class TestReduceWithDtype2(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1419
        self.prim_op_type = "prim"
1420 1421
        self.python_api = paddle.sum
        self.public_python_api = paddle.sum
1422 1423 1424
        self.inputs = {'X': np.random.random((6, 2, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].sum(axis=1, keepdims=True)}
        self.attrs = {'dim': [1], 'keep_dim': True}
1425 1426 1427 1428 1429 1430
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1431
        # cinn op_mapper not support in_dtype/out_dtype attr
1432 1433 1434 1435 1436 1437 1438
        self.enable_cinn = False

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', check_prim=True)
1439 1440


1441
class TestReduceSumOpError(unittest.TestCase):
1442
    def test_errors(self):
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        with paddle.fluid.framework._static_guard():
            with program_guard(Program(), Program()):
                # The input type of reduce_sum_op must be Variable.
                x1 = fluid.create_lod_tensor(
                    np.array([[-1]]), [[1]], fluid.CPUPlace()
                )
                self.assertRaises(TypeError, paddle.sum, x1)
                # The input dtype of reduce_sum_op  must be float32 or float64 or int32 or int64.
                x2 = paddle.static.data(name='x2', shape=[-1, 4], dtype="uint8")
                self.assertRaises(TypeError, paddle.sum, x2)
1453 1454


1455
class API_TestSumOp(unittest.TestCase):
1456 1457 1458
    def run_static(
        self, shape, x_dtype, attr_axis, attr_dtype=None, np_axis=None
    ):
1459 1460
        if np_axis is None:
            np_axis = attr_axis
1461

1462 1463 1464 1465 1466
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
            with fluid.program_guard(fluid.Program(), fluid.Program()):
1467
                data = paddle.static.data("data", shape=shape, dtype=x_dtype)
1468 1469 1470
                result_sum = paddle.sum(
                    x=data, axis=attr_axis, dtype=attr_dtype
                )
1471 1472 1473

                exe = fluid.Executor(place)
                input_data = np.random.rand(*shape).astype(x_dtype)
1474 1475 1476
                (res,) = exe.run(
                    feed={"data": input_data}, fetch_list=[result_sum]
                )
1477

1478 1479 1480 1481 1482
            np.testing.assert_allclose(
                res,
                np.sum(input_data.astype(attr_dtype), axis=np_axis),
                rtol=1e-05,
            )
1483

1484 1485 1486 1487
    def test_static(self):
        shape = [10, 10]
        axis = 1

1488 1489 1490
        self.run_static(shape, "bool", axis, attr_dtype=None)
        self.run_static(shape, "bool", axis, attr_dtype="int32")
        self.run_static(shape, "bool", axis, attr_dtype="int64")
1491
        self.run_static(shape, "bool", axis, attr_dtype="float16")
1492

1493 1494 1495
        self.run_static(shape, "int32", axis, attr_dtype=None)
        self.run_static(shape, "int32", axis, attr_dtype="int32")
        self.run_static(shape, "int32", axis, attr_dtype="int64")
1496
        self.run_static(shape, "int32", axis, attr_dtype="float64")
1497

1498 1499 1500 1501
        self.run_static(shape, "int64", axis, attr_dtype=None)
        self.run_static(shape, "int64", axis, attr_dtype="int64")
        self.run_static(shape, "int64", axis, attr_dtype="int32")

1502 1503 1504
        self.run_static(shape, "float32", axis, attr_dtype=None)
        self.run_static(shape, "float32", axis, attr_dtype="float32")
        self.run_static(shape, "float32", axis, attr_dtype="float64")
1505
        self.run_static(shape, "float32", axis, attr_dtype="int64")
1506 1507 1508 1509

        self.run_static(shape, "float64", axis, attr_dtype=None)
        self.run_static(shape, "float64", axis, attr_dtype="float32")
        self.run_static(shape, "float64", axis, attr_dtype="float64")
1510 1511 1512

        shape = [5, 5, 5]
        self.run_static(shape, "int32", (0, 1), attr_dtype="int32")
1513 1514 1515
        self.run_static(
            shape, "int32", (), attr_dtype="int32", np_axis=(0, 1, 2)
        )
1516 1517 1518

    def test_dygraph(self):
        np_x = np.random.random([2, 3, 4]).astype('int32')
1519 1520
        with fluid.dygraph.guard():
            x = fluid.dygraph.to_variable(np_x)
1521 1522 1523 1524 1525 1526 1527 1528 1529
            out0 = paddle.sum(x).numpy()
            out1 = paddle.sum(x, axis=0).numpy()
            out2 = paddle.sum(x, axis=(0, 1)).numpy()
            out3 = paddle.sum(x, axis=(0, 1, 2)).numpy()

        self.assertTrue((out0 == np.sum(np_x, axis=(0, 1, 2))).all())
        self.assertTrue((out1 == np.sum(np_x, axis=0)).all())
        self.assertTrue((out2 == np.sum(np_x, axis=(0, 1))).all())
        self.assertTrue((out3 == np.sum(np_x, axis=(0, 1, 2))).all())
1530 1531


1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
class TestAllAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        paddle.enable_static()
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
1542
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1543 1544 1545 1546
            result = paddle.all(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1547 1548 1549 1550 1551
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1552
            np.testing.assert_allclose(fetches[0], np.all(input_np), rtol=1e-05)
1553 1554 1555 1556 1557 1558 1559 1560 1561

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        paddle.disable_static()
        for place in self.places:
            with fluid.dygraph.guard(place):
1562
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1563 1564
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598

                out1 = paddle.all(x)
                np_out1 = out1.numpy()
                expect_res1 = np.all(np_x)
                self.assertTrue((np_out1 == expect_res1).all())

                out2 = paddle.all(x, axis=0)
                np_out2 = out2.numpy()
                expect_res2 = np.all(np_x, axis=0)
                self.assertTrue((np_out2 == expect_res2).all())

                out3 = paddle.all(x, axis=-1)
                np_out3 = out3.numpy()
                expect_res3 = np.all(np_x, axis=-1)
                self.assertTrue((np_out3 == expect_res3).all())

                out4 = paddle.all(x, axis=1, keepdim=True)
                np_out4 = out4.numpy()
                expect_res4 = np.all(np_x, axis=1, keepdims=True)
                self.assertTrue((np_out4 == expect_res4).all())

        paddle.enable_static()


class TestAnyAPI(unittest.TestCase):
    def setUp(self):
        np.random.seed(123)
        paddle.enable_static()
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
1599
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1600 1601 1602 1603
            result = paddle.any(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1604 1605 1606 1607 1608
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1609
            np.testing.assert_allclose(fetches[0], np.any(input_np), rtol=1e-05)
1610 1611 1612 1613 1614 1615 1616 1617 1618

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        paddle.disable_static()
        for place in self.places:
            with fluid.dygraph.guard(place):
1619
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1620 1621
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

                out1 = paddle.any(x)
                np_out1 = out1.numpy()
                expect_res1 = np.any(np_x)
                self.assertTrue((np_out1 == expect_res1).all())

                out2 = paddle.any(x, axis=0)
                np_out2 = out2.numpy()
                expect_res2 = np.any(np_x, axis=0)
                self.assertTrue((np_out2 == expect_res2).all())

                out3 = paddle.any(x, axis=-1)
                np_out3 = out3.numpy()
                expect_res3 = np.any(np_x, axis=-1)
                self.assertTrue((np_out3 == expect_res3).all())

                out4 = paddle.any(x, axis=1, keepdim=True)
                np_out4 = out4.numpy()
                expect_res4 = np.any(np_x, axis=1, keepdims=True)
                self.assertTrue((np_out4 == expect_res4).all())

        paddle.enable_static()


1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
class TestAllZeroError(unittest.TestCase):
    def test_errors(self):
        with paddle.fluid.dygraph.guard():

            def test_0_size():
                array = np.array([], dtype=np.float32)
                x = paddle.to_tensor(np.reshape(array, [0, 0, 0]), dtype='bool')
                paddle.all(x, axis=1)

            self.assertRaises(ValueError, test_0_size)


G
guosheng 已提交
1658
if __name__ == '__main__':
1659
    paddle.enable_static()
G
guosheng 已提交
1660
    unittest.main()