test_tile_op.py 11.7 KB
Newer Older
L
lilong12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   Copyright (c) 2018 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.

import unittest
import numpy as np
from op_test import OpTest
import paddle
import paddle.fluid as fluid
20
from paddle.fluid import Program, core, program_guard
21 22 23
import gradient_checker
from decorator_helper import prog_scope
import paddle.fluid.layers as layers
L
lilong12 已提交
24 25


H
hong 已提交
26
#Situation 1: repeat_times is a list (without tensor)
L
lilong12 已提交
27
class TestTileOpRank1(OpTest):
28

L
lilong12 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    def setUp(self):
        self.op_type = "tile"
        self.init_data()

        self.inputs = {'X': np.random.random(self.ori_shape).astype("float64")}
        self.attrs = {'repeat_times': self.repeat_times}
        output = np.tile(self.inputs['X'], self.repeat_times)
        self.outputs = {'Out': output}

    def init_data(self):
        self.ori_shape = [100]
        self.repeat_times = [2]

    def test_check_output(self):
        self.check_output()

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


49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
class TestTileOpRank_ZeroDim1(TestTileOpRank1):

    def init_data(self):
        self.ori_shape = []
        self.repeat_times = []


class TestTileOpRank_ZeroDim2(TestTileOpRank1):

    def init_data(self):
        self.ori_shape = []
        self.repeat_times = [2]


class TestTileOpRank_ZeroDim3(TestTileOpRank1):

    def init_data(self):
        self.ori_shape = []
        self.repeat_times = [2, 3]


L
lilong12 已提交
70 71
# with dimension expanding
class TestTileOpRank2Expanding(TestTileOpRank1):
72

L
lilong12 已提交
73 74 75 76 77 78
    def init_data(self):
        self.ori_shape = [120]
        self.repeat_times = [2, 2]


class TestTileOpRank2(TestTileOpRank1):
79

L
lilong12 已提交
80 81 82 83 84 85
    def init_data(self):
        self.ori_shape = [12, 14]
        self.repeat_times = [2, 3]


class TestTileOpRank3_Corner(TestTileOpRank1):
86

L
lilong12 已提交
87 88 89 90 91 92
    def init_data(self):
        self.ori_shape = (2, 10, 5)
        self.repeat_times = (1, 1, 1)


class TestTileOpRank3_Corner2(TestTileOpRank1):
93

L
lilong12 已提交
94 95 96 97 98 99
    def init_data(self):
        self.ori_shape = (2, 10, 5)
        self.repeat_times = (2, 2)


class TestTileOpRank3(TestTileOpRank1):
100

L
lilong12 已提交
101 102 103 104 105 106
    def init_data(self):
        self.ori_shape = (2, 4, 15)
        self.repeat_times = (2, 1, 4)


class TestTileOpRank4(TestTileOpRank1):
107

L
lilong12 已提交
108 109 110 111 112
    def init_data(self):
        self.ori_shape = (2, 4, 5, 7)
        self.repeat_times = (3, 2, 1, 2)


L
lilong12 已提交
113
# Situation 2: repeat_times is a list (with tensor)
L
lilong12 已提交
114
class TestTileOpRank1_tensor_attr(OpTest):
115

L
lilong12 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    def setUp(self):
        self.op_type = "tile"
        self.init_data()
        repeat_times_tensor = []
        for index, ele in enumerate(self.repeat_times):
            repeat_times_tensor.append(("x" + str(index), np.ones(
                (1)).astype('int32') * ele))

        self.inputs = {
            'X': np.random.random(self.ori_shape).astype("float64"),
            'repeat_times_tensor': repeat_times_tensor,
        }
        self.attrs = {"repeat_times": self.infer_repeat_times}
        output = np.tile(self.inputs['X'], self.repeat_times)
        self.outputs = {'Out': output}

    def init_data(self):
        self.ori_shape = [100]
        self.repeat_times = [2]
        self.infer_repeat_times = [-1]

    def test_check_output(self):
        self.check_output()

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


