test_stack_op.py 11.3 KB
Newer Older
X
Xin Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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
16 17

import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest, convert_float_to_uint16
19

20
import paddle
21
from paddle import fluid
22
from paddle.fluid.framework import Program, program_guard
X
Xin Pan 已提交
23

24 25
paddle.enable_static()

X
Xin Pan 已提交
26 27 28 29 30 31

class TestStackOpBase(OpTest):
    def initDefaultParameters(self):
        self.num_inputs = 4
        self.input_dim = (5, 6, 7)
        self.axis = 0
32
        self.dtype = 'float64'
X
Xin Pan 已提交
33 34 35 36 37 38 39

    def initParameters(self):
        pass

    def get_x_names(self):
        x_names = []
        for i in range(self.num_inputs):
40
            x_names.append(f'x{i}')
X
Xin Pan 已提交
41 42 43 44 45 46
        return x_names

    def setUp(self):
        self.initDefaultParameters()
        self.initParameters()
        self.op_type = 'stack'
C
ccrrong 已提交
47
        self.prim_op_type = "comp"
48
        self.python_api = paddle.stack
49
        self.public_python_api = paddle.stack
X
Xin Pan 已提交
50 51 52
        self.x = []
        for i in range(self.num_inputs):
            self.x.append(
53 54
                np.random.random(size=self.input_dim).astype(self.dtype)
            )
X
Xin Pan 已提交
55 56 57 58 59 60 61 62 63 64 65

        tmp = []
        x_names = self.get_x_names()
        for i in range(self.num_inputs):
            tmp.append((x_names[i], self.x[i]))

        self.inputs = {'X': tmp}
        self.outputs = {'Y': np.stack(self.x, axis=self.axis)}
        self.attrs = {'axis': self.axis}

    def test_check_output(self):
W
wanghuancoder 已提交
66
        self.check_output(check_prim=True)
X
Xin Pan 已提交
67 68

    def test_check_grad(self):
W
wanghuancoder 已提交
69
        self.check_grad(self.get_x_names(), 'Y', check_prim=True)
X
Xin Pan 已提交
70 71 72 73


class TestStackOp1(TestStackOpBase):
    def initParameters(self):
74
        self.num_inputs = 8
X
Xin Pan 已提交
75 76 77 78


class TestStackOp2(TestStackOpBase):
    def initParameters(self):
79
        self.num_inputs = 10
X
Xin Pan 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101


class TestStackOp3(TestStackOpBase):
    def initParameters(self):
        self.axis = -1


class TestStackOp4(TestStackOpBase):
    def initParameters(self):
        self.axis = -4


class TestStackOp5(TestStackOpBase):
    def initParameters(self):
        self.axis = 1


class TestStackOp6(TestStackOpBase):
    def initParameters(self):
        self.axis = 3


102 103 104
class TestStackOp_ZeroDim(TestStackOpBase):
    def initParameters(self):
        self.input_dim = ()
C
ccrrong 已提交
105
        self.enable_cinn = False
106 107


