test_reduce_op.py 50.4 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 77
        self.attrs = {'dim': [], 'reduce_all': True}

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')


Z
zhoukunsheng 已提交
739 740 741
class TestAllOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
742
        self.python_api = paddle.all
Z
zhoukunsheng 已提交
743 744 745 746 747
        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 已提交
748
        self.check_output()
Z
zhoukunsheng 已提交
749 750


751 752 753 754 755 756 757 758 759
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()}
        self.attrs = {'dim': [], 'reduce_all': True}

    def test_check_output(self):
W
wanghuancoder 已提交
760
        self.check_output()
761 762


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

    def test_check_output(self):
W
wanghuancoder 已提交
776
        self.check_output()
777 778


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

    def test_check_output(self):
W
wanghuancoder 已提交
788
        self.check_output()
789 790 791 792 793


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

    def test_check_output(self):
W
wanghuancoder 已提交
804
        self.check_output()
Z
zhoukunsheng 已提交
805 806 807 808 809


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

    def test_check_output(self):
W
wanghuancoder 已提交
818
        self.check_output()
Z
zhoukunsheng 已提交
819 820


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

    def test_check_output(self):
W
wanghuancoder 已提交
838
        self.check_output()
839 840


841 842 843 844 845
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
846
            self.assertRaises(TypeError, paddle.all, input1)
847
            # The input dtype of reduce_all_op must be bool.
G
GGBond8488 已提交
848 849
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
850
            )
851
            self.assertRaises(TypeError, paddle.all, input2)
852 853


Z
zhoukunsheng 已提交
854 855 856
class TestAnyOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
857
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
858 859 860 861 862
        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 已提交
863
        self.check_output()
Z
zhoukunsheng 已提交
864 865


866 867 868 869 870 871 872 873 874
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()}
        self.attrs = {'dim': [], 'reduce_all': True}

    def test_check_output(self):
W
wanghuancoder 已提交
875
        self.check_output()
876 877


878 879 880
class TestAny8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
881
        self.python_api = paddle.any
882
        self.inputs = {
883 884 885
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
886 887 888 889 890
        }
        self.attrs = {'reduce_all': True, 'dim': (3, 5, 4)}
        self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
891
        self.check_output()
892 893


Z
zhoukunsheng 已提交
894 895 896
class TestAnyOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
897
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
898 899 900 901 902
        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 已提交
903
        self.check_output()
Z
zhoukunsheng 已提交
904 905


906 907 908
class TestAny8DOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
909
        self.python_api = paddle.any
910
        self.inputs = {
911 912 913
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
914 915 916 917 918
        }
        self.attrs = {'dim': (3, 6)}
        self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
919
        self.check_output()
920 921


Z
zhoukunsheng 已提交
922 923 924
class TestAnyOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
925
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
926
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
927
        self.attrs = {'dim': (1,), 'keep_dim': True}
928
        self.outputs = {
929 930 931
            'Out': np.expand_dims(
                self.inputs['X'].any(axis=self.attrs['dim']), axis=1
            )
932 933 934
        }

    def test_check_output(self):
W
wanghuancoder 已提交
935
        self.check_output()
936 937 938 939 940


class TestAny8DOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
941
        self.python_api = paddle.any
942
        self.inputs = {
943 944 945
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
946
        }
947
        self.attrs = {'dim': (1,), 'keep_dim': True}
Z
zhoukunsheng 已提交
948
        self.outputs = {
949 950 951
            'Out': np.expand_dims(
                self.inputs['X'].any(axis=self.attrs['dim']), axis=1
            )
Z
zhoukunsheng 已提交
952 953 954
        }

    def test_check_output(self):
W
wanghuancoder 已提交
955
        self.check_output()
Z
zhoukunsheng 已提交
956 957


958 959 960 961 962
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
963
            self.assertRaises(TypeError, paddle.any, input1)
964
            # The input dtype of reduce_any_op must be bool.
