test_input_spec.py 11.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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.

15 16
import os
import tempfile
17 18
import unittest

19
import numpy as np
20

21
import paddle
22
import paddle.fluid as fluid
23
from paddle.fluid.framework import convert_np_dtype_to_dtype_
24
from paddle.jit.dy2static.utils import _compatible_non_tensor_spec
25
from paddle.static import InputSpec
26 27 28 29 30


class TestInputSpec(unittest.TestCase):
    def test_default(self):
        tensor_spec = InputSpec([3, 4])
31 32 33
        self.assertEqual(
            tensor_spec.dtype, convert_np_dtype_to_dtype_('float32')
        )
34
        self.assertIsNone(tensor_spec.name)
35 36 37 38 39

    def test_from_tensor(self):
        x_bool = fluid.layers.fill_constant(shape=[1], dtype='bool', value=True)
        bool_spec = InputSpec.from_tensor(x_bool)
        self.assertEqual(bool_spec.dtype, x_bool.dtype)
40
        self.assertEqual(list(bool_spec.shape), list(x_bool.shape))
41 42 43 44 45 46 47 48
        self.assertEqual(bool_spec.name, x_bool.name)

        bool_spec2 = InputSpec.from_tensor(x_bool, name='bool_spec')
        self.assertEqual(bool_spec2.name, bool_spec2.name)

    def test_from_numpy(self):
        x_numpy = np.ones([10, 12])
        x_np_spec = InputSpec.from_numpy(x_numpy)
49 50 51
        self.assertEqual(
            x_np_spec.dtype, convert_np_dtype_to_dtype_(x_numpy.dtype)
        )
52
        self.assertEqual(x_np_spec.shape, x_numpy.shape)
53
        self.assertIsNone(x_np_spec.name)
54 55 56

        x_numpy2 = np.array([1, 2, 3, 4]).astype('int64')
        x_np_spec2 = InputSpec.from_numpy(x_numpy2, name='x_np_int64')
57 58 59
        self.assertEqual(
            x_np_spec2.dtype, convert_np_dtype_to_dtype_(x_numpy2.dtype)
        )
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        self.assertEqual(x_np_spec2.shape, x_numpy2.shape)
        self.assertEqual(x_np_spec2.name, 'x_np_int64')

    def test_shape_with_none(self):
        tensor_spec = InputSpec([None, 4, None], dtype='int8', name='x_spec')
        self.assertEqual(tensor_spec.dtype, convert_np_dtype_to_dtype_('int8'))
        self.assertEqual(tensor_spec.name, 'x_spec')
        self.assertEqual(tensor_spec.shape, (-1, 4, -1))

    def test_shape_raise_error(self):
        # 1. shape should only contain int and None.
        with self.assertRaises(ValueError):
            tensor_spec = InputSpec(['None', 4, None], dtype='int8')

        # 2. shape should be type `list` or `tuple`
        with self.assertRaises(TypeError):
            tensor_spec = InputSpec(4, dtype='int8')

        # 3. len(shape) should be greater than 0.
        with self.assertRaises(ValueError):
            tensor_spec = InputSpec([], dtype='int8')

    def test_batch_and_unbatch(self):
        tensor_spec = InputSpec([10])
        # insert batch_size
        batch_tensor_spec = tensor_spec.batch(16)
        self.assertEqual(batch_tensor_spec.shape, (16, 10))

        # unbatch
        unbatch_spec = batch_tensor_spec.unbatch()
90
        self.assertEqual(unbatch_spec.shape, (10,))
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

        # 1. `unbatch` requires len(shape) > 1
        with self.assertRaises(ValueError):
            unbatch_spec.unbatch()

        # 2. `batch` requires len(batch_size) == 1
        with self.assertRaises(ValueError):
            tensor_spec.batch([16, 12])

        # 3. `batch` requires type(batch_size) == int
        with self.assertRaises(TypeError):
            tensor_spec.batch('16')

    def test_eq_and_hash(self):
        tensor_spec_1 = InputSpec([10, 16], dtype='float32')
        tensor_spec_2 = InputSpec([10, 16], dtype='float32')
        tensor_spec_3 = InputSpec([10, 16], dtype='float32', name='x')
        tensor_spec_4 = InputSpec([16], dtype='float32', name='x')

        # override ``__eq__`` according to [shape, dtype, name]
        self.assertTrue(tensor_spec_1 == tensor_spec_2)
        self.assertTrue(tensor_spec_1 != tensor_spec_3)  # different name
        self.assertTrue(tensor_spec_3 != tensor_spec_4)  # different shape

        # override ``__hash__``  according to [shape, dtype]
        self.assertTrue(hash(tensor_spec_1) == hash(tensor_spec_2))
        self.assertTrue(hash(tensor_spec_1) == hash(tensor_spec_3))
        self.assertTrue(hash(tensor_spec_3) != hash(tensor_spec_4))


