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

15 16
from __future__ import print_function

Z
zchen0211 已提交
17
import unittest
Q
qijun 已提交
18
import numpy as np
19
from op_test import OpTest
20 21
import paddle
import paddle.fluid as fluid
Z
zchen0211 已提交
22 23


24 25 26 27 28 29 30
def gather_numpy(x, index, axis):
    x_transpose = np.swapaxes(x, 0, axis)
    tmp_gather = x_transpose[index, ...]
    gather = np.swapaxes(tmp_gather, 0, axis)
    return gather


Q
qijun 已提交
31
class TestGatherOp(OpTest):
Z
zchen0211 已提交
32
    def setUp(self):
Q
qijun 已提交
33
        self.op_type = "gather"
W
whs 已提交
34
        self.config()
35 36 37 38 39
        xnp = np.random.random(self.x_shape).astype(self.x_type)
        self.inputs = {
            'X': xnp,
            'Index': np.array(self.index).astype(self.index_type)
        }
Q
qijun 已提交
40
        self.outputs = {'Out': self.inputs["X"][self.inputs["Index"]]}
Z
zchen0211 已提交
41

Q
qijun 已提交
42 43
    def test_check_output(self):
        self.check_output()
Z
zchen0211 已提交
44

Q
qijun 已提交
45 46
    def test_check_grad(self):
        self.check_grad(['X'], 'Out')
Z
zchen0211 已提交
47

W
whs 已提交
48
    def config(self):
49 50 51
        """
        For multi-dimension input
        """
W
whs 已提交
52
        self.x_shape = (10, 20)
53
        self.x_type = "float64"
W
whs 已提交
54
        self.index = [1, 3, 5]
55
        self.index_type = "int32"
W
whs 已提交
56 57 58 59


class TestCase1(TestGatherOp):
    def config(self):
60 61 62
        """
        For one dimension input
        """
Z
zhupengyang 已提交
63
        self.x_shape = (100)
64
        self.x_type = "float64"
W
whs 已提交
65
        self.index = [1, 3, 5]
66 67 68 69 70 71 72 73
        self.index_type = "int32"


class TestCase2(TestGatherOp):
    def config(self):
        """
        For int64_t index type
        """
Z
zhupengyang 已提交
74
        self.x_shape = (100)
75
        self.x_type = "float64"
76 77 78 79 80 81 82 83 84 85
        self.index = [1, 3, 5]
        self.index_type = "int64"


class TestCase3(TestGatherOp):
    def config(self):
        """
        For other input type
        """
        self.x_shape = (10, 20)
86
        self.x_type = "float64"
87 88
        self.index = [1, 3, 5]
        self.index_type = "int64"
W
whs 已提交
89

Z
zchen0211 已提交
90

91 92 93 94 95 96 97 98 99 100 101 102 103
class TestCase4(TestGatherOp):
    def config(self):
        self.x_shape = (10, 20)
        self.attrs = {'overwrite': False}
        self.x_type = "double"
        self.index = [1, 1]
        self.index_type = "int32"


class TestCase5(TestGatherOp):
    def config(self):
        self.x_shape = (10, 20)
        self.attrs = {'overwrite': False}
104
        self.x_type = "float64"
105 106 107 108 109 110 111 112
        self.index = [1, 1, 3]
        self.index_type = "int32"


class TestCase6(TestGatherOp):
    def config(self):
        self.x_shape = (10, 20)
        self.attrs = {'overwrite': True}
113
        self.x_type = "float64"
114 115 116 117
        self.index = [1, 3]
        self.index_type = "int32"


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 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 177 178 179 180 181 182 183 184 185
class TestGatherOp1(OpTest):
    def setUp(self):
        self.op_type = "gather"
        self.config()
        xnp = np.random.random(self.x_shape).astype(self.x_type)
        axis_np = np.array(self.axis).astype(self.index_type)
        index_np = np.array(self.index).astype(self.index_type)
        out = gather_numpy(xnp, index_np, axis_np[0])
        self.inputs = {'X': xnp, 'Index': index_np, 'Axis': axis_np}
        self.outputs = {'Out': out}

    def test_check_output(self):
        self.check_output()

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

    def config(self):
        """
        For multi-dimension input
        """
        self.x_shape = (3, 88, 3)
        self.x_type = "float64"
        self.index = [1, 3, 5]
        self.index_type = "int32"
        self.axis = [1]
        self.axis_type = "int32"


class TestGatherOp2(TestGatherOp1):
    def config(self):
        """
        For multi-dimension input
        """
        self.x_shape = (10, 88, 10)
        self.x_type = "float64"
        self.index = [1, 3, 5]
        self.index_type = "int64"
        self.axis = [0]
        self.axis_type = "int32"


