test_prroi_pool_op.py 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   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.

from __future__ import print_function

import numpy as np
import unittest
from py_precise_roi_pool import PyPrRoIPool
from op_test import OpTest
import paddle.fluid as fluid
22
import paddle.fluid.core as core
23 24 25 26 27 28 29 30 31 32
from paddle.fluid import compiler, Program, program_guard


class TestPRROIPoolOp(OpTest):
    def set_data(self):
        self.init_test_case()
        self.make_rois()
        self.prRoIPool = PyPrRoIPool()
        self.outs = self.prRoIPool.compute(
            self.x, self.rois, self.output_channels, self.spatial_scale,
33
            self.pooled_height, self.pooled_width).astype('float32')
34 35 36 37 38 39 40 41 42 43 44 45
        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
46 47
        self.height = 12
        self.width = 16
48 49 50

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

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

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

    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):
64
                x1 = np.random.uniform(
65
                    0, self.width // self.spatial_scale - self.pooled_width)
66
                y1 = np.random.uniform(
67 68
                    0, self.height // self.spatial_scale - self.pooled_height)

69 70 71 72
                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)
73 74 75
                roi = [bno, x1, y1, x2, y2]
                rois.append(roi)
        self.rois_num = len(rois)
76
        self.rois = np.array(rois).astype('float32')
77 78 79 80 81 82

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

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

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

    def run_net(self, place):
        with program_guard(Program(), Program()):
            x = fluid.layers.data(
                name="X",
                shape=[self.channels, self.height, self.width],
97
                dtype="float32")
98
            rois = fluid.layers.data(
99
                name="ROIs", shape=[4], dtype="float32", lod_level=1)
100
            output = fluid.layers.prroi_pool(x, rois, 0.25, 2, 2)
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            loss = fluid.layers.mean(output)
            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())
            exe.run(fluid.default_main_program(),
                    {'X': input_x,
                     "ROIs": input_rois})

    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()):
            x = fluid.layers.data(
123
                name="x", shape=[245, 30, 30], dtype="float32")
124
            rois = fluid.layers.data(
125
                name="rois", shape=[4], dtype="float32", lod_level=1)
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
            # 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):
    def set_data(self):
        self.init_test_case()
        self.make_rois()
        self.prRoIPool = PyPrRoIPool()
        self.outs = self.prRoIPool.compute(
            self.x, self.rois, self.output_channels, self.spatial_scale,
144
            self.pooled_height, self.pooled_width).astype('float32')
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

        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

173
        self.x = np.random.random(self.x_dim).astype('float32')
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

    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)
193
        self.rois = np.array(rois).astype('float32')
194 195 196 197 198 199

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

    def test_check_output(self):
200
        self.check_output(check_eager=True)
201 202 203 204 205 206

    def test_backward(self):
        places = [fluid.CPUPlace()]
        if fluid.core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
207
            self.check_grad_with_place(place, ['X'], 'Out', check_eager=True)
208 209 210 211 212 213

    def run_net(self, place):
        with program_guard(Program(), Program()):
            x = fluid.layers.data(
                name="X",
                shape=[self.channels, self.height, self.width],
214 215
                dtype="float32")
            rois = fluid.layers.data(name="ROIs", shape=[4], dtype="float32")
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
            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)
            loss = fluid.layers.mean(output)
            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()):
            x = fluid.layers.data(
241
                name="x", shape=[245, 30, 30], dtype="float32")
242
            rois = fluid.layers.data(
243
                name="rois", shape=[4], dtype="float32", lod_level=1)
244
            # spatial_scale must be float type
245 246
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 2, 7,
                              7)
247
            # pooled_height must be int type
248 249
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 0.25,
                              0.7, 7)
250
            # pooled_width must be int type
251 252
            self.assertRaises(TypeError, fluid.layers.prroi_pool, x, rois, 0.25,
                              7, 0.7)
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
            def test_bad_x():
                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)
                output = fluid.layers.prroi_pool(x, label, 0.25, 2, 2)

            self.assertRaises(TypeError, test_bad_x)

            def test_bad_y():
                x = fluid.layers.data(
                    name='data2',
                    shape=[2, 3, 16, 16],
                    dtype='float32',
                    append_batch_size=False)
                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)

281 282

if __name__ == '__main__':
283 284
    import paddle
    paddle.enable_static()
285
    unittest.main()