class TestTileOpRank2_Corner_tensor_attr(TestTileOpRank1_tensor_attr):
145

L
lilong12 已提交
146 147 148 149 150 151 152
    def init_data(self):
        self.ori_shape = [12, 14]
        self.repeat_times = [1, 1]
        self.infer_repeat_times = [1, -1]


class TestTileOpRank2_attr_tensor(TestTileOpRank1_tensor_attr):
153

L
lilong12 已提交
154 155 156 157 158 159 160 161
    def init_data(self):
        self.ori_shape = [12, 14]
        self.repeat_times = [2, 3]
        self.infer_repeat_times = [-1, 3]


# Situation 3: repeat_times is a tensor
class TestTileOpRank1_tensor(OpTest):
162

L
lilong12 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    def setUp(self):
        self.op_type = "tile"
        self.init_data()

        self.inputs = {
            'X': np.random.random(self.ori_shape).astype("float64"),
            'RepeatTimes': np.array(self.repeat_times).astype("int32"),
        }
        self.attrs = {}
        output = np.tile(self.inputs['X'], self.repeat_times)
        self.outputs = {'Out': output}

    def init_data(self):
        self.ori_shape = [100]
        self.repeat_times = [2]

    def test_check_output(self):
        self.check_output()

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


class TestTileOpRank2_tensor(TestTileOpRank1_tensor):
187

L
lilong12 已提交
188 189 190 191 192 193 194
    def init_data(self):
        self.ori_shape = [12, 14]
        self.repeat_times = [2, 3]


# Situation 4: input x is Integer
class TestTileOpInteger(OpTest):
195

L
lilong12 已提交
196 197 198
    def setUp(self):
        self.op_type = "tile"
        self.inputs = {
199
            'X': np.random.randint(10, size=(4, 4, 5)).astype("int32")
L
lilong12 已提交
200 201 202 203 204 205 206 207 208 209 210
        }
        self.attrs = {'repeat_times': [2, 1, 4]}
        output = np.tile(self.inputs['X'], (2, 1, 4))
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output()


# Situation 5: input x is Bool
class TestTileOpBoolean(OpTest):
211

L
lilong12 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224
    def setUp(self):
        self.op_type = "tile"
        self.inputs = {'X': np.random.randint(2, size=(2, 4, 5)).astype("bool")}
        self.attrs = {'repeat_times': [2, 1, 4]}
        output = np.tile(self.inputs['X'], (2, 1, 4))
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output()


# Situation 56: input x is Integer
class TestTileOpInt64_t(OpTest):
225

L
lilong12 已提交
226 227 228
    def setUp(self):
        self.op_type = "tile"
        self.inputs = {
229
            'X': np.random.randint(10, size=(2, 4, 5)).astype("int64")
L
lilong12 已提交
230 231 232 233 234 235 236 237 238 239
        }
        self.attrs = {'repeat_times': [2, 1, 4]}
        output = np.tile(self.inputs['X'], (2, 1, 4))
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output()


class TestTileError(unittest.TestCase):
240

L
lilong12 已提交
241 242
    def test_errors(self):
        with program_guard(Program(), Program()):
243 244
            x1 = fluid.create_lod_tensor(np.array([[-1]]), [[1]],
                                         fluid.CPUPlace())
L
lilong12 已提交
245 246 247 248 249
            repeat_times = [2, 2]
            self.assertRaises(TypeError, paddle.tile, x1, repeat_times)
            x2 = fluid.layers.data(name='x2', shape=[4], dtype="uint8")
            self.assertRaises(TypeError, paddle.tile, x2, repeat_times)
            x3 = fluid.layers.data(name='x3', shape=[4], dtype="bool")
L
lilong12 已提交
250
            x3.stop_gradient = False
