test_reduce_op.py 51.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.if_enable_cinn()
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

50 51 52
    def if_enable_cinn(self):
        pass

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

    def test_check_output(self):
W
wanghuancoder 已提交
57
        self.check_output()
58 59

    def test_check_grad(self):
W
Wilber 已提交
60
        self.check_grad(['X'], 'Out', check_prim=True)
61 62


63 64 65 66 67 68 69 70 71 72 73 74 75 76
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 已提交
77 78
class TestSumOp_ZeroDim(TestSumOp):
    def init_attrs(self):
79
        self.attrs = {'dim': []}
80

W
Wilber 已提交
81 82 83 84 85
    def init_input(self):
        self.x = np.random.random([]).astype(self.dtype)

    def calc_output(self):
        self.out = self.x.sum(axis=None)
86 87

    def test_check_grad(self):
W
wanghuancoder 已提交
88
        self.check_grad(['X'], 'Out')
89 90


W
Wilber 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104
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]}
105

W
Wilber 已提交
106 107 108 109 110 111 112

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)}
113 114

    def test_check_output(self):
W
Wilber 已提交
115
        self.check_output()
116 117

    def test_check_grad(self):
W
Wilber 已提交
118
        self.check_grad(['X'], 'Out')
119 120


W
Wilber 已提交
121 122 123 124 125
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)
126

W
Wilber 已提交
127 128
    def init_attrs(self):
        self.attrs = {'dim': (0, 1)}
129 130

    def test_check_output(self):
W
wanghuancoder 已提交
131
        self.check_output()
132 133 134 135

    def calc_gradient(self):
        x = self.inputs["X"]
        grad = np.ones(x.shape, dtype=x.dtype)
136
        return (grad,)
137 138

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


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

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

154
    def test_check_output(self):
W
wanghuancoder 已提交
155
        self.check_output()
G
guosheng 已提交
156

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

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


W
Wilber 已提交
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 236 237 238
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)
239 240


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

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

    def test_check_output(self):
W
wanghuancoder 已提交
260
        self.check_output()
G
guosheng 已提交
261

262 263 264 265 266 267 268 269 270
    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 已提交
271

272 273 274 275 276
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"
277
        self.prim_op_type = "prim"
278
        self.python_api = paddle.max
279 280
        self.public_python_api = paddle.max
        self.enable_cinn = False
281 282 283 284 285 286 287
        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 已提交
288
        self.check_output()
289

290 291 292 293 294 295 296 297 298 299
    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,
        )


