test_cumsum_op.py 15.6 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
E
emailweixu 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

W
WangZhen 已提交
15 16
import os
import tempfile
17 18 19
import unittest

import gradient_checker
E
emailweixu 已提交
20
import numpy as np
21
from decorator_helper import prog_scope
22
from op_test import OpTest
23

24
import paddle
25
import paddle.fluid as fluid
26
import paddle.fluid.core as core
27
import paddle.fluid.layers as layers
28
import paddle.inference as paddle_infer
29 30 31 32 33


class TestCumsumOp(unittest.TestCase):
    def run_cases(self):
        data_np = np.arange(12).reshape(3, 4)
Z
Zhou Wei 已提交
34
        data = paddle.to_tensor(data_np)
35 36 37

        y = paddle.cumsum(data)
        z = np.cumsum(data_np)
38
        np.testing.assert_array_equal(z, y.numpy())
39 40 41

        y = paddle.cumsum(data, axis=0)
        z = np.cumsum(data_np, axis=0)
42
        np.testing.assert_array_equal(z, y.numpy())
43 44 45

        y = paddle.cumsum(data, axis=-1)
        z = np.cumsum(data_np, axis=-1)
46
        np.testing.assert_array_equal(z, y.numpy())
47 48 49 50 51 52 53 54 55

        y = paddle.cumsum(data, dtype='float64')
        self.assertTrue(y.dtype == core.VarDesc.VarType.FP64)

        y = paddle.cumsum(data, dtype=np.int32)
        self.assertTrue(y.dtype == core.VarDesc.VarType.INT32)

        y = paddle.cumsum(data, axis=-2)
        z = np.cumsum(data_np, axis=-2)
56
        np.testing.assert_array_equal(z, y.numpy())
57 58 59 60

    def run_static(self, use_gpu=False):
        with fluid.program_guard(fluid.Program()):
            data_np = np.random.random((100, 100)).astype(np.float32)
61
            x = paddle.static.data('X', [100, 100])
62 63 64 65 66 67 68 69 70 71
            y = paddle.cumsum(x)
            y2 = paddle.cumsum(x, axis=0)
            y3 = paddle.cumsum(x, axis=-1)
            y4 = paddle.cumsum(x, dtype='float64')
            y5 = paddle.cumsum(x, dtype=np.int32)
            y6 = paddle.cumsum(x, axis=-2)

            place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
72 73 74 75 76 77 78 79 80 81 82
            out = exe.run(
                feed={'X': data_np},
                fetch_list=[
                    y.name,
                    y2.name,
                    y3.name,
                    y4.name,
                    y5.name,
                    y6.name,
                ],
            )
83 84

            z = np.cumsum(data_np)
85
            np.testing.assert_allclose(z, out[0], rtol=1e-05)
86
            z = np.cumsum(data_np, axis=0)
87
            np.testing.assert_allclose(z, out[1], rtol=1e-05)
88
            z = np.cumsum(data_np, axis=-1)
89
            np.testing.assert_allclose(z, out[2], rtol=1e-05)
90 91 92
            self.assertTrue(out[3].dtype == np.float64)
            self.assertTrue(out[4].dtype == np.int32)
            z = np.cumsum(data_np, axis=-2)
93
            np.testing.assert_allclose(z, out[5], rtol=1e-05)
94 95

    def test_cpu(self):
96 97 98
        paddle.disable_static(paddle.fluid.CPUPlace())
        self.run_cases()
        paddle.enable_static()
99 100 101 102 103 104

        self.run_static()

    def test_gpu(self):
        if not fluid.core.is_compiled_with_cuda():
            return
105 106 107
        paddle.disable_static(paddle.fluid.CUDAPlace(0))
        self.run_cases()
        paddle.enable_static()
108 109 110 111 112

        self.run_static(use_gpu=True)

    def test_name(self):
        with fluid.program_guard(fluid.Program()):
