test_reduce_op.py 45.9 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 306 307 308 309 310 311
        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}
312
        self.attrs = {'dim': [-1], 'keep_dim': True}
313 314 315 316 317
        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}
318 319

    def test_check_output(self):
W
wanghuancoder 已提交
320
        self.check_output()
321 322 323 324 325 326 327 328 329 330

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

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    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

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

362

363 364
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
365 366
    " its gradient check is not supported by unittest framework."
)
367 368
class TestMinOp(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""
G
guosheng 已提交
369

370 371
    def setUp(self):
        self.op_type = "reduce_min"
372
        self.python_api = paddle.min
373
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
W
whs 已提交
374 375 376 377
        self.attrs = {'dim': [2]}
        self.outputs = {
            'Out': self.inputs['X'].min(axis=tuple(self.attrs['dim']))
        }
G
guosheng 已提交
378

379
    def test_check_output(self):
W
wanghuancoder 已提交
380
        self.check_output()
G
guosheng 已提交
381 382


383 384 385 386 387 388 389 390 391 392 393 394 395
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 已提交
396
        self.check_output()
397 398


399 400 401 402 403
class TestMin6DOp(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
404
        self.python_api = paddle.min
405 406 407 408 409 410 411 412 413
        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 已提交
414
        self.check_output()
415 416 417 418 419 420 421


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

    def setUp(self):
        self.op_type = "reduce_min"
422
        self.python_api = paddle.min
423 424 425 426 427 428 429 430 431
        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 已提交
432
        self.check_output()
433 434


435 436 437 438 439 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
@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 已提交
480 481 482 483
def raw_reduce_prod(x, dim=[0], keep_dim=False):
    return paddle.prod(x, dim, keep_dim)


484 485 486
class TestProdOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
487
        self.python_api = raw_reduce_prod
488 489 490
        self.public_python_api = raw_reduce_prod
        self.prim_op_type = "prim"

491 492
        self.init_data_type()
        self.inputs = {'X': np.random.random((5, 6, 10)).astype(self.data_type)}
493 494
        self.outputs = {'Out': self.inputs['X'].prod(axis=0)}

495
    def init_data_type(self):
496 497 498
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
499

500
    def test_check_output(self):
W
wanghuancoder 已提交
501
        self.check_output()
502 503

    def test_check_grad(self):
504 505 506 507 508 509
        self.check_grad(['X'], 'Out', check_prim=True)


class TestProdOpFp64(TestProdOp):
    def init_data_type(self):
        self.data_type = "float64"
510 511


512 513
class TestProdOp_ZeroDim(OpTest):
    def setUp(self):
514 515
        self.python_api = raw_reduce_prod
        self.public_python_api = raw_reduce_prod
516
        self.op_type = "reduce_prod"
517
        self.prim_op_type = "prim"
518 519 520 521
        self.inputs = {'X': np.random.random([]).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].prod()}
        self.attrs = {'dim': [], 'reduce_all': True}

522 523 524
        # 0-D tensor doesn't support in cinn
        self.enable_cinn = False

525
    def test_check_output(self):
W
wanghuancoder 已提交
526
        self.check_output()
527 528

    def test_check_grad(self):
W
wanghuancoder 已提交
529
        self.check_grad(['X'], 'Out')
530 531


532 533 534
class TestProd6DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
535
        self.python_api = raw_reduce_prod
536 537
        self.public_python_api = raw_reduce_prod
        self.prim_op_type = "prim"
538
        self.init_data_type()
539
        self.inputs = {
540
            'X': np.random.random((5, 6, 2, 3, 4, 2)).astype(self.data_type)
541 542 543 544 545 546
        }
        self.attrs = {'dim': [2, 3, 4]}
        self.outputs = {
            'Out': self.inputs['X'].prod(axis=tuple(self.attrs['dim']))
        }

547
    def init_data_type(self):
548 549 550
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
551

552
    def test_check_output(self):
W
wanghuancoder 已提交
553
        self.check_output()
554 555

    def test_check_grad(self):
556
        self.check_grad(['X'], 'Out', check_prim=True)
557 558 559 560 561


class TestProd8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_prod"
H
hong 已提交
562
        self.python_api = raw_reduce_prod
563
        self.public_python_api = raw_reduce_prod
564
        self.init_data_type()
565
        self.inputs = {
566 567 568
            'X': np.random.random((2, 5, 3, 2, 2, 3, 4, 2)).astype(
                self.data_type
            )
569 570 571 572 573 574
        }
        self.attrs = {'dim': [2, 3, 4]}
        self.outputs = {
            'Out': self.inputs['X'].prod(axis=tuple(self.attrs['dim']))
        }

575
    def init_data_type(self):
576 577 578
        self.data_type = (
            "float32" if core.is_compiled_with_rocm() else "float64"
        )
579

580
    def test_check_output(self):
W
wanghuancoder 已提交
581
        self.check_output()
582 583

    def test_check_grad(self):
W
wanghuancoder 已提交
584
        self.check_grad(['X'], 'Out')
585 586


Z
zhoukunsheng 已提交
587 588 589
class TestAllOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
590
        self.python_api = paddle.all
Z
zhoukunsheng 已提交
591 592 593 594 595
        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 已提交
596
        self.check_output()
Z
zhoukunsheng 已提交
597 598


599 600 601 602 603 604 605 606 607
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 已提交
608
        self.check_output()
609 610


611 612 613
class TestAll8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
614
        self.python_api = paddle.all
615
        self.inputs = {
616 617 618
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
619 620 621 622 623
        }
        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 已提交
624
        self.check_output()
625 626


Z
zhoukunsheng 已提交
627 628 629
class TestAllOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
630
        self.python_api = paddle.all
Z
zhoukunsheng 已提交
631
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
632
        self.attrs = {'dim': (1,)}
633 634 635
        self.outputs = {'Out': self.inputs['X'].all(axis=self.attrs['dim'])}

    def test_check_output(self):
W
wanghuancoder 已提交
636
        self.check_output()
637 638 639 640 641


class TestAll8DOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
642
        self.python_api = paddle.all
643
        self.inputs = {
644 645 646
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
647 648 649
        }
        self.attrs = {'dim': (1, 3, 4)}
        self.outputs = {'Out': self.inputs['X'].all(axis=self.attrs['dim'])}
Z
zhoukunsheng 已提交
650 651

    def test_check_output(self):
W
wanghuancoder 已提交
652
        self.check_output()
Z
zhoukunsheng 已提交
653 654 655 656 657


class TestAllOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
658
        self.python_api = paddle.all
Z
zhoukunsheng 已提交
659 660 661
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
        self.attrs = {'dim': [1], 'keep_dim': True}
        self.outputs = {
662
            'Out': np.expand_dims(self.inputs['X'].all(axis=1), axis=1)
Z
zhoukunsheng 已提交
663 664 665
        }

    def test_check_output(self):
W
wanghuancoder 已提交
666
        self.check_output()
Z
zhoukunsheng 已提交
667 668


669 670 671
class TestAll8DOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_all"
672
        self.python_api = paddle.all
673
        self.inputs = {
674 675 676
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
677
        }
678
        self.attrs = {'dim': (5,), 'keep_dim': True}
679
        self.outputs = {
680 681 682
            'Out': np.expand_dims(
                self.inputs['X'].all(axis=self.attrs['dim']), axis=5
            )
683 684 685
        }

    def test_check_output(self):
W
wanghuancoder 已提交
686
        self.check_output()
687 688


689 690 691 692 693
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
694
            self.assertRaises(TypeError, paddle.all, input1)
695
            # The input dtype of reduce_all_op must be bool.
G
GGBond8488 已提交
696 697
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
698
            )