G
GGBond8488 已提交
965 966
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
967
            )
968
            self.assertRaises(TypeError, paddle.any, input2)
969 970


Q
qiaolongfei 已提交
971
class Test1DReduce(OpTest):
G
guosheng 已提交
972
    def setUp(self):
973
        self.op_type = "reduce_sum"
974
        self.python_api = paddle.sum
975
        self.public_python_api = paddle.sum
976
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
977
        self.inputs = {'X': np.random.random(120).astype("float64")}
Q
qiaolongfei 已提交
978
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
979
        self.enable_cinn = True
980 981 982

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

984
    def test_check_grad(self):
985
        self.check_grad(['X'], 'Out', check_prim=True)
G
guosheng 已提交
986 987


Q
qiaolongfei 已提交
988
class Test2DReduce0(Test1DReduce):
G
guosheng 已提交
989
    def setUp(self):
990
        self.op_type = "reduce_sum"
991
        self.python_api = paddle.sum
992
        self.public_python_api = paddle.sum
993
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
994 995
        self.attrs = {'dim': [0]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
996 997 998
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}


Q
qiaolongfei 已提交
999 1000 1001
class Test2DReduce1(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1002
        self.python_api = paddle.sum
1003
        self.public_python_api = paddle.sum
1004
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1005 1006
        self.attrs = {'dim': [1]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
Q
qiaolongfei 已提交
1007 1008 1009 1010 1011 1012 1013 1014
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }


class Test3DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1015
        self.python_api = paddle.sum
1016
        self.public_python_api = paddle.sum
1017
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
        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"
1028
        self.python_api = paddle.sum
1029
        self.public_python_api = paddle.sum
1030
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        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"
1041
        self.python_api = paddle.sum
1042
        self.public_python_api = paddle.sum
1043
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        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"
1054
        self.python_api = paddle.sum
1055
        self.public_python_api = paddle.sum
1056
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1057 1058 1059 1060 1061
        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 已提交
1062 1063


W
wanghuancoder 已提交
1064 1065 1066 1067
def reduce_sum_wrapper2(x, axis=[0], dtype=None, keepdim=False):
    return paddle._C_ops.sum(x, axis, dtype, keepdim)


1068 1069 1070
class Test8DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
1071
        self.python_api = reduce_sum_wrapper2
1072 1073 1074 1075 1076 1077 1078 1079
        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']))
        }

1080 1081 1082 1083 1084 1085
    def test_check_output(self):
        self.check_output()

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

1086

Q
qiaolongfei 已提交
1087 1088 1089
class TestKeepDimReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1090
        self.python_api = paddle.sum
1091
        self.public_python_api = paddle.sum
1092
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1093
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
Q
qiaolongfei 已提交
1094
        self.attrs = {'dim': [1], 'keep_dim': True}
Q
qiaolongfei 已提交
1095
        self.outputs = {
1096 1097 1098
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
Q
qiaolongfei 已提交
1099 1100 1101
        }


W
wanghuancoder 已提交
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
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')


1118 1119 1120
class TestKeepDim8DReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
1121
        self.python_api = reduce_sum_wrapper2
1122 1123 1124 1125 1126
        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 = {
1127 1128 1129
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
1130 1131
        }

1132 1133 1134 1135 1136 1137
    def test_check_output(self):
        self.check_output()

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

1138