113
            x = paddle.static.data('x', [3, 4])
114 115
            y = paddle.cumsum(x, name='out')
            self.assertTrue('out' in y.name)
E
emailweixu 已提交
116 117 118 119 120 121 122 123 124 125


class TestSumOp1(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2}
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].cumsum(axis=2)}

    def test_check_output(self):
126
        self.check_output()
E
emailweixu 已提交
127 128

    def test_check_grad(self):
129
        self.check_grad(['X'], 'Out')
E
emailweixu 已提交
130 131 132 133 134 135 136 137


class TestSumOp2(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': -1, 'reverse': True}
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.outputs = {
138 139 140
            'Out': np.flip(
                np.flip(self.inputs['X'], axis=2).cumsum(axis=2), axis=2
            )
E
emailweixu 已提交
141 142 143
        }

    def test_check_output(self):
144
        self.check_output()
E
emailweixu 已提交
145 146

    def test_check_grad(self):
147
        self.check_grad(['X'], 'Out')
E
emailweixu 已提交
148 149 150 151 152 153 154 155 156 157


class TestSumOp3(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 1}
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].cumsum(axis=1)}

    def test_check_output(self):
158
        self.check_output()
E
emailweixu 已提交
159 160

    def test_check_grad(self):
161
        self.check_grad(['X'], 'Out')
E
emailweixu 已提交
162 163 164 165 166 167 168 169 170 171


class TestSumOp4(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 0}
        self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
        self.outputs = {'Out': self.inputs['X'].cumsum(axis=0)}

    def test_check_output(self):
172
        self.check_output()
E
emailweixu 已提交
173 174

    def test_check_grad(self):
175
        self.check_grad(['X'], 'Out')
E
emailweixu 已提交
176 177 178 179 180


