test_sum_op.py 24.8 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.

15 16
import os
import tempfile
17 18 19
import unittest

import gradient_checker
20
import numpy as np
21
from decorator_helper import prog_scope
22
from op_test import OpTest
23

24 25
import paddle
import paddle.fluid as fluid
T
tangwei12 已提交
26
import paddle.fluid.core as core
27 28 29 30
import paddle.fluid.layers as layers
import paddle.inference as paddle_infer
from paddle import enable_static
from paddle.fluid.framework import _test_eager_guard
T
tangwei12 已提交
31
from paddle.fluid.op import Operator
32 33 34 35 36
from paddle.fluid.tests.unittests.op_test import (
    OpTest,
    convert_float_to_uint16,
    convert_uint16_to_float,
)
37 38 39 40 41


class TestSumOp(OpTest):
    def setUp(self):
        self.op_type = "sum"
C
chengduo 已提交
42
        self.init_kernel_type()
43 44
        self.use_mkldnn = False
        self.init_kernel_type()
Z
zhupengyang 已提交
45 46 47
        x0 = np.random.random((3, 40)).astype(self.dtype)
        x1 = np.random.random((3, 40)).astype(self.dtype)
        x2 = np.random.random((3, 40)).astype(self.dtype)
48
        self.inputs = {"X": [("x0", x0), ("x1", x1), ("x2", x2)]}
49 50
        y = x0 + x1 + x2
        self.outputs = {'Out': y}
51
        self.attrs = {'use_mkldnn': self.use_mkldnn}
52

C
chengduo 已提交
53
    def init_kernel_type(self):
54
        self.dtype = np.float64
C
chengduo 已提交
55

56
    def test_check_output(self):
Q
qijun 已提交
57
        self.check_output()
58 59

    def test_check_grad(self):
Q
qijun 已提交
60
        self.check_grad(['x0'], 'Out')
61 62


63
class TestSelectedRowsSumOp(unittest.TestCase):
C
chengduo 已提交
64
    def setUp(self):
Q
qiaolongfei 已提交
65 66 67
        self.height = 10
        self.row_numel = 12
        self.rows = [0, 1, 2, 3, 4, 5, 6]
68
        self.dtype = np.float64
C
chengduo 已提交
69
        self.init_kernel_type()
Q
qiaolongfei 已提交
70

C
chengduo 已提交
71
    def check_with_place(self, place, inplace):
72 73 74 75 76 77 78 79 80 81 82 83
        self.check_input_and_optput(
            core.Scope(), place, inplace, True, True, True
        )
        self.check_input_and_optput(
            core.Scope(), place, inplace, False, True, True
        )
        self.check_input_and_optput(
            core.Scope(), place, inplace, False, False, True
        )
        self.check_input_and_optput(
            core.Scope(), place, inplace, False, False, False
        )
T
tangwei12 已提交
84

C
chengduo 已提交
85
    def init_kernel_type(self):
C
chengduo 已提交
86
        pass
C
chengduo 已提交
87

C
chengduo 已提交
88 89 90 91
    def _get_array(self, rows, row_numel):
        array = np.ones((len(rows), row_numel)).astype(self.dtype)
        for i in range(len(rows)):
            array[i] *= rows[i]
Q
qiaolongfei 已提交
92 93
        return array

94 95 96 97 98 99 100 101 102
    def check_input_and_optput(
        self,
        scope,
        place,
        inplace,
        w1_has_data=False,
        w2_has_data=False,
        w3_has_data=False,
    ):
T
tangwei12 已提交
103 104 105 106

        self.create_selected_rows(scope, place, "W1", w1_has_data)
        self.create_selected_rows(scope, place, "W2", w2_has_data)
        self.create_selected_rows(scope, place, "W3", w3_has_data)
T
tangwei12 已提交
107 108

        # create Out Variable
Q
Qiao Longfei 已提交
109 110 111 112 113
        if inplace:
            out_var_name = "W1"
        else:
            out_var_name = "Out"
        out = scope.var(out_var_name).get_selected_rows()
T
tangwei12 已提交
114 115

        # create and run sum operator
Q
Qiao Longfei 已提交
116
        sum_op = Operator("sum", X=["W1", "W2", "W3"], Out=out_var_name)
T
tangwei12 已提交
117 118
        sum_op.run(scope, place)

T
tangwei12 已提交
119
        has_data_w_num = 0
Q
qiaolongfei 已提交
120 121
        for has_data in [w1_has_data, w2_has_data, w3_has_data]:
            if has_data:
T
tangwei12 已提交
122
                has_data_w_num += 1
T
tangwei12 已提交
123

Q
qiaolongfei 已提交
124 125
        if has_data_w_num > 0:
            self.assertEqual(len(out.rows()), 7)
126 127
            np.testing.assert_array_equal(
                np.array(out.get_tensor()),
128 129
                self._get_array(self.rows, self.row_numel) * has_data_w_num,
            )
Q
qiaolongfei 已提交
130 131
        else:
            self.assertEqual(len(out.rows()), 0)
T
tangwei12 已提交
132

Q
qiaolongfei 已提交
133
    def create_selected_rows(self, scope, place, var_name, has_data):
T
tangwei12 已提交
134
        # create and initialize W Variable
Q
qiaolongfei 已提交
135 136
        if has_data:
            rows = self.rows
T
tangwei12 已提交
137 138 139 140 141
        else:
            rows = []

        var = scope.var(var_name)
        w_selected_rows = var.get_selected_rows()
Q
qiaolongfei 已提交
142
        w_selected_rows.set_height(self.height)
T
tangwei12 已提交
143
        w_selected_rows.set_rows(rows)
C
chengduo 已提交
144
        w_array = self._get_array(self.rows, self.row_numel)
T
tangwei12 已提交
145 146 147 148 149 150 151
        w_tensor = w_selected_rows.get_tensor()
        w_tensor.set(w_array, place)

        return var

    def test_w_is_selected_rows(self):
        places = [core.CPUPlace()]
Q
Qiao Longfei 已提交
152 153
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))
T
tangwei12 已提交
154
        for place in places:
Q
Qiao Longfei 已提交
155 156
            for inplace in [True, False]:
                self.check_with_place(place, inplace)
T
tangwei12 已提交
157 158


159 160 161 162 163
class TestSelectedRowsSumOpInt(TestSelectedRowsSumOp):
    def init_kernel_type(self):
        self.dtype = np.int32


164 165 166
@unittest.skipIf(
    not core.supports_bfloat16(), 'place does not support BF16 evaluation'
)
167 168 169 170 171 172 173 174
class TestSelectedRowsSumBF16Op(TestSelectedRowsSumOp):
    def setUp(self):
        self.height = 10
        self.row_numel = 12
        self.rows = [0, 1, 2, 3, 4, 5, 6]
        self.dtype = np.uint16
        self.init_kernel_type()
        np.random.seed(12345)
175 176 177
        self.data = np.random.random((len(self.rows), self.row_numel)).astype(
            np.float32
        )
178 179 180 181 182 183 184

    def _get_array(self, rows, row_numel):
        if len(rows) > 0:
            return convert_float_to_uint16(self.data)
        else:
            return np.ndarray((0, row_numel), dtype=self.dtype)

185 186 187 188 189 190 191 192 193
    def check_input_and_optput(
        self,
        scope,
        place,
        inplace,
        w1_has_data=False,
        w2_has_data=False,
        w3_has_data=False,
    ):
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

        self.create_selected_rows(scope, place, "W1", w1_has_data)
        self.create_selected_rows(scope, place, "W2", w2_has_data)
        self.create_selected_rows(scope, place, "W3", w3_has_data)

        # create Out Variable
        if inplace:
            out_var_name = "W1"
        else:
            out_var_name = "Out"
        out = scope.var(out_var_name).get_selected_rows()

        # create and run sum operator
        sum_op = Operator("sum", X=["W1", "W2", "W3"], Out=out_var_name)
        sum_op.run(scope, place)

        has_data_w_num = 0
        for has_data in [w1_has_data, w2_has_data, w3_has_data]:
            if has_data:
                has_data_w_num += 1

        if has_data_w_num > 0:
            self.assertEqual(len(out.rows()), 7)
            out_bf16 = np.array(out.get_tensor())
            out_fp32 = convert_uint16_to_float(out_bf16)
219 220 221 222 223 224
            ref_fp32 = (
                convert_uint16_to_float(
                    self._get_array(self.rows, self.row_numel)
                )
                * has_data_w_num
            )
225 226 227 228 229 230 231 232 233
            np.testing.assert_allclose(out_fp32, ref_fp32, atol=0, rtol=0.95e-2)
        else:
            self.assertEqual(len(out.rows()), 0)

    def test_w_is_selected_rows(self):
        for inplace in [True, False]:
            self.check_with_place(core.CPUPlace(), inplace)