1139 1140
@skip_check_grad_ci(
    reason="reduce_max is discontinuous non-derivable function,"
1141 1142
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1143 1144 1145 1146 1147
class TestReduceMaxOpMultiAxises(OpTest):
    """Remove Max with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_max"
1148
        self.prim_op_type = "prim"
1149
        self.python_api = paddle.max
1150
        self.public_python_api = paddle.max
W
whs 已提交
1151 1152 1153 1154 1155 1156 1157
        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 已提交
1158
        self.check_output()
W
whs 已提交
1159

1160 1161 1162 1163 1164 1165 1166 1167 1168
    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 已提交
1169

1170 1171
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
1172 1173
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1174 1175 1176 1177 1178
class TestReduceMinOpMultiAxises(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
1179
        self.python_api = paddle.min
W
whs 已提交
1180 1181 1182 1183 1184 1185 1186
        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 已提交
1187
        self.check_output()
W
whs 已提交
1188 1189 1190 1191 1192


class TestKeepDimReduceSumMultiAxises(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1193
        self.python_api = paddle.sum
1194
        self.public_python_api = paddle.sum
1195
        self.prim_op_type = "prim"
W
whs 已提交
1196 1197 1198
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [-2, -1], 'keep_dim': True}
        self.outputs = {
1199 1200 1201
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
W
whs 已提交
1202 1203 1204 1205 1206 1207
        }

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1208
        self.check_grad(['X'], 'Out', check_prim=True)
W
whs 已提交
1209 1210


W
wanghuancoder 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
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')


1230 1231 1232
class TestReduceSumWithDimOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1233
        self.python_api = paddle.sum
1234
        self.public_python_api = paddle.sum
1235
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1236
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1237 1238
        self.attrs = {'dim': [1, 2], 'keep_dim': True}
        self.outputs = {
1239 1240 1241
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
1242
        }
1243
        self.enable_cinn = True
1244 1245 1246 1247 1248

    def test_check_output(self):
        self.check_output()

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


W
wanghuancoder 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
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')


1272 1273 1274
class TestReduceSumWithNumelOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1275
        self.python_api = paddle.sum
1276
        self.public_python_api = paddle.sum
1277
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1278
        self.inputs = {'X': np.random.random((100, 1)).astype("float64")}
1279 1280
        self.attrs = {'dim': [1], 'keep_dim': False}
        self.outputs = {
1281 1282 1283
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=False
            )
1284
        }
1285
        self.enable_cinn = True
1286 1287 1288 1289 1290

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1291
        self.check_grad(['X'], 'Out', check_prim=False)
1292 1293 1294 1295 1296


class TestReduceAll(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1297
        self.python_api = paddle.sum
1298
        self.public_python_api = paddle.sum
1299
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1300
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1301 1302
        self.attrs = {'reduce_all': True, 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum()}
1303
        self.enable_cinn = True
1304 1305 1306 1307 1308

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1309 1310 1311 1312 1313 1314 1315
        self.check_grad(['X'], 'Out', check_prim=True)


class TestReduceAllFp32(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
        self.python_api = paddle.sum
1316
        self.public_python_api = paddle.sum
1317 1318 1319 1320
        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()}
1321
        self.enable_cinn = True
1322 1323 1324 1325 1326 1327

    def test_check_output(self):
        self.check_output()

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


1330 1331 1332
class Test1DReduceWithAxes1(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1333
        self.python_api = paddle.sum
1334
        self.public_python_api = paddle.sum
1335
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1336
        self.inputs = {'X': np.random.random(100).astype("float64")}
1337 1338
        self.attrs = {'dim': [0], 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
1339
        self.enable_cinn = True
1340 1341

    def test_check_output(self):
1342
        self.check_output()
1343 1344

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


1348
def reduce_sum_wrapper(x, axis=None, out_dtype=None, keepdim=False, name=None):
1349 1350 1351
    return paddle.sum(x, axis, "float64", keepdim, name)


1352 1353 1354
class TestReduceWithDtype(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1355
        self.python_api = reduce_sum_wrapper
1356
        self.public_python_api = reduce_sum_wrapper
1357
        self.prim_op_type = "prim"
1358 1359 1360
        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}
1361 1362 1363 1364 1365 1366
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1367 1368

    def test_check_output(self):
1369
        self.check_output()
1370 1371

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


1375 1376 1377
class TestReduceWithDtype1(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1378
        self.python_api = reduce_sum_wrapper
1379
        self.public_python_api = reduce_sum_wrapper
1380
        self.prim_op_type = "prim"
1381 1382 1383
        self.inputs = {'X': np.random.random((6, 2, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].sum(axis=1)}
        self.attrs = {'dim': [1]}
1384 1385 1386 1387 1388 1389
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1390
        # cinn op_mapper not support in_dtype/out_dtype attr
1391 1392 1393 1394 1395 1396 1397
        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)
1398 1399 1400 1401 1402


class TestReduceWithDtype2(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1403 1404
        self.prim_op_type = "prim"
        self.python_api = reduce_sum_wrapper
1405
        self.public_python_api = reduce_sum_wrapper
1406 1407 1408
        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}
1409 1410 1411 1412 1413 1414
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1415
        # cinn op_mapper not support in_dtype/out_dtype attr
1416 1417 1418 1419 1420 1421 1422
        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)
1423 1424


1425
class TestReduceSumOpError(unittest.TestCase):
1426
    def test_errors(self):
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        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)
1437 1438


1439
class API_TestSumOp(unittest.TestCase):
1440 1441 1442
    def run_static(
        self, shape, x_dtype, attr_axis, attr_dtype=None, np_axis=None
    ):
1443 1444
        if np_axis is None:
            np_axis = attr_axis
1445

1446 1447 1448 1449 1450
        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()):
1451
                data = paddle.static.data("data", shape=shape, dtype=x_dtype)
1452 1453 1454
                result_sum = paddle.sum(
                    x=data, axis=attr_axis, dtype=attr_dtype
                )
1455 1456 1457

                exe = fluid.Executor(place)
                input_data = np.random.rand(*shape).astype(x_dtype)
1458 1459 1460
                (res,) = exe.run(
                    feed={"data": input_data}, fetch_list=[result_sum]
                )
1461

1462 1463 1464 1465 1466
            np.testing.assert_allclose(
                res,
                np.sum(input_data.astype(attr_dtype), axis=np_axis),
                rtol=1e-05,
            )
1467

1468 1469 1470 1471
    def test_static(self):
        shape = [10, 10]
        axis = 1

1472 1473 1474
        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")
1475
        self.run_static(shape, "bool", axis, attr_dtype="float16")
1476

1477 1478 1479
        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")
1480
        self.run_static(shape, "int32", axis, attr_dtype="float64")
1481

1482 1483 1484 1485
        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")

1486 1487 1488
        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")
1489
        self.run_static(shape, "float32", axis, attr_dtype="int64")
1490 1491 1492 1493

        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")
1494 1495 1496

        shape = [5, 5, 5]
        self.run_static(shape, "int32", (0, 1), attr_dtype="int32")
1497 1498 1499
        self.run_static(
            shape, "int32", (), attr_dtype="int32", np_axis=(0, 1, 2)
        )
1500 1501 1502

    def test_dygraph(self):
        np_x = np.random.random([2, 3, 4]).astype('int32')
1503 1504
        with fluid.dygraph.guard():
            x = fluid.dygraph.to_variable(np_x)
1505 1506 1507 1508 1509 1510 1511 1512 1513
            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())
1514 1515


1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
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()):
1526
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1527 1528 1529 1530
            result = paddle.all(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1531 1532 1533 1534 1535
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1536
            np.testing.assert_allclose(fetches[0], np.all(input_np), rtol=1e-05)
1537 1538 1539 1540 1541 1542 1543 1544 1545

    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):
1546
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1547 1548
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582

                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()):
1583
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1584 1585 1586 1587
            result = paddle.any(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1588 1589 1590 1591 1592
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1593
            np.testing.assert_allclose(fetches[0], np.any(input_np), rtol=1e-05)
1594 1595 1596 1597 1598 1599 1600 1601 1602

    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):
1603
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1604 1605
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629

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


1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
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 已提交
1642
if __name__ == '__main__':
1643
    paddle.enable_static()
G
guosheng 已提交
1644
    unittest.main()