class TestSumOp5(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
Z
zhupengyang 已提交
181
        self.inputs = {'X': np.random.random((5, 20)).astype("float64")}
E
emailweixu 已提交
182 183 184
        self.outputs = {'Out': self.inputs['X'].cumsum(axis=1)}

    def test_check_output(self):
185
        self.check_output()
E
emailweixu 已提交
186 187

    def test_check_grad(self):
188
        self.check_grad(['X'], 'Out')
E
emailweixu 已提交
189 190 191 192 193


class TestSumOp7(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
Z
zhupengyang 已提交
194
        self.inputs = {'X': np.random.random((100)).astype("float64")}
E
emailweixu 已提交
195 196 197
        self.outputs = {'Out': self.inputs['X'].cumsum(axis=0)}

    def test_check_output(self):
198
        self.check_output()
E
emailweixu 已提交
199 200

    def test_check_grad(self):
201
        self.check_grad(['X'], 'Out')
E
emailweixu 已提交
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
class TestCumsumFP16(unittest.TestCase):
    def check_main(self, x_np, dtype):
        paddle.disable_static()
        x = paddle.to_tensor(x_np.astype(dtype))
        x.stop_gradient = False
        y = paddle.cumsum(x, dtype=dtype)
        x_g = paddle.grad(y, [x])
        y_np = y.numpy().astype('float32')
        x_g_np = x_g[0].numpy().astype('float32')
        paddle.enable_static()
        return y_np, x_g_np

    def test_main(self):
        if not paddle.is_compiled_with_cuda():
            return

        np.random.seed(20)
        x_np = np.random.random([10, 12])
        y_np_1, x_g_np_1 = self.check_main(x_np, 'float16')
        y_np_2, x_g_np_2 = self.check_main(x_np, 'float32')

        np.testing.assert_allclose(y_np_1, y_np_2, rtol=1e-03)
        np.testing.assert_allclose(x_g_np_1, x_g_np_2, rtol=1e-03)


229
class TestSumOpExclusive1(OpTest):
E
emailweixu 已提交
230 231 232
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, "exclusive": True}
233
        a = np.random.random((4, 5, 65)).astype("float64")
E
emailweixu 已提交
234 235
        self.inputs = {'X': a}
        self.outputs = {
236 237 238 239 240 241 242
            'Out': np.concatenate(
                (
                    np.zeros((4, 5, 1), dtype=np.float64),
                    a[:, :, :-1].cumsum(axis=2),
                ),
                axis=2,
            )
E
emailweixu 已提交
243 244 245
        }

    def test_check_output(self):
246
        self.check_output()
E
emailweixu 已提交
247

248 249 250 251 252 253 254 255

class TestSumOpExclusive2(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, "exclusive": True}
        a = np.random.random((1, 1, 888)).astype("float64")
        self.inputs = {'X': a}
        self.outputs = {
256 257 258 259 260 261 262
            'Out': np.concatenate(
                (
                    np.zeros((1, 1, 1), dtype=np.float64),
                    a[:, :, :-1].cumsum(axis=2),
                ),
                axis=2,
            )
263 264 265 266 267 268 269 270 271 272 273 274 275
        }

    def test_check_output(self):
        self.check_output()


class TestSumOpExclusive3(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, "exclusive": True}
        a = np.random.random((4, 5, 888)).astype("float32")
        self.inputs = {'X': a}
        self.outputs = {
276 277 278 279 280 281 282
            'Out': np.concatenate(
                (
                    np.zeros((4, 5, 1), dtype=np.float64),
                    a[:, :, :-1].cumsum(axis=2),
                ),
                axis=2,
            )
283 284 285 286 287 288 289 290 291 292 293 294 295
        }

    def test_check_output(self):
        self.check_output()


class TestSumOpExclusive4(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, "exclusive": True}
        a = np.random.random((1, 1, 3049)).astype("float64")
        self.inputs = {'X': a}
        self.outputs = {
296 297 298 299 300 301 302
            'Out': np.concatenate(
                (
                    np.zeros((1, 1, 1), dtype=np.float64),
                    a[:, :, :-1].cumsum(axis=2),
                ),
                axis=2,
            )
303 304 305 306 307 308 309 310 311 312 313 314 315
        }

    def test_check_output(self):
        self.check_output()


class TestSumOpExclusive5(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, "exclusive": True}
        a = np.random.random((4, 5, 3096)).astype("float64")
        self.inputs = {'X': a}
        self.outputs = {
316 317 318 319 320 321 322
            'Out': np.concatenate(
                (
                    np.zeros((4, 5, 1), dtype=np.float64),
                    a[:, :, :-1].cumsum(axis=2),
                ),
                axis=2,
            )
323 324 325 326 327 328
        }

    def test_check_output(self):
        self.check_output()


329 330 331 332 333 334 335
class TestSumOpExclusiveFP16(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, "exclusive": True, "dtype": "float16"}
        a = np.random.random((4, 5, 3096)).astype("float64")
        self.inputs = {'X': a}
        self.outputs = {
336 337 338 339 340 341 342
            'Out': np.concatenate(
                (
                    np.zeros((4, 5, 1), dtype=np.float64),
                    a[:, :, :-1].cumsum(axis=2),
                ),
                axis=2,
            )
343 344 345 346 347 348
        }

    def test_check_output(self):
        self.check_output()


349 350 351 352 353 354 355 356
class TestSumOpReverseExclusive(OpTest):
    def setUp(self):
        self.op_type = "cumsum"
        self.attrs = {'axis': 2, 'reverse': True, "exclusive": True}
        a = np.random.random((4, 5, 6)).astype("float64")
        self.inputs = {'X': a}
        a = np.flip(a, axis=2)
        self.outputs = {
357 358 359 360 361 362 363
            'Out': np.concatenate(
                (
                    np.flip(a[:, :, :-1].cumsum(axis=2), axis=2),
                    np.zeros((4, 5, 1), dtype=np.float64),
                ),
                axis=2,
            )
364 365 366 367
        }

    def test_check_output(self):
        self.check_output()
E
emailweixu 已提交
368 369


370 371 372 373 374
class BadInputTest(unittest.TestCase):
    def test_error(self):
        with fluid.program_guard(fluid.Program()):

            def test_bad_x():
375
                data = [1, 2, 4]
376
                result = paddle.cumsum(data, axis=0)
377 378 379 380

            self.assertRaises(TypeError, test_bad_x)


W
WangZhen 已提交
381 382 383 384 385
class TestTensorAxis(unittest.TestCase):
    def setUp(self):
        paddle.seed(2022)
        self.temp_dir = tempfile.TemporaryDirectory()
        self.save_path = os.path.join(self.temp_dir.name, 'tensor_axis_cumsum')
386 387 388 389 390
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.is_compiled_with_cuda()
            else paddle.CPUPlace()
        )