300
class TestMaxFP32Op(OpTest):
301 302 303 304 305 306 307
    """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
308
        self.init_dtype()
309
        self.if_enable_cinn()
310 311 312 313 314 315
        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}
316
        self.attrs = {'dim': [-1], 'keep_dim': True}
317 318 319 320 321
        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}
322

323 324 325
    def if_enable_cinn(self):
        pass

326
    def test_check_output(self):
W
wanghuancoder 已提交
327
        self.check_output()
328 329 330 331 332 333 334 335 336 337

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

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    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

356 357 358
    def if_enable_cinn(self):
        self.enable_cinn = False

359 360 361 362 363 364 365 366 367 368 369 370 371
    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,
        )

372

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

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

389
    def test_check_output(self):
W
wanghuancoder 已提交
390
        self.check_output()
G
guosheng 已提交
391 392


393 394 395 396 397 398 399 400 401 402 403 404 405
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 已提交
406
        self.check_output()
407 408


409 410 411 412 413
class TestMin6DOp(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
414
        self.python_api = paddle.min
415 416 417 418 419 420 421 422 423
        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 已提交
424
        self.check_output()
425 426 427 428 429 430 431


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

    def setUp(self):
        self.op_type = "reduce_min"
432
        self.python_api = paddle.min
433 434 435 436 437 438 439 440 441
        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 已提交
442
        self.check_output()
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 487 488 489
@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 已提交
490 491 492 493
def raw_reduce_prod(x, dim=[0], keep_dim=False):
    return paddle.prod(x, dim, keep_dim)


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

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

508
    def init_data_type(self):
509 510 511
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
512

513 514 515
    def if_enable_cinn(self):
        pass

516
    def test_check_output(self):
W
wanghuancoder 已提交
517
        self.check_output()
518 519

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


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 563 564 565
@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
        )


566 567 568
class TestProdOpFp64(TestProdOp):
    def init_data_type(self):
        self.data_type = "float64"
569 570


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

581 582 583
        # 0-D tensor doesn't support in cinn
        self.enable_cinn = False

584 585 586 587 588
    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}

589
    def test_check_output(self):
W
wanghuancoder 已提交
590
        self.check_output()
591 592

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


596 597 598
class TestProd6DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
599
        self.python_api = raw_reduce_prod
600 601
        self.public_python_api = raw_reduce_prod
        self.prim_op_type = "prim"
602
        self.init_data_type()
603 604 605 606 607 608 609 610 611
        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):
612
        self.inputs = {
613
            'X': np.random.random((5, 6, 2, 3, 4, 2)).astype(self.data_type)
614 615 616 617 618 619
        }
        self.attrs = {'dim': [2, 3, 4]}
        self.outputs = {
            'Out': self.inputs['X'].prod(axis=tuple(self.attrs['dim']))
        }

620 621
    def if_enable_cinn(self):
        pass
622

623
    def test_check_output(self):
W
wanghuancoder 已提交
624
        self.check_output()
625 626

    def test_check_grad(self):
627
        self.check_grad(['X'], 'Out', check_prim=True)
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 671 672 673
@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
        )


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

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

693
    def init_data_type(self):
694 695 696
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
697

698
    def test_check_output(self):
W
wanghuancoder 已提交
699
        self.check_output()
700 701

    def test_check_grad(self):
W
wanghuancoder 已提交
702
        self.check_grad(['X'], 'Out')
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 739 740 741
@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')


742 743 744 745
def reduce_all_wrapper(x, axis=None, keepdim=False, reduce_all=True, name=None):
    return paddle.all(x, axis, keepdim, name)


Z
zhoukunsheng 已提交
746 747 748
class TestAllOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
749
        self.python_api = reduce_all_wrapper
Z
zhoukunsheng 已提交
750 751 752 753 754
        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 已提交
755
        self.check_output()
Z
zhoukunsheng 已提交
756 757


758 759 760 761 762 763
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()}
764
        self.attrs = {'dim': []}
765 766

    def test_check_output(self):
W
wanghuancoder 已提交
767
        self.check_output()
768 769


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

    def test_check_output(self):
W
wanghuancoder 已提交
783
        self.check_output()
784 785


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

    def test_check_output(self):
W
wanghuancoder 已提交
795
        self.check_output()
796 797 798 799 800


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

    def test_check_output(self):
W
wanghuancoder 已提交
811
        self.check_output()
Z
zhoukunsheng 已提交
812 813 814 815 816


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

    def test_check_output(self):
W
wanghuancoder 已提交
825
        self.check_output()
Z
zhoukunsheng 已提交
826 827


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

    def test_check_output(self):
W
wanghuancoder 已提交
845
        self.check_output()
846 847


848 849 850 851 852
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
853
            self.assertRaises(TypeError, paddle.all, input1)
854
            # The input dtype of reduce_all_op must be bool.
G
GGBond8488 已提交
855 856
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
857
            )
858
            self.assertRaises(TypeError, paddle.all, input2)
859 860


861 862 863 864
def reduce_any_wrapper(x, axis=None, keepdim=False, reduce_all=True, name=None):
    return paddle.any(x, axis, keepdim, name)


Z
zhoukunsheng 已提交
865 866 867
class TestAnyOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
868
        self.python_api = reduce_any_wrapper
Z
zhoukunsheng 已提交
869 870 871 872 873
        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 已提交
874
        self.check_output()
Z
zhoukunsheng 已提交
875 876


877 878 879 880 881 882
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()}
883
        self.attrs = {'dim': []}
884 885

    def test_check_output(self):
W
wanghuancoder 已提交
886
        self.check_output()
887 888


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

    def test_check_output(self):
W
wanghuancoder 已提交
902
        self.check_output()
903 904


Z
zhoukunsheng 已提交
905 906 907
class TestAnyOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
908
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
909 910 911 912 913
        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 已提交
914
        self.check_output()
Z
zhoukunsheng 已提交
915 916


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

    def test_check_output(self):
W
wanghuancoder 已提交
930
        self.check_output()
931 932


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

    def test_check_output(self):
W
wanghuancoder 已提交
946
        self.check_output()
947 948 949 950 951


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

    def test_check_output(self):
W
wanghuancoder 已提交
966
        self.check_output()
Z
zhoukunsheng 已提交
967 968


969 970 971 972 973
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
974
            self.assertRaises(TypeError, paddle.any, input1)
975
            # The input dtype of reduce_any_op must be bool.
G
GGBond8488 已提交
976 977
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
978
            )
979
            self.assertRaises(TypeError, paddle.any, input2)
980 981


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

    def if_enable_cinn(self):
        pass
994 995 996

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

998
    def test_check_grad(self):
999
        self.check_grad(['X'], 'Out', check_prim=True)
G
guosheng 已提交
1000 1001


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


Q
qiaolongfei 已提交
1014 1015 1016
class Test2DReduce1(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1017
        self.python_api = paddle.sum
1018
        self.public_python_api = paddle.sum
1019
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1020 1021
        self.attrs = {'dim': [1]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
Q
qiaolongfei 已提交
1022 1023 1024
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }
1025
        self.if_enable_cinn()
Q
qiaolongfei 已提交
1026 1027 1028 1029 1030


class Test3DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1031
        self.python_api = paddle.sum
1032
        self.public_python_api = paddle.sum
1033
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1034 1035 1036 1037 1038
        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']))
        }
1039
        self.if_enable_cinn()
Q
qiaolongfei 已提交
1040 1041 1042 1043 1044


class Test3DReduce1(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1045
        self.python_api = paddle.sum
1046
        self.public_python_api = paddle.sum
1047
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1048 1049 1050 1051 1052
        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']))
        }
1053
        self.if_enable_cinn()
Q
qiaolongfei 已提交
1054 1055 1056 1057 1058


class Test3DReduce2(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1059
        self.python_api = paddle.sum
1060
        self.public_python_api = paddle.sum
1061
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1062 1063 1064 1065 1066
        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']))
        }
1067
        self.if_enable_cinn()
Q
qiaolongfei 已提交
1068 1069 1070 1071 1072


class Test3DReduce3(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1073
        self.python_api = paddle.sum
1074
        self.public_python_api = paddle.sum
1075
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1076 1077 1078 1079 1080
        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']))
        }
1081
        self.if_enable_cinn()
G
guosheng 已提交
1082 1083


W
wanghuancoder 已提交
1084 1085 1086 1087
def reduce_sum_wrapper2(x, axis=[0], dtype=None, keepdim=False):
    return paddle._C_ops.sum(x, axis, dtype, keepdim)


1088 1089 1090
class Test8DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
1091
        self.python_api = reduce_sum_wrapper2
1092 1093 1094 1095 1096 1097 1098 1099
        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']))
        }

1100 1101 1102 1103 1104 1105
    def test_check_output(self):
        self.check_output()

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

1106

Q
qiaolongfei 已提交
1107 1108 1109
class TestKeepDimReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
1110
        self.python_api = paddle.sum
1111
        self.public_python_api = paddle.sum
1112
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
1113
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
Q
qiaolongfei 已提交
1114
        self.attrs = {'dim': [1], 'keep_dim': True}
Q
qiaolongfei 已提交
1115
        self.outputs = {
1116 1117 1118
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
Q
qiaolongfei 已提交
1119
        }
1120
        self.if_enable_cinn()
Q
qiaolongfei 已提交
1121 1122


W
wanghuancoder 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
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')


1139 1140 1141
class TestKeepDim8DReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
1142
        self.python_api = reduce_sum_wrapper2
1143 1144 1145 1146 1147
        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 = {
1148 1149 1150
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
1151 1152
        }

1153 1154 1155 1156 1157 1158
    def test_check_output(self):
        self.check_output()

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

1159

1160 1161
@skip_check_grad_ci(
    reason="reduce_max is discontinuous non-derivable function,"
1162 1163
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1164 1165 1166 1167 1168
class TestReduceMaxOpMultiAxises(OpTest):
    """Remove Max with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_max"
