test_prroi_pool_op.py 11.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2019 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
from py_precise_roi_pool import PyPrRoIPool
from op_test import OpTest
19
import paddle
20
import paddle.fluid as fluid
21
from paddle.fluid import Program, program_guard
22 23 24


class TestPRROIPoolOp(OpTest):
25

26 27 28 29
    def set_data(self):
        self.init_test_case()
        self.make_rois()
        self.prRoIPool = PyPrRoIPool()
30 31 32 33 34
        self.outs = self.prRoIPool.compute(self.x, self.rois,
                                           self.output_channels,
                                           self.spatial_scale,
                                           self.pooled_height,
                                           self.pooled_width).astype('float32')
35 36 37 38 39 40 41 42 43 44 45 46
        self.inputs = {'X': self.x, 'ROIs': (self.rois[:, 1:5], self.rois_lod)}
        self.attrs = {
            'output_channels': self.output_channels,
            'spatial_scale': self.spatial_scale,
            'pooled_height': self.pooled_height,
            'pooled_width': self.pooled_width
        }
        self.outputs = {'Out': self.outs}

    def init_test_case(self):
        self.batch_size = 3
        self.channels = 3 * 2 * 2
47 48
        self.height = 12
        self.width = 16
49 50 51

        self.x_dim = [self.batch_size, self.channels, self.height, self.width]

52
        self.spatial_scale = 1.0 / 2.0
53
        self.output_channels = self.channels
54 55
        self.pooled_height = 4
        self.pooled_width = 4
56

57
        self.x = np.random.random(self.x_dim).astype('float32')
58 59 60 61 62 63 64

    def make_rois(self):
        rois = []
        self.rois_lod = [[]]
        for bno in range(self.batch_size):
            self.rois_lod[0].append(bno + 1)
            for i in range(bno + 1):