699
            self.assertRaises(TypeError, paddle.all, input2)
700 701


Z
zhoukunsheng 已提交
702 703 704
class TestAnyOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
705
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
706 707 708 709 710
        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 已提交
711
        self.check_output()
Z
zhoukunsheng 已提交
712 713


714 715 716 717 718 719 720 721 722
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 已提交
723
        self.check_output()
724 725


726 727 728
class TestAny8DOp(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
729
        self.python_api = paddle.any
730
        self.inputs = {
731 732 733
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
734 735 736 737 738
        }
        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 已提交
739
        self.check_output()
740 741


Z
zhoukunsheng 已提交
742 743 744
class TestAnyOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
745
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
746 747 748 749 750
        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 已提交
751
        self.check_output()
Z
zhoukunsheng 已提交
752 753


754 755 756
class TestAny8DOpWithDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
757
        self.python_api = paddle.any
758
        self.inputs = {
759 760 761
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
762 763 764 765 766
        }
        self.attrs = {'dim': (3, 6)}
        self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}

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


Z
zhoukunsheng 已提交
770 771 772
class TestAnyOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
773
        self.python_api = paddle.any
Z
zhoukunsheng 已提交
774
        self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype("bool")}
775
        self.attrs = {'dim': (1,), 'keep_dim': True}