class TestGatherOp3(TestGatherOp1):
    def config(self):
        """
        For multi-dimension input
        """
        self.x_shape = (10, 88, 10)
        self.x_type = "float64"
        self.index = [1, 3, 5]
        self.index_type = "int64"
        self.axis = [2]
        self.axis_type = "int32"


class TestGatherOp4(TestGatherOp1):
    def config(self):
        """
        For multi-dimension input
        """
        self.x_shape = (3, 100, 10)
        self.x_type = "float64"
        self.index = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        self.index_type = "int64"
        self.axis = [0]
        self.axis_type = "int32"


186
class API_TestGather(unittest.TestCase):
187
    def test_out1(self):
188 189
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            data1 = fluid.layers.data('data1', shape=[-1, 2], dtype='float64')
190 191
            index = fluid.layers.data('index', shape=[-1, 1], dtype='int32')
            out = paddle.fluid.layers.gather(data1, index)
192 193 194 195 196 197 198 199 200 201
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input = np.array([[1, 2], [3, 4], [5, 6]])
            index_1 = np.array([1, 2])
            result, = exe.run(feed={"data1": input,
                                    "index": index_1},
                              fetch_list=[out])
            expected_output = np.array([[3, 4], [5, 6]])
        self.assertTrue(np.allclose(result, expected_output))

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    def test_out2(self):
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
            x = paddle.data('x', shape=[-1, 2], dtype='float64')
            index = paddle.data('index', shape=[-1, 1], dtype='int32')
            axis = paddle.data('axis', shape=[1], dtype='int32')
            out = paddle.gather(x, index, axis)
            place = paddle.CPUPlace()
            exe = paddle.static.Executor(place)
            x_np = np.array([[1, 2], [3, 4], [5, 6]]).astype('float64')
            index_np = np.array([1, 1]).astype('int32')
            axis_np = np.array([1]).astype('int32')
            result, = exe.run(
                feed={"x": x_np,
                      "index": index_np,
                      'axis': axis_np},
                fetch_list=[out])
            expected_output = gather_numpy(x_np, index_np, axis_np)
        self.assertTrue(np.allclose(result, expected_output))

222 223

class API_TestDygraphGather(unittest.TestCase):
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    def test_out1(self):
        paddle.disable_static()
        input_1 = np.array([[1, 2], [3, 4], [5, 6]])
        index_1 = np.array([1, 2])
        input = paddle.to_tensor(input_1)
        index = paddle.to_tensor(index_1)
        output = paddle.fluid.layers.gather(input, index)
        output_np = output.numpy()
        expected_output = np.array([[3, 4], [5, 6]])
        self.assertTrue(np.allclose(output_np, expected_output))
        paddle.enable_static()

    def test_out12(self):
        paddle.disable_static()
        input_1 = np.array([[1, 2], [3, 4], [5, 6]])
        index_1 = np.array([1, 2])
        x = paddle.to_tensor(input_1)
        index = paddle.to_tensor(index_1)
        output = paddle.gather(x, index, axis=0)
        output_np = output.numpy()
        expected_output = gather_numpy(input_1, index_1, axis=0)
245
        self.assertTrue(np.allclose(output_np, expected_output))
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        paddle.enable_static()


class TestGathertError(unittest.TestCase):
    def test_error1(self):
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):

            shape = [8, 9, 6]
            x = paddle.data(shape=shape, dtype='int8', name='x')
            axis = paddle.data(shape=[1], dtype='float32', name='axis')
            index = paddle.data(shape=shape, dtype='int32', name='index')
            index_float = paddle.data(
                shape=shape, dtype='float32', name='index_float')

            def test_x_type():
                paddle.gather(x, index)

            self.assertRaises(TypeError, test_x_type)

            def test_index_type():
                paddle.gather(x, index_float)

            self.assertRaises(TypeError, test_index_type)

            def test_axis_dtype():
                paddle.gather(x, index, axis=1.11)

            self.assertRaises(TypeError, test_axis_dtype)

            def test_axis_dtype():
                paddle.gather(x, index, axis=axis)

            self.assertRaises(TypeError, test_axis_dtype)

    def test_error2(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):

            shape = [8, 9, 6]
            x = fluid.data(shape=shape, dtype='int8', name='x')
            index = fluid.data(shape=shape, dtype='int32', name='mask')
            index_float = fluid.data(
                shape=shape, dtype='float32', name='index_float')

            def test_x_type():
                paddle.fluid.layers.gather(x, index)

            self.assertRaises(TypeError, test_x_type)

            def test_index_type():
                paddle.fluid.layers.gather(x, index_float)

            self.assertRaises(TypeError, test_index_type)
299 300


Z
zchen0211 已提交
301 302
if __name__ == "__main__":
    unittest.main()