121 122
class NetWithNonTensorSpec(paddle.nn.Layer):
    def __init__(self, in_num, out_num):
123
        super().__init__()
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
        self.linear_1 = paddle.nn.Linear(in_num, out_num)
        self.bn_1 = paddle.nn.BatchNorm1D(out_num)

        self.linear_2 = paddle.nn.Linear(in_num, out_num)
        self.bn_2 = paddle.nn.BatchNorm1D(out_num)

        self.linear_3 = paddle.nn.Linear(in_num, out_num)
        self.bn_3 = paddle.nn.BatchNorm1D(out_num)

    def forward(self, x, bool_v=False, str_v="bn", int_v=1, list_v=None):
        x = self.linear_1(x)
        if 'bn' in str_v:
            x = self.bn_1(x)

        if bool_v:
            x = self.linear_2(x)
            x = self.bn_2(x)

        config = {"int_v": int_v, 'other_key': "value"}
        if list_v and list_v[-1] > 2:
            x = self.linear_3(x)
            x = self.another_func(x, config)

        out = paddle.mean(x)
        return out

    def another_func(self, x, config=None):
        # config is a dict actually
        use_bn = config['int_v'] > 0

        x = self.linear_1(x)
        if use_bn:
            x = self.bn_3(x)

        return x


class TestNetWithNonTensorSpec(unittest.TestCase):
    def setUp(self):
        self.in_num = 16
        self.out_num = 16
        self.x_spec = paddle.static.InputSpec([-1, 16], name='x')
        self.x = paddle.randn([4, 16])
167 168 169 170
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

    @classmethod
    def setUpClass(cls):
        paddle.disable_static()

    def test_non_tensor_bool(self):
        specs = [self.x_spec, False]
        self.check_result(specs, 'bool')

    def test_non_tensor_str(self):
        specs = [self.x_spec, True, "xxx"]
        self.check_result(specs, 'str')

    def test_non_tensor_int(self):
        specs = [self.x_spec, True, "bn", 10]
        self.check_result(specs, 'int')

    def test_non_tensor_list(self):
        specs = [self.x_spec, False, "bn", -10, [4]]
        self.check_result(specs, 'list')

    def check_result(self, specs, path):
193
        path = os.path.join(self.temp_dir.name, './net_non_tensor_', path)
194 195 196 197 198 199 200 201 202 203 204 205

        net = NetWithNonTensorSpec(self.in_num, self.out_num)
        net.eval()
        # dygraph out
        dy_out = net(self.x, *specs[1:])

        # jit.save directly
        paddle.jit.save(net, path + '_direct', input_spec=specs)
        load_net = paddle.jit.load(path + '_direct')
        load_net.eval()
        pred_out = load_net(self.x)

206
        np.testing.assert_allclose(dy_out, pred_out, rtol=1e-05)
207 208 209 210 211

        # @to_static by InputSpec
        net = paddle.jit.to_static(net, input_spec=specs)
        st_out = net(self.x, *specs[1:])

212
        np.testing.assert_allclose(dy_out, st_out, rtol=1e-05)
213 214 215 216 217 218 219

        # jit.save and jit.load
        paddle.jit.save(net, path)
        load_net = paddle.jit.load(path)
        load_net.eval()
        load_out = load_net(self.x)

220
        np.testing.assert_allclose(st_out, load_out, rtol=1e-05)
