test_stack_op.py 8.4 KB
Newer Older
X
Xin Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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 numpy as np
import unittest
17
import paddle
18
import paddle.fluid as fluid
19 20
from op_test import OpTest, convert_float_to_uint16
import paddle.fluid.core as core
X
Xin Pan 已提交
21 22 23


class TestStackOpBase(OpTest):
24

X
Xin Pan 已提交
25 26 27 28
    def initDefaultParameters(self):
        self.num_inputs = 4
        self.input_dim = (5, 6, 7)
        self.axis = 0
29
        self.dtype = 'float64'
X
Xin Pan 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43

    def initParameters(self):
        pass

    def get_x_names(self):
        x_names = []
        for i in range(self.num_inputs):
            x_names.append('x{}'.format(i))
        return x_names

    def setUp(self):
        self.initDefaultParameters()
        self.initParameters()
        self.op_type = 'stack'
44
        self.python_api = paddle.stack
X
Xin Pan 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
        self.x = []
        for i in range(self.num_inputs):
            self.x.append(
                np.random.random(size=self.input_dim).astype(self.dtype))

        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):
60
        self.check_output(check_eager=True)
X
Xin Pan 已提交
61 62

    def test_check_grad(self):
63
        self.check_grad(self.get_x_names(), 'Y', check_eager=True)
X
Xin Pan 已提交
64 65 66


class TestStackOp1(TestStackOpBase):
67

X
Xin Pan 已提交
68
    def initParameters(self):
69
        self.num_inputs = 8
X
Xin Pan 已提交
70 71 72


class TestStackOp2(TestStackOpBase):
73

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


class TestStackOp3(TestStackOpBase):
79

X
Xin Pan 已提交
80 81 82 83 84
    def initParameters(self):
        self.axis = -1


class TestStackOp4(TestStackOpBase):
85

X
Xin Pan 已提交
86 87 88 89 90
    def initParameters(self):
        self.axis = -4


class TestStackOp5(TestStackOpBase):
91

X
Xin Pan 已提交
92 93 94 95 96
    def initParameters(self):
        self.axis = 1


class TestStackOp6(TestStackOpBase):
97

X
Xin Pan 已提交
98 99 100 101
    def initParameters(self):
        self.axis = 3


102
class TestStackBF16Op(OpTest):
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    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):
            x_names.append('x{}'.format(i))
        return x_names

    def setUp(self):
        self.initDefaultParameters()
        self.initParameters()
        self.op_type = 'stack'
123
        self.python_api = paddle.stack
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        self.x = []
        for i in range(self.num_inputs):
            self.x.append(
                np.random.random(size=self.input_dim).astype(np.float32))

        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):
141
        self.check_output(check_eager=True)
142 143

    def test_check_grad(self):
144
        self.check_grad(self.get_x_names(), 'Y', check_eager=True)
145 146


147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
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")
        self.place = fluid.CUDAPlace(0) \
            if fluid.is_compiled_with_cuda() else fluid.CPUPlace()
        self.set_program()

    def set_program(self):
        self.program = fluid.Program()
        with fluid.program_guard(self.program):
            input = fluid.layers.assign(self.x)
            tensor_array = fluid.layers.create_array(dtype='float32')
            zero = fluid.layers.fill_constant(shape=[1], value=0, dtype="int64")

            for i in range(self.iter_num):
                fluid.layers.array_write(input, zero + i, tensor_array)

            self.out_var = fluid.layers.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)
177 178
        np.testing.assert_array_equal(
            res[0], np.stack([self.x] * self.iter_num, axis=self.axis))
179 180


181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
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")
        self.place = fluid.CUDAPlace(0) \
            if fluid.is_compiled_with_cuda() else fluid.CPUPlace()
        self.set_program()

    def set_program(self):
        self.program = fluid.Program()
        with fluid.program_guard(self.program):
            input = fluid.layers.assign(self.x)
            tensor_array = fluid.layers.create_array(dtype='float32')
            zero = fluid.layers.fill_constant(shape=[1], value=0, dtype="int64")

            for i in range(self.iter_num):
                fluid.layers.array_write(input, zero + i, tensor_array)

            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)
211 212
        np.testing.assert_array_equal(
            res[0], np.stack([self.x] * self.iter_num, axis=self.axis))
213 214 215


class API_test(unittest.TestCase):
216

217 218 219 220 221 222 223 224 225 226 227
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            data1 = fluid.layers.data('data1', shape=[1, 2], dtype='float64')
            data2 = fluid.layers.data('data2', shape=[1, 2], dtype='float64')
            data3 = fluid.layers.data('data3', shape=[1, 2], dtype='float64')
            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')
228 229 230 231 232 233
            result, = exe.run(feed={
                "data1": input1,
                "data2": input2,
                "data3": input3
            },
                              fetch_list=[result_stack])
234 235 236
            expected_result = np.stack([input1, input2, input3], axis=0)
            self.assertTrue(np.allclose(expected_result, result))

L
Leo Chen 已提交
237 238 239 240 241
    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)

242 243

class API_DygraphTest(unittest.TestCase):
244

245 246 247 248 249 250 251 252
    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 已提交
253
            result = paddle.stack([x1, x2, x3])
254
            result_np = result.numpy()
L
Leo Chen 已提交
255
        expected_result = np.stack([data1, data2, data3])
256 257 258 259
        self.assertTrue(np.allclose(expected_result, result_np))

        with fluid.dygraph.guard():
            y1 = fluid.dygraph.to_variable(data1)
L
Leo Chen 已提交
260
            result = paddle.stack([y1], axis=0)
261
            result_np_2 = result.numpy()
L
Leo Chen 已提交
262
        expected_result_2 = np.stack([data1], axis=0)
263 264
        self.assertTrue(np.allclose(expected_result_2, result_np_2))

L
Leo Chen 已提交
265 266 267 268 269
    def test_single_tensor_error(self):
        with fluid.dygraph.guard():
            x = paddle.to_tensor([1, 2, 3])
            self.assertRaises(Exception, paddle.stack, x)

270

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