L
lilong12 已提交
251 252 253
            self.assertRaises(ValueError, paddle.tile, x3, repeat_times)


254
class TestTileAPIStatic(unittest.TestCase):
255

256 257 258 259 260 261 262 263 264
    def test_api(self):
        with program_guard(Program(), Program()):
            repeat_times = [2, 2]
            x1 = fluid.layers.data(name='x1', shape=[4], dtype="int32")
            out = paddle.tile(x1, repeat_times)
            positive_2 = fluid.layers.fill_constant([1], dtype="int32", value=2)
            out2 = paddle.tile(x1, repeat_times=[positive_2, 2])


L
lilong12 已提交
265 266
# Test python API
class TestTileAPI(unittest.TestCase):
267

L
lilong12 已提交
268
    def test_api(self):
L
lilong12 已提交
269 270
        with fluid.dygraph.guard():
            np_x = np.random.random([12, 14]).astype("float32")
271
            x = paddle.to_tensor(np_x)
L
lilong12 已提交
272 273

            positive_2 = np.array([2]).astype("int32")
274
            positive_2 = paddle.to_tensor(positive_2)
L
lilong12 已提交
275 276

            repeat_times = np.array([2, 3]).astype("int32")
277
            repeat_times = paddle.to_tensor(repeat_times)
L
lilong12 已提交
278 279 280 281 282 283 284 285

            out_1 = paddle.tile(x, repeat_times=[2, 3])
            out_2 = paddle.tile(x, repeat_times=[positive_2, 3])
            out_3 = paddle.tile(x, repeat_times=repeat_times)

            assert np.array_equal(out_1.numpy(), np.tile(np_x, (2, 3)))
            assert np.array_equal(out_2.numpy(), np.tile(np_x, (2, 3)))
            assert np.array_equal(out_3.numpy(), np.tile(np_x, (2, 3)))
L
lilong12 已提交
286 287


288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 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
class TestTileDoubleGradCheck(unittest.TestCase):

    def tile_wrapper(self, x):
        return paddle.tile(x[0], [2, 1])

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

        gradient_checker.double_grad_check([data],
                                           out,
                                           x_init=[data_arr],
                                           place=place,
                                           eps=eps)
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
        gradient_checker.double_grad_check_for_dygraph(self.tile_wrapper,
                                                       [data],
                                                       out,
                                                       x_init=[data_arr],
                                                       place=place)

    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 TestTileTripleGradCheck(unittest.TestCase):

    def tile_wrapper(self, x):
        return paddle.tile(x[0], [2, 1])

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

        gradient_checker.triple_grad_check([data],
                                           out,
                                           x_init=[data_arr],
                                           place=place,
                                           eps=eps)
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
        gradient_checker.triple_grad_check_for_dygraph(self.tile_wrapper,
                                                       [data],
                                                       out,
                                                       x_init=[data_arr],
                                                       place=place)

    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)


362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
class TestTileAPI_ZeroDim(unittest.TestCase):

    def test_dygraph(self):
        paddle.disable_static()
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})

        x = paddle.rand([])
        x.stop_gradient = False

        out = paddle.tile(x, [])
        out.backward()
        self.assertEqual(out.shape, [])
        self.assertEqual(x.grad.shape, [])
        self.assertEqual(out.grad.shape, [])

        out = paddle.tile(x, [3])
        out.backward()
        self.assertEqual(out.shape, [3])
        self.assertEqual(x.grad.shape, [])
        self.assertEqual(out.grad.shape, [3])

        out = paddle.tile(x, [2, 3])
        out.backward()
        self.assertEqual(out.shape, [2, 3])
        self.assertEqual(x.grad.shape, [])
        self.assertEqual(out.grad.shape, [2, 3])

        paddle.enable_static()


L
lilong12 已提交
392
if __name__ == "__main__":
H
hong 已提交
393
    paddle.enable_static()
L
lilong12 已提交
394
    unittest.main()