776
        self.outputs = {
777 778 779
            'Out': np.expand_dims(
                self.inputs['X'].any(axis=self.attrs['dim']), axis=1
            )
780 781 782
        }

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


class TestAny8DOpWithKeepDim(OpTest):
    def setUp(self):
        self.op_type = "reduce_any"
789
        self.python_api = paddle.any
790
        self.inputs = {
791 792 793
            'X': np.random.randint(0, 2, (2, 5, 3, 2, 2, 3, 4, 2)).astype(
                "bool"
            )
794
        }
795
        self.attrs = {'dim': (1,), 'keep_dim': True}
Z
zhoukunsheng 已提交
796
        self.outputs = {
797 798 799
            'Out': np.expand_dims(
                self.inputs['X'].any(axis=self.attrs['dim']), axis=1
            )
Z
zhoukunsheng 已提交
800 801 802
        }

    def test_check_output(self):
W
wanghuancoder 已提交
803
        self.check_output()
Z
zhoukunsheng 已提交
804 805


806 807 808 809 810
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
811
            self.assertRaises(TypeError, paddle.any, input1)
812
            # The input dtype of reduce_any_op must be bool.
G
GGBond8488 已提交
813 814
            input2 = paddle.static.data(
                name='input2', shape=[-1, 12, 10], dtype="int32"
815
            )
816
            self.assertRaises(TypeError, paddle.any, input2)
817 818


Q
qiaolongfei 已提交
819
class Test1DReduce(OpTest):
G
guosheng 已提交
820
    def setUp(self):
821
        self.op_type = "reduce_sum"
822
        self.python_api = paddle.sum
823
        self.public_python_api = paddle.sum
824
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
825
        self.inputs = {'X': np.random.random(120).astype("float64")}
Q
qiaolongfei 已提交
826
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
827
        self.enable_cinn = True
828 829 830

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

832
    def test_check_grad(self):
833
        self.check_grad(['X'], 'Out', check_prim=True)
G
guosheng 已提交
834 835


Q
qiaolongfei 已提交
836
class Test2DReduce0(Test1DReduce):
G
guosheng 已提交
837
    def setUp(self):
838
        self.op_type = "reduce_sum"
839
        self.python_api = paddle.sum
840
        self.public_python_api = paddle.sum
841
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
842 843
        self.attrs = {'dim': [0]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
844 845 846
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}