W
WangZhen 已提交
391 392 393 394 395 396

    def test_dygraph(self):
        paddle.disable_static()
        x = np.random.randn(5, 6)
        axis = 1
        np_out = np.cumsum(x, axis)
397 398 399
        pd_out = paddle.cumsum(
            paddle.to_tensor(x), axis=paddle.to_tensor([axis], dtype='int32')
        )
W
WangZhen 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
        np.testing.assert_allclose(np_out, pd_out.numpy())

    def test_static_and_infer(self):
        paddle.enable_static()
        np_x = np.random.randn(9, 10, 11).astype('float32')
        main_prog = paddle.static.Program()
        starup_prog = paddle.static.Program()
        with paddle.static.program_guard(main_prog, starup_prog):
            # run static
            x = paddle.static.data(shape=np_x.shape, name='x', dtype=np_x.dtype)
            print(x)
            linear = paddle.nn.Linear(np_x.shape[-1], np_x.shape[-1])
            linear_out = linear(x)
            relu_out = paddle.nn.functional.relu(linear_out)
            axis = paddle.full([1], 2, dtype='int64')
            out = paddle.cumsum(relu_out, axis=axis)
416
            loss = paddle.mean(out)
417
            sgd = paddle.optimizer.SGD(learning_rate=0.0)
418
            sgd.minimize(paddle.mean(out))
W
WangZhen 已提交
419 420 421 422 423 424 425

            exe = paddle.static.Executor(self.place)
            exe.run(starup_prog)
            static_out = exe.run(feed={'x': np_x}, fetch_list=[out])

            # run infer
            paddle.static.save_inference_model(self.save_path, [x], [out], exe)
426 427 428
            config = paddle_infer.Config(
                self.save_path + '.pdmodel', self.save_path + '.pdiparams'
            )
W
WangZhen 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
            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 = np_x
            input_handle.reshape(np_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)


447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
class TestCumsumDoubleGradCheck(unittest.TestCase):
    def cumsum_wrapper(self, x):
        return paddle.cumsum(x[0], 0)

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

        data = layers.data('data', [3, 4], False, dtype)
        data.persistable = True
        out = paddle.cumsum(data, 0)
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

462 463 464 465 466 467
        gradient_checker.double_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
        gradient_checker.double_grad_check_for_dygraph(
            self.cumsum_wrapper, [data], out, x_init=[data_arr], place=place
        )
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

    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 TestCumsumTripleGradCheck(unittest.TestCase):
    def cumsum_wrapper(self, x):
        return paddle.cumsum(x[0], 0)

    @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, 3], False, dtype)
        data.persistable = True
        out = paddle.cumsum(data, 0)
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

493 494 495 496 497 498
        gradient_checker.triple_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
        gradient_checker.triple_grad_check_for_dygraph(
            self.cumsum_wrapper, [data], out, x_init=[data_arr], place=place
        )
499 500 501 502 503 504 505 506 507 508

    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)


E
emailweixu 已提交
509 510
if __name__ == '__main__':
    unittest.main()