1169
        self.prim_op_type = "prim"
1170
        self.python_api = paddle.max
1171
        self.public_python_api = paddle.max
W
whs 已提交
1172 1173 1174 1175 1176 1177 1178
        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 已提交
1179
        self.check_output()
W
whs 已提交
1180

1181 1182 1183 1184 1185 1186 1187 1188 1189
    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 已提交
1190

1191 1192
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
1193 1194
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1195 1196 1197 1198 1199
class TestReduceMinOpMultiAxises(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
1200
        self.python_api = paddle.min
W
whs 已提交
1201 1202 1203 1204 1205 1206 1207
        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 已提交
1208
        self.check_output()
W
whs 已提交
1209 1210 1211 1212 1213


class TestKeepDimReduceSumMultiAxises(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1214
        self.python_api = paddle.sum
1215
        self.public_python_api = paddle.sum
1216
        self.prim_op_type = "prim"
W
whs 已提交
1217 1218 1219
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [-2, -1], 'keep_dim': True}
        self.outputs = {
1220 1221 1222
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
W
whs 已提交
1223
        }
1224 1225 1226 1227
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
W
whs 已提交
1228 1229 1230 1231 1232

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1233
        self.check_grad(['X'], 'Out', check_prim=True)
W
whs 已提交
1234 1235


W
wanghuancoder 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
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')


1255 1256 1257
class TestReduceSumWithDimOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1258
        self.python_api = paddle.sum
1259
        self.public_python_api = paddle.sum
1260
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1261
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1262 1263
        self.attrs = {'dim': [1, 2], 'keep_dim': True}
        self.outputs = {
1264 1265 1266
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
1267
        }
1268 1269 1270 1271
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
1272 1273 1274 1275 1276

    def test_check_output(self):
        self.check_output()

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


W
wanghuancoder 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
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')


1300 1301 1302
class TestReduceSumWithNumelOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1303
        self.python_api = paddle.sum
1304
        self.public_python_api = paddle.sum
1305
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1306
        self.inputs = {'X': np.random.random((100, 1)).astype("float64")}
1307 1308
        self.attrs = {'dim': [1], 'keep_dim': False}
        self.outputs = {
1309 1310 1311
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=False
            )
1312
        }