108 109 110 111 112 113 114 115 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 145 146 147 148
class TestStackFP16Op(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16


class TestStackFP16Op1(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16
        self.num_inputs = 8


class TestStackFP16Op2(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16
        self.num_inputs = 10


class TestStackFP16Op3(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16
        self.axis = -1


class TestStackFP16Op4(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16
        self.axis = -4


class TestStackFP16Op5(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16
        self.axis = 1


class TestStackFP16Op6(TestStackOpBase):
    def initParameters(self):
        self.dtype = np.float16
        self.axis = 3


149 150 151 152 153 154 155 156 157 158 159 160 161
class TestStackBF16Op(OpTest):
    def initDefaultParameters(self):
        self.num_inputs = 4
        self.input_dim = (5, 6, 7)
        self.axis = 0
        self.dtype = np.uint16

    def initParameters(self):
        pass

    def get_x_names(self):
        x_names = []
        for i in range(self.num_inputs):
162
            x_names.append(f'x{i}')
163 164 165 166 167 168
        return x_names

    def setUp(self):
        self.initDefaultParameters()
        self.initParameters()
        self.op_type = 'stack'
C
ccrrong 已提交
169 170
        self.prim_op_type = "comp"
        self.enable_cinn = False
171
        self.python_api = paddle.stack
172
        self.public_python_api = paddle.stack
173 174 175
        self.x = []
        for i in range(self.num_inputs):
            self.x.append(
176 177
                np.random.random(size=self.input_dim).astype(np.float32)
            )
178 179 180 181 182 183 184 185 186 187 188 189 190

        out = np.stack(self.x, axis=self.axis)

        tmp = []
        x_names = self.get_x_names()
        for i in range(self.num_inputs):
            tmp.append((x_names[i], convert_float_to_uint16(self.x[i])))

        self.inputs = {'X': tmp}
        self.outputs = {'Y': convert_float_to_uint16(out)}
        self.attrs = {'axis': self.axis}

    def test_check_output(self):
W
wanghuancoder 已提交
191
        self.check_output(check_prim=True)
192 193

    def test_check_grad(self):
C
ccrrong 已提交
194
        # concat_grad unspport bfloat16 dtype, skip check_prim
W
wanghuancoder 已提交
195
        self.check_grad(self.get_x_names(), 'Y')
196 197


198 199 200 201 202 203 204 205 206 207
class TestStackAPIWithLoDTensorArray(unittest.TestCase):
    """
    Test stack api when the input(x) is a LoDTensorArray.
    """

    def setUp(self):
        self.axis = 1
        self.iter_num = 3
        self.input_shape = [2, 3]
        self.x = np.random.random(self.input_shape).astype("float32")
208 209 210 211 212
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
213 214 215 216 217
        self.set_program()

    def set_program(self):
        self.program = fluid.Program()
        with fluid.program_guard(self.program):
218
            input = paddle.assign(self.x)
219
            tensor_array = paddle.tensor.create_array(dtype='float32')
220 221 222
            zero = paddle.tensor.fill_constant(
                shape=[1], value=0, dtype="int64"
            )
223 224

            for i in range(self.iter_num):
225
                paddle.tensor.array_write(input, zero + i, tensor_array)
226

227
            self.out_var = paddle.stack(tensor_array, axis=self.axis)
228 229 230 231 232

    def test_case(self):
        self.assertTrue(self.out_var.shape[self.axis] == -1)
        exe = fluid.Executor(self.place)
        res = exe.run(self.program, fetch_list=self.out_var)
233
        np.testing.assert_array_equal(
234 235
            res[0], np.stack([self.x] * self.iter_num, axis=self.axis)
        )
236 237


238 239 240 241 242 243 244 245 246 247
class TestTensorStackAPIWithLoDTensorArray(unittest.TestCase):
    """
    Test stack api when the input(x) is a LoDTensorArray.
    """

    def setUp(self):
        self.axis = 1
        self.iter_num = 3
        self.input_shape = [2, 3]
        self.x = np.random.random(self.input_shape).astype("float32")
248 249 250 251 252
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
253 254 255 256 257
        self.set_program()

    def set_program(self):
        self.program = fluid.Program()
        with fluid.program_guard(self.program):
258
            input = paddle.assign(self.x)
259
            tensor_array = paddle.tensor.create_array(dtype='float32')
260 261 262
            zero = paddle.tensor.fill_constant(
                shape=[1], value=0, dtype="int64"
            )
263 264

            for i in range(self.iter_num):
265
                paddle.tensor.array_write(input, zero + i, tensor_array)
266 267 268 269 270 271 272

            self.out_var = paddle.stack(tensor_array, axis=self.axis)

    def test_case(self):
        self.assertTrue(self.out_var.shape[self.axis] == -1)
        exe = fluid.Executor(self.place)
        res = exe.run(self.program, fetch_list=self.out_var)
273
        np.testing.assert_array_equal(
274 275
            res[0], np.stack([self.x] * self.iter_num, axis=self.axis)
        )
276 277 278 279 280


class API_test(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
G
GGBond8488 已提交
281 282 283
            data1 = paddle.static.data('data1', shape=[1, 2], dtype='float64')
            data2 = paddle.static.data('data2', shape=[1, 2], dtype='float64')
            data3 = paddle.static.data('data3', shape=[1, 2], dtype='float64')
284 285 286 287 288 289
            result_stack = paddle.stack([data1, data2, data3], axis=0)
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([1, 2]).astype('float64')
            input2 = np.random.random([1, 2]).astype('float64')
            input3 = np.random.random([1, 2]).astype('float64')
290 291 292 293
            (result,) = exe.run(
                feed={"data1": input1, "data2": input2, "data3": input3},
                fetch_list=[result_stack],
            )
294
            expected_result = np.stack([input1, input2, input3], axis=0)
295
            np.testing.assert_allclose(expected_result, result, rtol=1e-05)
296

L
Leo Chen 已提交
297 298 299 300 301
    def test_single_tensor_error(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            x = paddle.rand([2, 3])
            self.assertRaises(TypeError, paddle.stack, x)

302 303 304 305 306 307 308 309 310 311

class API_DygraphTest(unittest.TestCase):
    def test_out(self):
        data1 = np.array([[1.0, 2.0]])
        data2 = np.array([[3.0, 4.0]])
        data3 = np.array([[5.0, 6.0]])
        with fluid.dygraph.guard():
            x1 = fluid.dygraph.to_variable(data1)
            x2 = fluid.dygraph.to_variable(data2)
            x3 = fluid.dygraph.to_variable(data3)
L
Leo Chen 已提交
312
            result = paddle.stack([x1, x2, x3])
313
            result_np = result.numpy()
L
Leo Chen 已提交
314
        expected_result = np.stack([data1, data2, data3])
315
        np.testing.assert_allclose(expected_result, result_np, rtol=1e-05)
316 317 318

        with fluid.dygraph.guard():
            y1 = fluid.dygraph.to_variable(data1)
L
Leo Chen 已提交
319
            result = paddle.stack([y1], axis=0)
320
            result_np_2 = result.numpy()
L
Leo Chen 已提交
321
        expected_result_2 = np.stack([data1], axis=0)
322
        np.testing.assert_allclose(expected_result_2, result_np_2, rtol=1e-05)
323

L
Leo Chen 已提交
324 325 326 327 328
    def test_single_tensor_error(self):
        with fluid.dygraph.guard():
            x = paddle.to_tensor([1, 2, 3])
            self.assertRaises(Exception, paddle.stack, x)

329

330 331 332 333 334 335 336 337 338
class TestStackOpWithNegativeShape(unittest.TestCase):
    def test_out(self):
        main_prg, startup_prg = Program(), Program()
        with program_guard(main_prg, startup_prg):
            b = paddle.static.data(name='b', shape=[-1], dtype='int64')
            e = paddle.static.data(name='e', shape=[3], dtype='int64')
            k = paddle.stack([b, e], axis=0)
            exe = paddle.static.Executor()
            exe.run(startup_prg)
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
            out = exe.run(
                main_prg,
                feed={
                    'b': np.ones(
                        [
                            3,
                        ]
                    ).astype("int64"),
                    'e': np.zeros(
                        [
                            3,
                        ]
                    ).astype("int64"),
                },
                fetch_list=[k],
            )
        np.testing.assert_allclose(
            out[0], np.array([[1, 1, 1], [0, 0, 0]]), rtol=1e-05
        )
358 359


360 361 362 363 364 365 366 367 368
class TestStackAPI_ZeroDim(unittest.TestCase):
    def test_dygraph(self):
        paddle.disable_static()

        x1 = paddle.rand([])
        x2 = paddle.rand([])
        x1.stop_gradient = False
        x2.stop_gradient = False
        out = paddle.stack([x1, x2])
369
        out.retain_grads()
370 371 372 373 374 375 376 377 378 379
        out.backward()

        self.assertEqual(out.shape, [2])
        self.assertEqual(x1.grad.shape, [])
        self.assertEqual(x2.grad.shape, [])
        self.assertEqual(out.grad.shape, [2])

        paddle.enable_static()


X
Xin Pan 已提交
380 381
if __name__ == '__main__':
    unittest.main()