Q
qiaolongfei 已提交
847 848 849
class Test2DReduce1(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
850
        self.python_api = paddle.sum
851
        self.public_python_api = paddle.sum
852
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
853 854
        self.attrs = {'dim': [1]}
        self.inputs = {'X': np.random.random((20, 10)).astype("float64")}
Q
qiaolongfei 已提交
855 856 857 858 859 860 861 862
        self.outputs = {
            'Out': self.inputs['X'].sum(axis=tuple(self.attrs['dim']))
        }


class Test3DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
863
        self.python_api = paddle.sum
864
        self.public_python_api = paddle.sum
865
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
866 867 868 869 870 871 872 873 874 875
        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"
876
        self.python_api = paddle.sum
877
        self.public_python_api = paddle.sum
878
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
879 880 881 882 883 884 885 886 887 888
        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"
889
        self.python_api = paddle.sum
890
        self.public_python_api = paddle.sum
891
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
892 893 894 895 896 897 898 899 900 901
        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"
902
        self.python_api = paddle.sum
903
        self.public_python_api = paddle.sum
904
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
905 906 907 908 909
        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 已提交
910 911


W
wanghuancoder 已提交
912 913 914 915
def reduce_sum_wrapper2(x, axis=[0], dtype=None, keepdim=False):
    return paddle._C_ops.sum(x, axis, dtype, keepdim)


916 917 918
class Test8DReduce0(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
919
        self.python_api = reduce_sum_wrapper2
920 921 922 923 924 925 926 927
        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']))
        }

928 929 930 931 932 933
    def test_check_output(self):
        self.check_output()

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

934

Q
qiaolongfei 已提交
935 936 937
class TestKeepDimReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
938
        self.python_api = paddle.sum
939
        self.public_python_api = paddle.sum
940
        self.prim_op_type = "prim"
Q
qiaolongfei 已提交
941
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
Q
qiaolongfei 已提交
942
        self.attrs = {'dim': [1], 'keep_dim': True}
Q
qiaolongfei 已提交
943
        self.outputs = {
944 945 946
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
Q
qiaolongfei 已提交
947 948 949
        }


W
wanghuancoder 已提交
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
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')


966 967 968
class TestKeepDim8DReduce(Test1DReduce):
    def setUp(self):
        self.op_type = "reduce_sum"
W
wanghuancoder 已提交
969
        self.python_api = reduce_sum_wrapper2
970 971 972 973 974
        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 = {
975 976 977
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=self.attrs['keep_dim']
            )
978 979
        }

980 981 982 983 984 985
    def test_check_output(self):
        self.check_output()

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

986