1313 1314 1315 1316
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
1317 1318 1319 1320 1321

    def test_check_output(self):
        self.check_output()

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


1325 1326 1327 1328 1329 1330
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)


1331 1332 1333
class TestReduceAll(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1334 1335
        self.python_api = reduce_sum_wrapper
        self.public_python_api = reduce_sum_wrapper
1336
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1337
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1338 1339
        self.attrs = {'reduce_all': True, 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum()}
1340 1341 1342 1343
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
1344 1345 1346 1347 1348

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1349 1350 1351 1352 1353 1354
        self.check_grad(['X'], 'Out', check_prim=True)


class TestReduceAllFp32(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1355 1356
        self.python_api = reduce_sum_wrapper
        self.public_python_api = reduce_sum_wrapper
1357 1358 1359 1360
        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()}
1361 1362 1363 1364
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
1365 1366 1367 1368 1369 1370

    def test_check_output(self):
        self.check_output()

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


1373 1374 1375
class Test1DReduceWithAxes1(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1376
        self.python_api = paddle.sum
1377
        self.public_python_api = paddle.sum
1378
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1379
        self.inputs = {'X': np.random.random(100).astype("float64")}
1380 1381
        self.attrs = {'dim': [0], 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
1382 1383 1384 1385
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
1386 1387

    def test_check_output(self):
1388
        self.check_output()
1389 1390

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


1394 1395 1396 1397
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)
1398 1399


1400 1401 1402
class TestReduceWithDtype(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1403 1404
        self.python_api = reduce_sum_wrapper_fp64
        self.public_python_api = reduce_sum_wrapper_fp64
1405
        self.prim_op_type = "prim"
1406 1407 1408
        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}
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 1416 1417 1418
        self.if_enable_cinn()

    def if_enable_cinn(self):
        pass
1419 1420

    def test_check_output(self):
1421
        self.check_output()
1422 1423

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


1427 1428 1429
class TestReduceWithDtype1(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1430 1431
        self.python_api = paddle.sum
        self.public_python_api = paddle.sum
1432
        self.prim_op_type = "prim"
1433 1434 1435
        self.inputs = {'X': np.random.random((6, 2, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].sum(axis=1)}
        self.attrs = {'dim': [1]}
1436 1437 1438 1439 1440 1441
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1442
        # cinn op_mapper not support in_dtype/out_dtype attr
1443 1444 1445 1446 1447 1448 1449
        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)
1450 1451 1452 1453 1454


class TestReduceWithDtype2(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1455
        self.prim_op_type = "prim"
1456 1457
        self.python_api = paddle.sum
        self.public_python_api = paddle.sum
1458 1459 1460
        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}
1461 1462 1463 1464 1465 1466
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1467
        # cinn op_mapper not support in_dtype/out_dtype attr
1468 1469 1470 1471 1472 1473 1474
        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)
1475 1476


1477
class TestReduceSumOpError(unittest.TestCase):
1478
    def test_errors(self):
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
        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)
1489 1490


1491
class API_TestSumOp(unittest.TestCase):
1492 1493 1494
    def run_static(
        self, shape, x_dtype, attr_axis, attr_dtype=None, np_axis=None
    ):
1495 1496
        if np_axis is None:
            np_axis = attr_axis
1497

1498 1499 1500 1501 1502
        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()):
