test_tensor_shape.py 15.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

from __future__ import print_function

import numpy

import unittest
20
import paddle
21
import paddle.fluid as fluid
22
from paddle.fluid.dygraph.jit import declarative
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39


def dyfunc_tensor_shape_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.reshape(x, shape=x.shape)
    return res


def dyfunc_tensor_shape_2(x):
    x = fluid.dygraph.to_variable(x)
    shape = x.shape
    shape2 = shape
    res = fluid.layers.reshape(x, shape2)
    return res


def dyfunc_tensor_shape_3(x):
40
    # Transform y.shape but run y.shape actually because y is not Tensor
41 42 43 44 45 46 47 48 49 50 51 52 53 54
    x = fluid.dygraph.to_variable(x)
    y = numpy.ones(5)
    res = fluid.layers.reshape(x, shape=y.shape)
    return res


def dyfunc_tensor_shape_4(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.reshape(x, shape=(-1, x.shape[0], len(x.shape)))
    return res


def dyfunc_tensor_shape_5(x):
    # `res = fluid.layers.reshape(x, shape=(-1, s))` to
55
    # `res = fluid.layers.reshape(x, shape=(-1,
56
    #           paddle.jit.dy2static.convert_var_shape(x)[0]))`
57 58 59 60 61 62
    x = fluid.dygraph.to_variable(x)
    s = x.shape[0]
    res = fluid.layers.reshape(x, shape=(-1, s))
    return res


63 64 65 66 67 68 69 70 71 72
def dyfunc_tensor_shape_6(x):
    # `res = fluid.layers.reshape(x, shape=(-1, s))` to
    # `res = fluid.layers.reshape(x, shape=(-1,
    #           paddle.jit.dy2static.convert_var_shape(x)[0:]))`
    x = fluid.dygraph.to_variable(x)
    s = x.shape[0:]
    res = fluid.layers.reshape(x, shape=s)
    return res


73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
def dyfunc_tuple_shape_1(x):
    x = paddle.to_tensor(x)
    a, b = x.shape
    res = paddle.reshape(x, shape=(b, a))
    return res


def dyfunc_tuple_shape_2(x):
    x = paddle.to_tensor(x)
    shape = x.shape
    a, b = shape
    res = paddle.reshape(x, shape=(b, a))
    return res


88 89 90 91 92 93 94 95 96 97 98
def dyfunc_paddle_shape_api(x):
    x = paddle.to_tensor(x)
    # paddle.shape will not be converted.
    a = paddle.shape(x)[0]
    # alias api will also not be converted.
    alias_old_api = paddle.fluid.layers
    b = alias_old_api.shape(x)[1]
    res = paddle.reshape(x, shape=(b, a))
    return res


99 100 101 102 103
def dyfunc_with_if_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.reshape(x, [-1, 1])
    x_shape_0 = x.shape[0]
    if x_shape_0 < 1:
104
        # `res.shape[0]` is transformed into
105
        #   `paddle.jit.dy2static.convert_var_shape(res)[0]`
106 107 108 109 110 111 112 113 114 115 116
        if res.shape[0] > 1:
            res = fluid.layers.fill_constant(
                value=2, shape=x.shape, dtype="int32")
        else:
            res = fluid.layers.fill_constant(
                value=3, shape=x.shape, dtype="int32")
    return res


def dyfunc_with_if_2(x):
    x = fluid.dygraph.to_variable(x)
117
    # `len(x.shape)` will not be transformed because x.shape is not used by Paddle api.
118 119 120 121 122 123 124 125 126 127 128
    if len(x.shape) < 1:
        res = x
    else:
        res = fluid.layers.fill_constant(value=8, shape=x.shape, dtype="int32")

    return res


def dyfunc_with_for_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
129
    # `x.shape[0]` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
130 131 132 133 134 135 136 137 138 139
    for i in range(x.shape[0]):
        res += 1
    return res


def dyfunc_with_for_2(x):
    x = fluid.dygraph.to_variable(x)
    x_shape_0 = x.shape[0]
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")

140
    # `x_shape_0` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    for i in range(x_shape_0):
        res += 1
    return res


def dyfunc_with_for_3(x):
    # TODO(liym27):
    #  It will fail to run because `for i in range(len(x.shape))` will be transformed into Paddle while_loop.
    #  Here the python list x.shape will be added to loop_vars. However, loop_vars doesn't support python list.
    #  And the condition of `for i in range(len(x.shape))` only uses the length of x.shape, so it doesn't have to be transformed into Paddle while_loop.
    #  After the AST tranformation of for loop is improved, add TestTensorShapeInFor3.
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    # `len(x.shape)` is not transformed.
    for i in range(len(x.shape)):
        res += 1

    return res


def dyfunc_with_while_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
164
    # `x.shape[0]` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
165 166 167 168 169 170 171 172 173 174 175 176
    i = 1
    while i < x.shape[0]:
        res += 1
        i = i + 2
    return res


def dyfunc_with_while_2(x):
    x = fluid.dygraph.to_variable(x)
    x_shape_0 = x.shape[0]
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    i = 1
177
    # `x_shape_0` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
178
    while i < x_shape_0:
179 180 181
        res += 1
        i = i + 2
    return res
182 183


184 185 186 187 188 189 190 191 192 193 194 195 196
def dyfunc_with_while_3(x):
    x = fluid.dygraph.to_variable(x)
    x_shape = x.shape
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    i = 1

    # `len(x.shape)` is not transformed.
    while len(x_shape) > i:
        res += 1
        i += 1
    return res


197 198 199 200 201 202 203 204 205 206 207 208 209
def dyfunc_with_while_4(x):
    x = fluid.dygraph.to_variable(x)
    y = numpy.ones(5)
    y_shape_0 = y.shape[0]
    i = 1

    # Transform y_shape_0 but run y.shape[0] actually because y is not Tensor
    while y_shape_0 > i:
        x += 1
        i += 1
    return x


210 211 212 213 214 215 216 217
def dyfunc_change_shape_after_assign(x):
    x = paddle.to_tensor(x)
    a, b = x.shape
    x = paddle.reshape(x, shape=(-1, 1))
    res = paddle.reshape(x, shape=(b, a))
    return res


218 219
# 1. Basic tests without control flow
class TestTensorShapeBasic(unittest.TestCase):
220 221 222 223
    def setUp(self):
        self.input = numpy.ones(5).astype("int32")
        self.place = fluid.CUDAPlace(0) if fluid.is_compiled_with_cuda(
        ) else fluid.CPUPlace()
224 225
        self._set_input_spec()
        self._set_expected_op_num()
226 227 228 229
        self.init_test_func()

    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_1
230

231 232 233
    def _set_input_spec(self):
        self.input_spec = [paddle.static.InputSpec(shape=[5], dtype="int32")]

234
    def _run(self, to_static):
235
        with fluid.dygraph.guard():
236 237 238 239
            if to_static:
                res = declarative(self.dygraph_func)(self.input).numpy()
            else:
                res = self.dygraph_func(self.input).numpy()
240 241
            return res

242 243
    def get_dygraph_output(self):
        return self._run(to_static=False)
244

245
    def get_static_output(self):
246
        return self._run(to_static=True)
247 248

    def test_transformed_static_result(self):
249 250 251 252 253 254 255
        static_res = self.get_static_output()
        dygraph_res = self.get_dygraph_output()
        self.assertTrue(
            numpy.allclose(dygraph_res, static_res),
            msg='dygraph res is {}\nstatic_res is {}'.format(dygraph_res,
                                                             static_res))

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

    def _compute_op_num(self, program):
        self.op_num = sum([len(block.ops) for block in program.blocks])
        self.shape_op_num = 0
        self.slice_op_num = 0

        for block in program.blocks:
            self.shape_op_num += len(
                [op for op in block.ops if op.type == "shape"])
            self.slice_op_num += len(
                [op for op in block.ops if op.type == "slice"])

    def test_op_num(self):
        static_layer = paddle.jit.to_static(self.dygraph_func, self.input_spec)
        program = static_layer.main_program
        self._compute_op_num(program)
        self.assertEqual(self.op_num, self.expected_op_num)
        self.assertEqual(self.shape_op_num, self.expected_shape_op_num)
        self.assertEqual(self.slice_op_num, self.expected_slice_op_num)

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

class TestTensorShapeBasic2(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_2


class TestTensorShapeBasic3(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_3


class TestTensorShapeBasic4(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_4


class TestTensorShapeBasic5(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_5

300 301 302 303 304
    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

305

306 307 308 309
class TestTensorShapeBasic6(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_6

310 311 312 313 314
    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

315

316 317 318
class TestTupleShape1(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = numpy.ones((5, 7)).astype("int32")
319
        self.input_spec = [paddle.static.InputSpec(shape=[5, 7], dtype="int32")]
320 321 322 323 324 325
        self.dygraph_func = dyfunc_tuple_shape_1


class TestTupleShape2(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = numpy.ones((5, 7)).astype("int32")
326
        self.input_spec = [paddle.static.InputSpec(shape=[5, 7], dtype="int32")]
327 328 329
        self.dygraph_func = dyfunc_tuple_shape_2


330 331 332 333 334 335 336 337 338 339 340 341
class TestPaddleShapeApi(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = numpy.ones((5, 7)).astype("int32")
        self.input_spec = [paddle.static.InputSpec(shape=[5, 7], dtype="int32")]
        self.dygraph_func = dyfunc_paddle_shape_api

    def _set_expected_op_num(self):
        self.expected_op_num = 6
        self.expected_shape_op_num = 2
        self.expected_slice_op_num = 2


342 343 344 345 346
# 2. Tests with control flow if
class TestTensorShapeInIf1(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_if_1

347
    def _set_expected_op_num(self):
348 349 350
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1
351

352 353 354 355 356

class TestTensorShapeInIf2(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_if_2

357 358 359 360 361
    def _set_expected_op_num(self):
        self.expected_op_num = 14
        self.expected_shape_op_num = 2
        self.expected_slice_op_num = 1

362 363 364 365 366 367

# 3. Tests with control flow for loop
class TestTensorShapeInFor1(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_for_1

368 369 370 371 372
    def _set_expected_op_num(self):
        self.expected_op_num = 22
        self.expected_shape_op_num = 3
        self.expected_slice_op_num = 3

373

374
class TestTensorShapeInFor2(TestTensorShapeInFor1):
375 376 377
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_for_2

378 379 380 381 382
    def _set_expected_op_num(self):
        self.expected_op_num = 9
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

383 384

# 4. Tests with control flow while loop
385
class TestTensorShapeInWhile1(TestTensorShapeInFor1):
386 387 388 389
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_1


390
class TestTensorShapeInWhile2(TestTensorShapeInFor1):
391 392
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_2
393

394 395 396 397 398
    def _set_expected_op_num(self):
        self.expected_op_num = 6
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

399

400 401 402 403
class TestTensorShapeInWhile3(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_3

404
    def _set_expected_op_num(self):
405 406 407
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0
408

409 410 411 412 413

class TestTensorShapeInWhile4(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_4

414 415 416 417 418 419 420 421 422 423 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
    def _set_expected_op_num(self):
        self.expected_op_num = 5
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0


# 5. Test op num for negetive dim
class TestOpNumBasicWithTensorShape(unittest.TestCase):
    def setUp(self):
        self._set_input_spec()
        self._set_test_func()
        self._set_expected_op_num()

    def _set_input_spec(self):
        self.input_spec = [
            paddle.static.InputSpec(
                shape=[-1, 5], dtype="int32")
        ]

    def _set_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_1

    def _set_expected_op_num(self):
        self.expected_op_num = 3
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 0

    def _compute_op_num(self, program):
        self.op_num = sum([len(block.ops) for block in program.blocks])
        self.shape_op_num = 0
        self.slice_op_num = 0

        for block in program.blocks:
            self.shape_op_num += len(
                [op for op in block.ops if op.type == "shape"])
            self.slice_op_num += len(
                [op for op in block.ops if op.type == "slice"])

    def test_op_num(self):
        static_layer = paddle.jit.to_static(self.dygraph_func, self.input_spec)
        program = static_layer.main_program

        self._compute_op_num(program)
        self.assertEqual(self.op_num, self.expected_op_num)
        self.assertEqual(self.shape_op_num, self.expected_shape_op_num)
        self.assertEqual(self.slice_op_num, self.expected_slice_op_num)


class TestOpNumBasicWithTensorShape4(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_4

    def _set_expected_op_num(self):
        self.expected_op_num = 6
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1


class TestOpNumWithTensorShapeTuple1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_tuple_shape_1

    def _set_expected_op_num(self):
477 478 479
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0
480 481 482 483 484 485 486


class TestOpNumWithTensorShapeInIf1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_with_if_1

    def _set_expected_op_num(self):
487
        self.expected_op_num = 19
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        self.expected_shape_op_num = 4
        self.expected_slice_op_num = 2


class TestOpNumWithTensorShapeInFor1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_with_for_1

    def _set_expected_op_num(self):
        self.expected_op_num = 22
        self.expected_shape_op_num = 3
        self.expected_slice_op_num = 3


class TestOpNumWithTensorShapeInWhile1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_with_while_1

    def _set_expected_op_num(self):
        self.expected_op_num = 22
        self.expected_shape_op_num = 3
        self.expected_slice_op_num = 3

511

512 513 514 515 516 517 518 519 520 521 522 523
class TestChangeShapeAfterAssign(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = numpy.ones((2, 3)).astype("int32")
        self.input_spec = [paddle.static.InputSpec(shape=[2, 3], dtype="int32")]
        self.dygraph_func = dyfunc_change_shape_after_assign

    def _set_expected_op_num(self):
        self.expected_op_num = 3
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0


524 525
if __name__ == '__main__':
    unittest.main()