987 988
@skip_check_grad_ci(
    reason="reduce_max is discontinuous non-derivable function,"
989 990
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
991 992 993 994 995
class TestReduceMaxOpMultiAxises(OpTest):
    """Remove Max with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_max"
996
        self.prim_op_type = "prim"
997
        self.python_api = paddle.max
998
        self.public_python_api = paddle.max
W
whs 已提交
999 1000 1001 1002 1003 1004 1005
        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 已提交
1006
        self.check_output()
W
whs 已提交
1007

1008 1009 1010 1011 1012 1013 1014 1015 1016
    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 已提交
1017

1018 1019
@skip_check_grad_ci(
    reason="reduce_min is discontinuous non-derivable function,"
1020 1021
    " its gradient check is not supported by unittest framework."
)
W
whs 已提交
1022 1023 1024 1025 1026
class TestReduceMinOpMultiAxises(OpTest):
    """Remove Min with subgradient from gradient check to confirm the success of CI."""

    def setUp(self):
        self.op_type = "reduce_min"
1027
        self.python_api = paddle.min
W
whs 已提交
1028 1029 1030 1031 1032 1033 1034
        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 已提交
1035
        self.check_output()
W
whs 已提交
1036 1037 1038 1039 1040


class TestKeepDimReduceSumMultiAxises(OpTest):
    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"
W
whs 已提交
1044 1045 1046
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.attrs = {'dim': [-2, -1], 'keep_dim': True}
        self.outputs = {
1047 1048 1049
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
W
whs 已提交
1050 1051 1052 1053 1054 1055
        }

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1056
        self.check_grad(['X'], 'Out', check_prim=True)
W
whs 已提交
1057 1058


W
wanghuancoder 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
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')


1078 1079 1080
class TestReduceSumWithDimOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1081
        self.python_api = paddle.sum
1082
        self.public_python_api = paddle.sum
1083
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1084
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1085 1086
        self.attrs = {'dim': [1, 2], 'keep_dim': True}
        self.outputs = {
1087 1088 1089
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=True
            )
1090
        }
1091
        self.enable_cinn = True
1092 1093 1094 1095 1096

    def test_check_output(self):
        self.check_output()

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


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


1120 1121 1122
class TestReduceSumWithNumelOne(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1123
        self.python_api = paddle.sum
1124
        self.public_python_api = paddle.sum
1125
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1126
        self.inputs = {'X': np.random.random((100, 1)).astype("float64")}
1127 1128
        self.attrs = {'dim': [1], 'keep_dim': False}
        self.outputs = {
1129 1130 1131
            'Out': self.inputs['X'].sum(
                axis=tuple(self.attrs['dim']), keepdims=False
            )
1132
        }
1133
        self.enable_cinn = True
1134 1135 1136 1137 1138

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1139
        self.check_grad(['X'], 'Out', check_prim=False)
1140 1141 1142 1143 1144


class TestReduceAll(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1145
        self.python_api = paddle.sum
1146
        self.public_python_api = paddle.sum
1147
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1148
        self.inputs = {'X': np.random.random((100, 1, 1)).astype("float64")}
1149 1150
        self.attrs = {'reduce_all': True, 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum()}
1151
        self.enable_cinn = True
1152 1153 1154 1155 1156

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
1157 1158 1159 1160 1161 1162 1163
        self.check_grad(['X'], 'Out', check_prim=True)


class TestReduceAllFp32(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
        self.python_api = paddle.sum
1164
        self.public_python_api = paddle.sum
1165 1166 1167 1168
        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()}
1169
        self.enable_cinn = True
1170 1171 1172 1173 1174 1175

    def test_check_output(self):
        self.check_output()

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


1178 1179 1180
class Test1DReduceWithAxes1(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1181
        self.python_api = paddle.sum
1182
        self.public_python_api = paddle.sum
1183
        self.prim_op_type = "prim"
Z
zhupengyang 已提交
1184
        self.inputs = {'X': np.random.random(100).astype("float64")}
1185 1186
        self.attrs = {'dim': [0], 'keep_dim': False}
        self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
1187
        self.enable_cinn = True
1188 1189

    def test_check_output(self):
1190
        self.check_output()
1191 1192

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


1196
def reduce_sum_wrapper(x, axis=None, out_dtype=None, keepdim=False, name=None):
1197 1198 1199
    return paddle.sum(x, axis, "float64", keepdim, name)


1200 1201 1202
class TestReduceWithDtype(OpTest):
    def setUp(self):
        self.op_type = "reduce_sum"
1203
        self.python_api = reduce_sum_wrapper
1204
        self.public_python_api = reduce_sum_wrapper
1205
        self.prim_op_type = "prim"
1206 1207 1208
        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}
1209 1210 1211 1212 1213 1214
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1215 1216

    def test_check_output(self):
1217
        self.check_output()
1218 1219

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


1223 1224 1225
class TestReduceWithDtype1(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1226
        self.python_api = reduce_sum_wrapper
1227
        self.public_python_api = reduce_sum_wrapper
1228
        self.prim_op_type = "prim"
1229 1230 1231
        self.inputs = {'X': np.random.random((6, 2, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].sum(axis=1)}
        self.attrs = {'dim': [1]}
1232 1233 1234 1235 1236 1237
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1238
        # cinn op_mapper not support in_dtype/out_dtype attr
1239 1240 1241 1242 1243 1244 1245
        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)
1246 1247 1248 1249 1250


class TestReduceWithDtype2(TestReduceWithDtype):
    def setUp(self):
        self.op_type = "reduce_sum"
1251 1252
        self.prim_op_type = "prim"
        self.python_api = reduce_sum_wrapper
1253
        self.public_python_api = reduce_sum_wrapper
1254 1255 1256
        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}
1257 1258 1259 1260 1261 1262
        self.attrs.update(
            {
                'in_dtype': int(convert_np_dtype_to_dtype_(np.float32)),
                'out_dtype': int(convert_np_dtype_to_dtype_(np.float64)),
            }
        )
1263
        # cinn op_mapper not support in_dtype/out_dtype attr
1264 1265 1266 1267 1268 1269 1270
        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)
1271 1272


1273
class TestReduceSumOpError(unittest.TestCase):
1274
    def test_errors(self):
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
        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)
1285 1286


1287
class API_TestSumOp(unittest.TestCase):
1288 1289 1290
    def run_static(
        self, shape, x_dtype, attr_axis, attr_dtype=None, np_axis=None
    ):
1291 1292
        if np_axis is None:
            np_axis = attr_axis
1293

1294 1295 1296 1297 1298
        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()):
1299
                data = paddle.static.data("data", shape=shape, dtype=x_dtype)
1300 1301 1302
                result_sum = paddle.sum(
                    x=data, axis=attr_axis, dtype=attr_dtype
                )
1303 1304 1305

                exe = fluid.Executor(place)
                input_data = np.random.rand(*shape).astype(x_dtype)
1306 1307 1308
                (res,) = exe.run(
                    feed={"data": input_data}, fetch_list=[result_sum]
                )
1309

1310 1311 1312 1313 1314
            np.testing.assert_allclose(
                res,
                np.sum(input_data.astype(attr_dtype), axis=np_axis),
                rtol=1e-05,
            )
1315

1316 1317 1318 1319
    def test_static(self):
        shape = [10, 10]
        axis = 1

1320 1321 1322
        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")
1323
        self.run_static(shape, "bool", axis, attr_dtype="float16")
1324

1325 1326 1327
        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")
1328
        self.run_static(shape, "int32", axis, attr_dtype="float64")
1329

1330 1331 1332 1333
        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")

1334 1335 1336
        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")
1337
        self.run_static(shape, "float32", axis, attr_dtype="int64")
1338 1339 1340 1341

        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")
1342 1343 1344

        shape = [5, 5, 5]
        self.run_static(shape, "int32", (0, 1), attr_dtype="int32")
1345 1346 1347
        self.run_static(
            shape, "int32", (), attr_dtype="int32", np_axis=(0, 1, 2)
        )
1348 1349 1350

    def test_dygraph(self):
        np_x = np.random.random([2, 3, 4]).astype('int32')
1351 1352
        with fluid.dygraph.guard():
            x = fluid.dygraph.to_variable(np_x)
1353 1354 1355 1356 1357 1358 1359 1360 1361
            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())
1362 1363


1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
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()):
1374
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1375 1376 1377 1378
            result = paddle.all(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1379 1380 1381 1382 1383
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1384
            np.testing.assert_allclose(fetches[0], np.all(input_np), rtol=1e-05)
1385 1386 1387 1388 1389 1390 1391 1392 1393

    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):
1394
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1395 1396
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430

                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()):
1431
            input = paddle.static.data(name="input", shape=[4, 4], dtype="bool")
1432 1433 1434 1435
            result = paddle.any(x=input)
            input_np = np.random.randint(0, 2, [4, 4]).astype("bool")

            exe = fluid.Executor(place)
1436 1437 1438 1439 1440
            fetches = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[result],
            )
1441
            np.testing.assert_allclose(fetches[0], np.any(input_np), rtol=1e-05)
1442 1443 1444 1445 1446 1447 1448 1449 1450

    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):
1451
                np_x = np.random.randint(0, 2, (12, 10)).astype(np.bool_)
1452 1453
                x = paddle.assign(np_x)
                x = paddle.cast(x, 'bool')
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477

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


1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
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 已提交
1490
if __name__ == '__main__':
1491
    paddle.enable_static()
G
guosheng 已提交
1492
    unittest.main()