1503
                data = paddle.static.data("data", shape=shape, dtype=x_dtype)
1504 1505 1506
                result_sum = paddle.sum(
                    x=data, axis=attr_axis, dtype=attr_dtype
                )
1507 1508 1509

                exe = fluid.Executor(place)
                input_data = np.random.rand(*shape).astype(x_dtype)
1510 1511 1512
                (res,) = exe.run(
                    feed={"data": input_data}, fetch_list=[result_sum]
                )
1513

1514 1515 1516 1517 1518
            np.testing.assert_allclose(
                res,
                np.sum(input_data.astype(attr_dtype), axis=np_axis),
                rtol=1e-05,
            )
1519

1520 1521 1522 1523
    def test_static(self):
        shape = [10, 10]
        axis = 1

1524 1525 1526
        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")
1527
        self.run_static(shape, "bool", axis, attr_dtype="float16")
1528

1529 1530 1531
        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")
1532
        self.run_static(shape, "int32", axis, attr_dtype="float64")
1533

1534 1535 1536 1537
        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")

1538 1539 1540
        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")
1541
        self.run_static(shape, "float32", axis, attr_dtype="int64")
1542 1543 1544 1545

        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")
1546 1547 1548

        shape = [5, 5, 5]
        self.run_static(shape, "int32", (0, 1), attr_dtype="int32")
1549 1550 1551
        self.run_static(
            shape, "int32", (), attr_dtype="int32", np_axis=(0, 1, 2)
        )
1552 1553 1554

    def test_dygraph(self):
        np_x = np.random.random([2, 3, 4]).astype('int32')
1555 1556
        with fluid.dygraph.guard():
            x = fluid.dygraph.to_variable(np_x)
1557 1558 1559 1560 1561 1562 1563 1564 1565
            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())
1566 1567


1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
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()):
1578
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1579 1580 1581 1582
            result = paddle.all(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1583 1584 1585 1586 1587
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1588
            np.testing.assert_allclose(fetches[0], np.all(input_np), rtol=1e-05)
1589 1590 1591 1592 1593 1594 1595 1596 1597

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

                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()):
1635
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1636 1637 1638 1639
            result = paddle.any(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1640 1641 1642 1643 1644
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1645
            np.testing.assert_allclose(fetches[0], np.any(input_np), rtol=1e-05)
1646 1647 1648 1649 1650 1651 1652 1653 1654

    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):
1655
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1656 1657
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681

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


1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
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 已提交
1694
if __name__ == '__main__':
1695
    paddle.enable_static()
G
guosheng 已提交
1696
    unittest.main()