65
                x1 = np.random.uniform(
66
                    0, self.width // self.spatial_scale - self.pooled_width)
67
                y1 = np.random.uniform(
68 69
                    0, self.height // self.spatial_scale - self.pooled_height)

70 71 72 73
                x2 = np.random.uniform(x1 + self.pooled_width,
                                       self.width // self.spatial_scale)
                y2 = np.random.uniform(y1 + self.pooled_height,
                                       self.height // self.spatial_scale)
74 75 76
                roi = [bno, x1, y1, x2, y2]
                rois.append(roi)
        self.rois_num = len(rois)
77
        self.rois = np.array(rois).astype('float32')
78 79 80 81 82 83

    def setUp(self):
        self.op_type = 'prroi_pool'
        self.set_data()

    def test_check_output(self):
84
        self.check_output(check_eager=True)
85 86

    def test_backward(self):
87 88 89 90
        places = [fluid.CPUPlace()]
        if fluid.core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
91
            self.check_grad_with_place(place, ['X'], 'Out', check_eager=True)
92 93 94 95 96 97

    def run_net(self, place):
        with program_guard(Program(), Program()):
            x = fluid.layers.data(
                name="X",
                shape=[self.channels, self.height, self.width],
98
                dtype="float32")
99 100 101 102
            rois = fluid.layers.data(name="ROIs",
                                     shape=[4],
                                     dtype="float32",
                                     lod_level=1)
103
            output = fluid.layers.prroi_pool(x, rois, 0.25, 2, 2)
104
            loss = paddle.mean(output)
105 106 107 108 109 110 111
            optimizer = fluid.optimizer.SGD(learning_rate=1e-3)
            optimizer.minimize(loss)
            input_x = fluid.create_lod_tensor(self.x, [], place)
            input_rois = fluid.create_lod_tensor(self.rois[:, 1:5],
                                                 self.rois_lod, place)
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
112 113 114 115
            exe.run(fluid.default_main_program(), {
                'X': input_x,
                "ROIs": input_rois
            })
116 117 118 119 120 121 122 123 124 125

    def test_net(self):
        places = [fluid.CPUPlace()]
        if fluid.core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
            self.run_net(place)

    def test_errors(self):
        with program_guard(Program(), Program()):
126 127 128 129 130 131 132
            x = fluid.layers.data(name="x",
                                  shape=[245, 30, 30],
                                  dtype="float32")
            rois = fluid.layers.data(name="rois",
                                     shape=[4],
                                     dtype="float32",
                                     lod_level=1)
133 134 135 136 137 138 139 140 141 142 143 144
            # spatial_scale must be float type
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 2, 7,
                              7)
            # pooled_height must be int type
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 0.25,
                              0.7, 7)
            # pooled_width must be int type
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 0.25,
                              7, 0.7)


class TestPRROIPoolOpTensorRoIs(OpTest):
145

146 147 148 149
    def set_data(self):
        self.init_test_case()
        self.make_rois()
        self.prRoIPool = PyPrRoIPool()
150 151 152 153 154
        self.outs = self.prRoIPool.compute(self.x, self.rois,
                                           self.output_channels,
                                           self.spatial_scale,
                                           self.pooled_height,
                                           self.pooled_width).astype('float32')
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

        self.rois_index = np.array(self.rois_lod).reshape([-1]).astype(np.int64)
        self.inputs = {
            'X': self.x,
            'ROIs': self.rois[:, 1:5],
            'BatchRoINums': self.rois_index
        }
        self.attrs = {
            'output_channels': self.output_channels,
            'spatial_scale': self.spatial_scale,
            'pooled_height': self.pooled_height,
            'pooled_width': self.pooled_width
        }
        self.outputs = {'Out': self.outs}

    def init_test_case(self):
        self.batch_size = 3
        self.channels = 3 * 2 * 2
        self.height = 12
        self.width = 16

        self.x_dim = [self.batch_size, self.channels, self.height, self.width]

        self.spatial_scale = 1.0 / 2.0
        self.output_channels = self.channels
        self.pooled_height = 4
        self.pooled_width = 4

183
        self.x = np.random.random(self.x_dim).astype('float32')
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

    def make_rois(self):
        rois = []
        self.rois_lod = []
        for bno in range(self.batch_size):
            self.rois_lod.append(bno + 1)
            for i in range(bno + 1):
                x1 = np.random.uniform(
                    0, self.width // self.spatial_scale - self.pooled_width)
                y1 = np.random.uniform(
                    0, self.height // self.spatial_scale - self.pooled_height)

                x2 = np.random.uniform(x1 + self.pooled_width,
                                       self.width // self.spatial_scale)
                y2 = np.random.uniform(y1 + self.pooled_height,
                                       self.height // self.spatial_scale)
                roi = [bno, x1, y1, x2, y2]
                rois.append(roi)
        self.rois_num = len(rois)
203
        self.rois = np.array(rois).astype('float32')
204 205 206 207 208 209

    def setUp(self):
        self.op_type = 'prroi_pool'
        self.set_data()

    def test_check_output(self):
210
        self.check_output(check_eager=True)
211 212 213 214 215 216

    def test_backward(self):
        places = [fluid.CPUPlace()]
        if fluid.core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
217
            self.check_grad_with_place(place, ['X'], 'Out', check_eager=True)
218 219 220 221 222 223

    def run_net(self, place):
        with program_guard(Program(), Program()):
            x = fluid.layers.data(
                name="X",
                shape=[self.channels, self.height, self.width],
224 225
                dtype="float32")
            rois = fluid.layers.data(name="ROIs", shape=[4], dtype="float32")
226 227 228 229 230 231 232 233 234
            rois_index = fluid.layers.data(name='rois_idx',
                                           shape=[],
                                           dtype="int64")
            output = fluid.layers.prroi_pool(x,
                                             rois,
                                             0.25,
                                             2,
                                             2,
                                             batch_roi_nums=rois_index)
235
            loss = paddle.mean(output)
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            optimizer = fluid.optimizer.SGD(learning_rate=1e-3)
            optimizer.minimize(loss)
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
            exe.run(fluid.default_main_program(), {
                'X': self.x,
                "ROIs": self.rois[:, 1:5],
                "rois_idx": self.rois_index
            })

    def test_net(self):
        places = [fluid.CPUPlace()]
        if fluid.core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
            self.run_net(place)

    def test_errors(self):
        with program_guard(Program(), Program()):
255 256 257 258 259 260 261
            x = fluid.layers.data(name="x",
                                  shape=[245, 30, 30],
                                  dtype="float32")
            rois = fluid.layers.data(name="rois",
                                     shape=[4],
                                     dtype="float32",
                                     lod_level=1)
262
            # spatial_scale must be float type
263 264
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 2, 7,
                              7)
265
            # pooled_height must be int type
266 267
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 0.25,
                              0.7, 7)
268
            # pooled_width must be int type
269 270
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 0.25,
                              7, 0.7)
271

272
            def test_bad_x():
273 274 275 276 277 278 279 280 281
                x = fluid.layers.data(name='data1',
                                      shape=[2, 3, 16, 16],
                                      dtype='int64',
                                      append_batch_size=False)
                label = fluid.layers.data(name='label1',
                                          shape=[2, 4],
                                          dtype='float32',
                                          lod_level=1,
                                          append_batch_size=False)
282 283 284 285 286
                output = fluid.layers.prroi_pool(x, label, 0.25, 2, 2)

            self.assertRaises(TypeError, test_bad_x)

            def test_bad_y():
287 288 289 290
                x = fluid.layers.data(name='data2',
                                      shape=[2, 3, 16, 16],
                                      dtype='float32',
                                      append_batch_size=False)
291 292 293 294 295
                label = [[1, 2, 3, 4], [2, 3, 4, 5]]
                output = fluid.layers.prroi_pool(x, label, 0.25, 2, 2)

            self.assertRaises(TypeError, test_bad_y)

296 297

if __name__ == '__main__':
298 299
    import paddle
    paddle.enable_static()
300
    unittest.main()