L
lidanqing 已提交
234 235 236 237 238
class TestSelectedRowsSumBF16OpBigRow(TestSelectedRowsSumBF16Op):
    def init_kernel_type(self):
        self.row_numel = 102


C
chengduo 已提交
239 240 241 242 243
class TestLoDTensorAndSelectedRowsOp(TestSelectedRowsSumOp):
    def setUp(self):
        self.height = 10
        self.row_numel = 12
        self.rows = [0, 1, 2, 2, 4, 5, 6]
244
        self.dtype = np.float64
C
chengduo 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

    def check_with_place(self, place, inplace):
        scope = core.Scope()
        if inplace:
            self.create_lod_tensor(scope, place, "x1")
            self.create_selected_rows(scope, place, "x2", True)
            out = scope.var("x1").get_tensor()
            out_name = "x1"
        else:
            self.create_selected_rows(scope, place, "x1", True)
            self.create_lod_tensor(scope, place, "x2")
            out = scope.var("out").get_tensor()
            out_name = "out"

        # create and run sum operator
        sum_op = Operator("sum", X=["x1", "x2"], Out=out_name)
        sum_op.run(scope, place)

        result = np.ones((1, self.height)).astype(np.int32).tolist()[0]
        for ele in self.rows:
            result[ele] += 1

        out_t = np.array(out)
        self.assertEqual(out_t.shape[0], self.height)
269 270
        np.testing.assert_array_equal(
            out_t,
271 272 273
            self._get_array([i for i in range(self.height)], self.row_numel)
            * np.tile(np.array(result).reshape(self.height, 1), self.row_numel),
        )
C
chengduo 已提交
274 275 276 277

    def create_lod_tensor(self, scope, place, var_name):
        var = scope.var(var_name)
        w_tensor = var.get_tensor()
278 279 280
        w_array = self._get_array(
            [i for i in range(self.height)], self.row_numel
        )
C
chengduo 已提交
281 282 283 284
        w_tensor.set(w_array, place)
        return var


285 286 287 288
# ----------- test fp16 -----------
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
C
chengduo 已提交
289 290 291 292 293
class TestFP16SumOp(TestSumOp):
    def init_kernel_type(self):
        self.dtype = np.float16

    def test_check_output(self):
C
chengduo 已提交
294 295 296
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
            self.check_output_with_place(place, atol=2e-2)
C
chengduo 已提交
297 298 299 300

    # FIXME: Because of the precision fp16, max_relative_error
    # should be 0.15 here.
    def test_check_grad(self):
C
chengduo 已提交
301 302 303
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
            self.check_grad(['x0'], 'Out', max_relative_error=0.15)
C
chengduo 已提交
304 305


C
chengduo 已提交
306
def create_test_sum_fp16_class(parent):
307 308 309
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
C
chengduo 已提交
310 311 312
    class TestSumFp16Case(parent):
        def init_kernel_type(self):
            self.dtype = np.float16
C
chengduo 已提交
313

C
chengduo 已提交
314
        def test_w_is_selected_rows(self):
C
chengduo 已提交
315 316 317 318 319
            place = core.CUDAPlace(0)
            if core.is_float16_supported(place):
                for inplace in [True, False]:
                    self.check_with_place(place, inplace)

C
chengduo 已提交
320 321 322 323 324
    cls_name = "{0}_{1}".format(parent.__name__, "SumFp16Test")
    TestSumFp16Case.__name__ = cls_name
    globals()[cls_name] = TestSumFp16Case


325
# ----------- test bf16 -----------
326 327 328 329 330 331 332 333 334
class TestSumBF16Op(OpTest):
    def setUp(self):
        self.op_type = "sum"
        self.init_kernel_type()
        x0 = np.random.random((3, 40)).astype(np.float32)
        x1 = np.random.random((3, 40)).astype(np.float32)
        x2 = np.random.random((3, 40)).astype(np.float32)
        y = x0 + x1 + x2
        self.inputs = {
335 336 337 338 339
            "X": [
                ("x0", convert_float_to_uint16(x0)),
                ("x1", convert_float_to_uint16(x1)),
                ("x2", convert_float_to_uint16(x2)),
            ]
340 341 342 343 344 345 346 347 348 349 350 351 352
        }
        self.outputs = {'Out': convert_float_to_uint16(y)}

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

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['x0'], 'Out', numeric_grad_delta=0.5)