221 222 223 224 225 226 227 228

    def test_spec_compatible(self):
        net = NetWithNonTensorSpec(self.in_num, self.out_num)

        specs = [self.x_spec, False, "bn", -10]
        net = paddle.jit.to_static(net, input_spec=specs)
        net.eval()

229
        path = os.path.join(self.temp_dir.name, './net_twice')
230 231 232 233 234 235 236 237 238 239 240 241 242

        # NOTE: check input_specs_compatible
        new_specs = [self.x_spec, True, "bn", 10]
        with self.assertRaises(ValueError):
            paddle.jit.save(net, path, input_spec=new_specs)

        dy_out = net(self.x)

        paddle.jit.save(net, path, [self.x_spec, False, "bn"])
        load_net = paddle.jit.load(path)
        load_net.eval()
        pred_out = load_net(self.x)

243
        np.testing.assert_allclose(dy_out, pred_out, rtol=1e-05)
244 245 246 247


class NetWithNonTensorSpecPrune(paddle.nn.Layer):
    def __init__(self, in_num, out_num):
248
        super().__init__()
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
        self.linear_1 = paddle.nn.Linear(in_num, out_num)
        self.bn_1 = paddle.nn.BatchNorm1D(out_num)

    def forward(self, x, y, use_bn=False):
        x = self.linear_1(x)
        if use_bn:
            x = self.bn_1(x)

        out = paddle.mean(x)

        if y is not None:
            loss = paddle.mean(y) + out

        return out, loss


class TestNetWithNonTensorSpecWithPrune(unittest.TestCase):
    def setUp(self):
        self.in_num = 16
        self.out_num = 16
        self.x_spec = paddle.static.InputSpec([-1, 16], name='x')
        self.y_spec = paddle.static.InputSpec([16], name='y')
        self.x = paddle.randn([4, 16])
        self.y = paddle.randn([16])
273
        self.temp_dir = tempfile.TemporaryDirectory()
274 275 276 277 278 279 280

    @classmethod
    def setUpClass(cls):
        paddle.disable_static()

    def test_non_tensor_with_prune(self):
        specs = [self.x_spec, self.y_spec, True]
281
        path = os.path.join(self.temp_dir.name, './net_non_tensor_prune_')
282 283 284 285 286 287 288 289 290 291 292 293

        net = NetWithNonTensorSpecPrune(self.in_num, self.out_num)
        net.eval()
        # dygraph out
        dy_out, _ = net(self.x, self.y, *specs[2:])

        # jit.save directly
        paddle.jit.save(net, path + '_direct', input_spec=specs)
        load_net = paddle.jit.load(path + '_direct')
        load_net.eval()
        pred_out, _ = load_net(self.x, self.y)

294
        np.testing.assert_allclose(dy_out, pred_out, rtol=1e-05)
295 296 297 298 299

        # @to_static by InputSpec
        net = paddle.jit.to_static(net, input_spec=specs)
        st_out, _ = net(self.x, self.y, *specs[2:])

300
        np.testing.assert_allclose(dy_out, st_out, rtol=1e-05)
301 302 303 304 305 306 307 308

        # jit.save and jit.load with prune y and loss
        prune_specs = [self.x_spec, True]
        paddle.jit.save(net, path, prune_specs, output_spec=[st_out])
        load_net = paddle.jit.load(path)
        load_net.eval()
        load_out = load_net(self.x)  # no y and no loss

309
        np.testing.assert_allclose(st_out, load_out, rtol=1e-05)
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327


class UnHashableObject:
    def __init__(self, val):
        self.val = val

    def __hash__(self):
        raise TypeError("Unsupported to call hash()")


class TestCompatibleNonTensorSpec(unittest.TestCase):
    def test_case(self):
        self.assertTrue(_compatible_non_tensor_spec([1, 2, 3], [1, 2, 3]))
        self.assertFalse(_compatible_non_tensor_spec([1, 2, 3], [1, 2]))
        self.assertFalse(_compatible_non_tensor_spec([1, 2, 3], [1, 3, 2]))

        # not supported unhashable object.
        self.assertTrue(
328 329 330 331
            _compatible_non_tensor_spec(
                UnHashableObject(1), UnHashableObject(1)
            )
        )
332 333


334 335
if __name__ == '__main__':
    unittest.main()