S
Steffy-zxf 已提交
353
class API_Test_Add_n(unittest.TestCase):
354 355
    def test_api(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
356 357 358 359 360 361
            input0 = fluid.layers.fill_constant(
                shape=[2, 3], dtype='int64', value=5
            )
            input1 = fluid.layers.fill_constant(
                shape=[2, 3], dtype='int64', value=3
            )
362 363
            expected_result = np.empty((2, 3))
            expected_result.fill(8)
S
Steffy-zxf 已提交
364
            sum_value = paddle.add_n([input0, input1])
365 366 367
            exe = fluid.Executor(fluid.CPUPlace())
            result = exe.run(fetch_list=[sum_value])

S
Steffy-zxf 已提交
368 369 370 371 372 373 374 375 376
            self.assertEqual((result == expected_result).all(), True)

        with fluid.dygraph.guard():
            input0 = paddle.ones(shape=[2, 3], dtype='float32')
            expected_result = np.empty((2, 3))
            expected_result.fill(2)
            sum_value = paddle.add_n([input0, input0])

            self.assertEqual((sum_value.numpy() == expected_result).all(), True)
377

378
    def test_dygraph_api(self):
379 380 381 382 383 384 385 386 387
        with fluid.dygraph.guard():
            with _test_eager_guard():
                input0 = paddle.ones(shape=[2, 3], dtype='float32')
                input1 = paddle.ones(shape=[2, 3], dtype='float32')
                input0.stop_gradient = False
                input1.stop_gradient = False
                expected_result = np.empty((2, 3))
                expected_result.fill(2)
                sum_value = paddle.add_n([input0, input1])
388 389 390
                self.assertEqual(
                    (sum_value.numpy() == expected_result).all(), True
                )
391 392 393 394 395

                expected_grad_result = np.empty((2, 3))
                expected_grad_result.fill(1)
                sum_value.backward()
                self.assertEqual(
396 397
                    (input0.grad.numpy() == expected_grad_result).all(), True
                )
398
                self.assertEqual(
399 400
                    (input1.grad.numpy() == expected_grad_result).all(), True
                )
401

W
Weilong Wu 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    def test_add_n_and_add_and_grad(self):
        with fluid.dygraph.guard():
            np_x = np.array([[1, 2, 3], [4, 5, 6]])
            np_y = [[7, 8, 9], [10, 11, 12]]
            np_z = [[1, 1, 1], [1, 1, 1]]
            x = paddle.to_tensor(np_x, dtype='float32', stop_gradient=False)
            y = paddle.to_tensor(np_y, dtype='float32', stop_gradient=False)
            z = paddle.to_tensor(np_z, dtype='float32')

            out1 = x + z
            out2 = y + z
            out = paddle.add_n([out1, out2])

            dx, dy = paddle.grad([out], [x, y], create_graph=True)

417
            expected_out = np.array([[10.0, 12.0, 14.0], [16.0, 18.0, 20.0]])
W
Weilong Wu 已提交
418 419 420
            expected_dx = np.array([[1, 1, 1], [1, 1, 1]])
            expected_dy = np.array([[1, 1, 1], [1, 1, 1]])

421 422 423
            np.testing.assert_allclose(out, expected_out, rtol=1e-05)
            np.testing.assert_allclose(dx, expected_dx, rtol=1e-05)
            np.testing.assert_allclose(dy, expected_dy, rtol=1e-05)
W
Weilong Wu 已提交
424

425

426 427 428 429 430 431 432 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 480 481 482
class TestRaiseSumError(unittest.TestCase):
    def test_errors(self):
        def test_type():
            fluid.layers.sum([11, 22])

        self.assertRaises(TypeError, test_type)

        def test_dtype():
            data1 = fluid.data(name="input1", shape=[10], dtype="int8")
            data2 = fluid.data(name="input2", shape=[10], dtype="int8")
            fluid.layers.sum([data1, data2])

        self.assertRaises(TypeError, test_dtype)

        def test_dtype1():
            data1 = fluid.data(name="input1", shape=[10], dtype="int8")
            fluid.layers.sum(data1)

        self.assertRaises(TypeError, test_dtype1)


class TestRaiseSumsError(unittest.TestCase):
    def test_errors(self):
        def test_type():
            fluid.layers.sums([11, 22])

        self.assertRaises(TypeError, test_type)

        def test_dtype():
            data1 = fluid.data(name="input1", shape=[10], dtype="int8")
            data2 = fluid.data(name="input2", shape=[10], dtype="int8")
            fluid.layers.sums([data1, data2])

        self.assertRaises(TypeError, test_dtype)

        def test_dtype1():
            data1 = fluid.data(name="input1", shape=[10], dtype="int8")
            fluid.layers.sums(data1)

        self.assertRaises(TypeError, test_dtype1)

        def test_out_type():
            data1 = fluid.data(name="input1", shape=[10], dtype="flaot32")
            data2 = fluid.data(name="input2", shape=[10], dtype="float32")
            fluid.layers.sums([data1, data2], out=[10])

        self.assertRaises(TypeError, test_out_type)

        def test_out_dtype():
            data1 = fluid.data(name="input1", shape=[10], dtype="flaot32")
            data2 = fluid.data(name="input2", shape=[10], dtype="float32")
            out = fluid.data(name="out", shape=[10], dtype="int8")
            fluid.layers.sums([data1, data2], out=out)

        self.assertRaises(TypeError, test_out_dtype)


L
Leo Chen 已提交
483 484 485 486
class TestSumOpError(unittest.TestCase):
    def test_errors(self):
        def test_empty_list_input():
            with fluid.dygraph.guard():
487
                fluid._legacy_C_ops.sum([])
L
Leo Chen 已提交
488 489 490

        def test_list_of_none_input():
            with fluid.dygraph.guard():
491
                fluid._legacy_C_ops.sum([None])
L
Leo Chen 已提交
492 493 494 495 496

        self.assertRaises(Exception, test_empty_list_input)
        self.assertRaises(Exception, test_list_of_none_input)


C
chengduo 已提交
497 498
create_test_sum_fp16_class(TestSelectedRowsSumOp)
create_test_sum_fp16_class(TestLoDTensorAndSelectedRowsOp)
C
chengduo 已提交
499

500 501 502 503 504 505 506

class TestReduceOPTensorAxisBase(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
        paddle.seed(2022)
        self.temp_dir = tempfile.TemporaryDirectory()
        self.save_path = os.path.join(self.temp_dir.name, 'reduce_tensor_axis')
507 508 509 510 511
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
            else paddle.CPUPlace()
        )
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        self.keepdim = False
        self.init_data()

    def tearDwon(self):
        self.temp_dir.cleanup()

    def init_data(self):
        self.pd_api = paddle.sum
        self.np_api = np.sum
        self.x = paddle.randn([10, 5, 9, 9], dtype='float64')
        self.np_axis = np.array((1, 2), dtype='int64')
        self.tensor_axis = paddle.to_tensor(self.np_axis, dtype='int64')

    def test_dygraph(self):
        self.x.stop_gradient = False
        pd_out = self.pd_api(self.x, self.tensor_axis)
        np_out = self.np_api(self.x.numpy(), tuple(self.np_axis))
        np.testing.assert_allclose(
530 531
            pd_out.numpy() if pd_out.size > 1 else pd_out.item(), np_out
        )
532 533 534 535 536 537 538 539 540
        pd_out.backward()
        self.assertEqual(self.x.gradient().shape, tuple(self.x.shape))

    def test_static_and_infer(self):
        paddle.enable_static()
        main_prog = paddle.static.Program()
        starup_prog = paddle.static.Program()
        with paddle.static.program_guard(main_prog, starup_prog):
            # run static
541 542 543
            x = paddle.static.data(
                shape=self.x.shape, name='x', dtype='float32'
            )
544 545 546 547 548 549 550 551 552 553 554 555 556
            if isinstance(self.tensor_axis, paddle.Tensor):
                axis = paddle.assign(self.np_axis)
            else:
                axis = []
                for i, item in enumerate(self.tensor_axis):
                    if isinstance(item, int):
                        axis.append(item)
                    else:
                        axis.append(paddle.full([1], self.np_axis[i], 'int64'))

            linear = paddle.nn.Linear(x.shape[-1], 5)
            linear_out = linear(x)
            out = self.pd_api(linear_out, axis, keepdim=self.keepdim)
557

558
            sgd = paddle.optimizer.SGD(learning_rate=0.0)
559
            sgd.minimize(paddle.mean(out))
560 561
            exe = paddle.static.Executor(self.place)
            exe.run(starup_prog)
562 563 564
            static_out = exe.run(
                feed={'x': self.x.numpy().astype('float32')}, fetch_list=[out]
            )
565 566 567

            # run infer
            paddle.static.save_inference_model(self.save_path, [x], [out], exe)
568 569 570
            config = paddle_infer.Config(
                self.save_path + '.pdmodel', self.save_path + '.pdiparams'
            )
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
            if paddle.is_compiled_with_cuda():
                config.enable_use_gpu(100, 0)
            else:
                config.disable_gpu()
            predictor = paddle_infer.create_predictor(config)
            input_names = predictor.get_input_names()
            input_handle = predictor.get_input_handle(input_names[0])
            fake_input = self.x.numpy().astype('float32')
            input_handle.reshape(self.x.shape)
            input_handle.copy_from_cpu(fake_input)
            predictor.run()
            output_names = predictor.get_output_names()
            output_handle = predictor.get_output_handle(output_names[0])
            infer_out = output_handle.copy_to_cpu()
            np.testing.assert_allclose(static_out[0], infer_out)


class TestSumWithTensorAxis1(TestReduceOPTensorAxisBase):
    def init_data(self):
        self.pd_api = paddle.sum
        self.np_api = np.sum
        self.x = paddle.randn([10, 5, 9, 9], dtype='float64')
        self.np_axis = np.array([0, 1, 2], dtype='int64')
        self.tensor_axis = [
            0,
            paddle.to_tensor([1], 'int64'),
597
            paddle.to_tensor([2], 'int64'),
598 599 600
        ]


601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
class TestAddNDoubleGradCheck(unittest.TestCase):
    def add_n_wrapper(self, x):
        return paddle.add_n(x)

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

        data1 = layers.data('data1', [3, 4, 5], False, dtype)
        data1.persistable = True
        data2 = layers.data('data2', [3, 4, 5], False, dtype)
        data2.persistable = True
        out = paddle.add_n([data1, data2])
        data1_arr = np.random.uniform(-1, 1, data1.shape).astype(dtype)
        data2_arr = np.random.uniform(-1, 1, data1.shape).astype(dtype)

619 620 621 622 623 624 625
        gradient_checker.double_grad_check(
            [data1, data2],
            out,
            x_init=[data1_arr, data2_arr],
            place=place,
            eps=eps,
        )
626 627
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
        gradient_checker.double_grad_check_for_dygraph(
628 629
            self.add_n_wrapper,
            [data1, data2],
630 631
            out,
            x_init=[data1_arr, data2_arr],
632 633
            place=place,
        )
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

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


class TestAddNTripleGradCheck(unittest.TestCase):
    def add_n_wrapper(self, x):
        return paddle.add_n(x)

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

        data1 = layers.data('data1', [3, 4, 5], False, dtype)
        data1.persistable = True
        data2 = layers.data('data2', [3, 4, 5], False, dtype)
        data2.persistable = True
        out = paddle.add_n([data1, data2])
        data1_arr = np.random.uniform(-1, 1, data1.shape).astype(dtype)
        data2_arr = np.random.uniform(-1, 1, data1.shape).astype(dtype)

662 663 664 665 666 667 668
        gradient_checker.triple_grad_check(
            [data1, data2],
            out,
            x_init=[data1_arr, data2_arr],
            place=place,
            eps=eps,
        )
669 670
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
        gradient_checker.triple_grad_check_for_dygraph(
671 672
            self.add_n_wrapper,
            [data1, data2],
673 674
            out,
            x_init=[data1_arr, data2_arr],
675 676
            place=place,
        )
677 678 679 680 681 682 683 684 685 686

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
class TestSumDoubleGradCheck(unittest.TestCase):
    def sum_wrapper(self, x):
        return paddle.sum(x[0], axis=1, keepdim=True)

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

        data = layers.data('data', [2, 4], False, dtype)
        data.persistable = True
        out = paddle.sum(data, axis=1, keepdim=True)
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

702 703 704
        gradient_checker.double_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
705
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
706 707 708
        gradient_checker.double_grad_check_for_dygraph(
            self.sum_wrapper, [data], out, x_init=[data_arr], place=place
        )
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

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


class TestSumTripleGradCheck(unittest.TestCase):
    def sum_wrapper(self, x):
        return paddle.sum(x[0], axis=1, keepdim=True)

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

        data = layers.data('data', [2, 4], False, dtype)
        data.persistable = True
        out = paddle.sum(data, axis=1, keepdim=True)
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

734 735 736
        gradient_checker.triple_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
737
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
738 739 740
        gradient_checker.triple_grad_check_for_dygraph(
            self.sum_wrapper, [data], out, x_init=[data_arr], place=place
        )
741 742 743 744 745 746 747 748 749 750

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


Q
qijun 已提交
751
if __name__ == "__main__":
752
    enable_static()
753
    unittest.main()