test_ofa.py 14.5 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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.

import sys
sys.path.append("../")
import numpy as np
import unittest
import paddle
C
ceci3 已提交
20
import paddle.nn as nn
C
ceci3 已提交
21 22 23 24
from paddle.nn import ReLU
from paddleslim.nas import ofa
from paddleslim.nas.ofa import OFA, RunConfig, DistillConfig
from paddleslim.nas.ofa.convert_super import supernet
25
from paddleslim.nas.ofa.layers import Block, SuperSeparableConv2D
C
ceci3 已提交
26 27


C
ceci3 已提交
28
class ModelConv(nn.Layer):
C
ceci3 已提交
29 30 31 32 33 34 35
    def __init__(self):
        super(ModelConv, self).__init__()
        with supernet(
                kernel_size=(3, 5, 7),
                channel=((4, 8, 12), (8, 12, 16), (8, 12, 16),
                         (8, 12, 16))) as ofa_super:
            models = []
C
ceci3 已提交
36
            models += [nn.Conv2D(3, 4, 3, padding=1)]
C
ceci3 已提交
37
            models += [nn.InstanceNorm2D(4)]
C
ceci3 已提交
38 39
            models += [ReLU()]
            models += [nn.Conv2D(4, 4, 3, groups=4)]
C
ceci3 已提交
40
            models += [nn.InstanceNorm2D(4)]
C
ceci3 已提交
41
            models += [ReLU()]
C
ceci3 已提交
42 43
            models += [nn.Conv2DTranspose(4, 4, 3, groups=4, padding=1)]
            models += [nn.BatchNorm2D(4)]
C
ceci3 已提交
44 45 46 47 48 49 50 51
            models += [ReLU()]
            models += [nn.Conv2D(4, 3, 3)]
            models += [ReLU()]
            models = ofa_super.convert(models)

        models += [
            Block(
                SuperSeparableConv2D(
C
ceci3 已提交
52 53
                    3, 6, 1, padding=1, candidate_config={'channel': (3, 6)}),
                fixed=True)
C
ceci3 已提交
54 55 56 57 58
        ]
        with supernet(
                kernel_size=(3, 5, 7), expand_ratio=(1, 2, 4)) as ofa_super:
            models1 = []
            models1 += [nn.Conv2D(6, 4, 3)]
C
ceci3 已提交
59
            models1 += [nn.BatchNorm2D(4)]
C
ceci3 已提交
60 61
            models1 += [ReLU()]
            models1 += [nn.Conv2D(4, 4, 3, groups=2)]
C
ceci3 已提交
62
            models1 += [nn.InstanceNorm2D(4)]
C
ceci3 已提交
63 64
            models1 += [ReLU()]
            models1 += [nn.Conv2DTranspose(4, 4, 3, groups=2)]
C
ceci3 已提交
65
            models1 += [nn.BatchNorm2D(4)]
C
ceci3 已提交
66 67
            models1 += [ReLU()]
            models1 += [nn.Conv2DTranspose(4, 4, 3)]
C
ceci3 已提交
68 69 70 71
            models1 += [nn.BatchNorm2D(4)]
            models1 += [ReLU()]
            models1 += [nn.Conv2DTranspose(4, 4, 1)]
            models1 += [nn.BatchNorm2D(4)]
C
ceci3 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
            models1 += [ReLU()]
            models1 = ofa_super.convert(models1)

        models += models1
        self.models = paddle.nn.Sequential(*models)

    def forward(self, inputs, depth=None):
        if depth != None:
            assert isinstance(depth, int)
            assert depth <= len(self.models)
        else:
            depth = len(self.models)
        for idx in range(depth):
            layer = self.models[idx]
            inputs = layer(inputs)
        return inputs


C
ceci3 已提交
90 91 92 93 94
class ModelConv2(nn.Layer):
    def __init__(self):
        super(ModelConv2, self).__init__()
        with supernet(expand_ratio=(1, 2, 4)) as ofa_super:
            models = []
C
ceci3 已提交
95 96 97 98 99 100 101 102 103 104
            models += [
                nn.Conv2DTranspose(
                    4, 4, 3, weight_attr=paddle.ParamAttr(name='conv1_w'))
            ]
            models += [
                nn.BatchNorm2D(
                    4,
                    weight_attr=paddle.ParamAttr(name='bn1_w'),
                    bias_attr=paddle.ParamAttr(name='bn1_b'))
            ]
C
ceci3 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            models += [ReLU()]
            models += [nn.Conv2D(4, 4, 3)]
            models += [nn.BatchNorm2D(4)]
            models += [ReLU()]
            models = ofa_super.convert(models)

        with supernet(channel=((4, 6, 8), (4, 6, 8))) as ofa_super:
            models1 = []
            models1 += [nn.Conv2DTranspose(4, 4, 3)]
            models1 += [nn.BatchNorm2D(4)]
            models1 += [ReLU()]
            models1 += [nn.Conv2DTranspose(4, 4, 3)]
            models1 += [nn.BatchNorm2D(4)]
            models1 += [ReLU()]
            models1 = ofa_super.convert(models1)
        models += models1

        with supernet(kernel_size=(3, 5, 7)) as ofa_super:
            models2 = []
            models2 += [nn.Conv2D(4, 4, 3)]
            models2 += [nn.BatchNorm2D(4)]
            models2 += [ReLU()]
            models2 += [nn.Conv2DTranspose(4, 4, 3)]
            models2 += [nn.BatchNorm2D(4)]
            models2 += [ReLU()]
            models2 += [nn.Conv2D(4, 4, 3)]
            models2 += [nn.BatchNorm2D(4)]
            models2 += [ReLU()]
            models2 = ofa_super.convert(models2)

        models += models2
        self.models = paddle.nn.Sequential(*models)


class ModelLinear(nn.Layer):
C
ceci3 已提交
140 141
    def __init__(self):
        super(ModelLinear, self).__init__()
142
        with supernet(expand_ratio=(1.0, 2.0, 4.0)) as ofa_super:
C
ceci3 已提交
143 144 145 146 147 148 149
            models = []
            models += [nn.Embedding(num_embeddings=64, embedding_dim=64)]
            models += [nn.Linear(64, 128)]
            models += [nn.LayerNorm(128)]
            models += [nn.Linear(128, 256)]
            models = ofa_super.convert(models)

C
ceci3 已提交
150 151
        with supernet(expand_ratio=(1, 2, 4)) as ofa_super:
            models1 = []
C
ceci3 已提交
152
            models1 += [nn.Linear(256, 256)]
C
ceci3 已提交
153 154 155
            models1 = ofa_super.convert(models1)

        models += models1
C
ceci3 已提交
156 157 158 159 160 161 162 163 164 165 166 167
        self.models = paddle.nn.Sequential(*models)

    def forward(self, inputs, depth=None):
        if depth != None:
            assert isinstance(depth, int)
            assert depth < len(self.models)
        else:
            depth = len(self.models)
        for idx in range(depth):
            layer = self.models[idx]
            inputs = layer(inputs)
        return inputs
C
ceci3 已提交
168

C
ceci3 已提交
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
class ModelOriginLinear(nn.Layer):
    def __init__(self):
        super(ModelOriginLinear, self).__init__()
        models = []
        models += [nn.Embedding(num_embeddings=64, embedding_dim=64)]
        models += [nn.Linear(64, 128)]
        models += [nn.LayerNorm(128)]
        models += [nn.Linear(128, 256)]
        models += [nn.Linear(256, 256)]

        self.models = paddle.nn.Sequential(*models)

    def forward(self, inputs):
        return self.models(inputs)


C
ceci3 已提交
186
class ModelLinear1(nn.Layer):
C
ceci3 已提交
187 188 189 190
    def __init__(self):
        super(ModelLinear1, self).__init__()
        with supernet(channel=((64, 128, 256), (64, 128, 256),
                               (64, 128, 256))) as ofa_super:
C
ceci3 已提交
191 192 193 194 195 196 197 198
            models = []
            models += [nn.Embedding(num_embeddings=64, embedding_dim=64)]
            models += [nn.Linear(64, 128)]
            models += [nn.LayerNorm(128)]
            models += [nn.Linear(128, 256)]
            models = ofa_super.convert(models)

        with supernet(channel=((64, 128, 256), )) as ofa_super:
C
ceci3 已提交
199
            models1 = []
C
ceci3 已提交
200
            models1 += [nn.Linear(256, 256)]
C
ceci3 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
            models1 = ofa_super.convert(models1)

        models += models1

        self.models = paddle.nn.Sequential(*models)

    def forward(self, inputs, depth=None):
        if depth != None:
            assert isinstance(depth, int)
            assert depth < len(self.models)
        else:
            depth = len(self.models)
        for idx in range(depth):
            layer = self.models[idx]
            inputs = layer(inputs)
        return inputs


C
ceci3 已提交
219
class ModelLinear2(nn.Layer):
C
ceci3 已提交
220 221 222
    def __init__(self):
        super(ModelLinear2, self).__init__()
        with supernet(expand_ratio=None) as ofa_super:
C
ceci3 已提交
223
            models = []
C
ceci3 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
            models += [
                nn.Embedding(
                    num_embeddings=64,
                    embedding_dim=64,
                    weight_attr=paddle.ParamAttr(name='emb'))
            ]
            models += [
                nn.Linear(
                    64,
                    128,
                    weight_attr=paddle.ParamAttr(name='fc1_w'),
                    bias_attr=paddle.ParamAttr(name='fc1_b'))
            ]
            models += [
                nn.LayerNorm(
                    128,
                    weight_attr=paddle.ParamAttr(name='ln1_w'),
                    bias_attr=paddle.ParamAttr(name='ln1_b'))
            ]
C
ceci3 已提交
243 244
            models += [nn.Linear(128, 256)]
            models = ofa_super.convert(models)
C
ceci3 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        self.models = paddle.nn.Sequential(*models)

    def forward(self, inputs, depth=None):
        if depth != None:
            assert isinstance(depth, int)
            assert depth < len(self.models)
        else:
            depth = len(self.models)
        for idx in range(depth):
            layer = self.models[idx]
            inputs = layer(inputs)
        return inputs


class TestOFA(unittest.TestCase):
C
ceci3 已提交
260 261 262 263 264 265 266 267 268 269
    def setUp(self):
        self.init_model_and_data()
        self.init_config()

    def init_model_and_data(self):
        self.model = ModelConv()
        self.teacher_model = ModelConv()
        data_np = np.random.random((1, 3, 10, 10)).astype(np.float32)
        label_np = np.random.random((1)).astype(np.float32)

C
ceci3 已提交
270
        self.data = paddle.to_tensor(data_np)
C
ceci3 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

    def init_config(self):
        default_run_config = {
            'train_batch_size': 1,
            'n_epochs': [[1], [2, 3], [4, 5]],
            'init_learning_rate': [[0.001], [0.003, 0.001], [0.003, 0.001]],
            'dynamic_batch_size': [1, 1, 1],
            'total_images': 1,
            'elastic_depth': (5, 15, 24)
        }
        self.run_config = RunConfig(**default_run_config)

        default_distill_config = {
            'lambda_distill': 0.01,
            'teacher_model': self.teacher_model,
C
ceci3 已提交
286 287
            'mapping_layers': ['models.0.fn'],
            'mapping_op': 'conv2d'
C
ceci3 已提交
288 289
        }
        self.distill_config = DistillConfig(**default_distill_config)
C
ceci3 已提交
290
        self.elastic_order = ['kernel_size', 'width', 'depth']
C
ceci3 已提交
291 292 293 294

    def test_ofa(self):
        ofa_model = OFA(self.model,
                        self.run_config,
C
ceci3 已提交
295 296
                        distill_config=self.distill_config,
                        elastic_order=self.elastic_order)
C
ceci3 已提交
297 298 299 300 301 302

        start_epoch = 0
        for idx in range(len(self.run_config.n_epochs)):
            cur_idx = self.run_config.n_epochs[idx]
            for ph_idx in range(len(cur_idx)):
                cur_lr = self.run_config.init_learning_rate[idx][ph_idx]
C
ceci3 已提交
303
                adam = paddle.optimizer.Adam(
C
ceci3 已提交
304
                    learning_rate=cur_lr,
C
ceci3 已提交
305
                    parameters=(ofa_model.parameters() + ofa_model.netAs_param))
C
ceci3 已提交
306 307
                for epoch_id in range(start_epoch,
                                      self.run_config.n_epochs[idx][ph_idx]):
C
ceci3 已提交
308 309
                    if epoch_id == 0:
                        ofa_model.set_epoch(epoch_id)
C
ceci3 已提交
310 311 312
                    for model_no in range(self.run_config.dynamic_batch_size[
                            idx]):
                        output, _ = ofa_model(self.data)
C
ceci3 已提交
313
                        loss = paddle.mean(output)
C
ceci3 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
                        if self.distill_config.mapping_layers != None:
                            dis_loss = ofa_model.calc_distill_loss()
                            loss += dis_loss
                            dis_loss = dis_loss.numpy()[0]
                        else:
                            dis_loss = 0
                        print('epoch: {}, loss: {}, distill loss: {}'.format(
                            epoch_id, loss.numpy()[0], dis_loss))
                        loss.backward()
                        adam.minimize(loss)
                        adam.clear_gradients()
                start_epoch = self.run_config.n_epochs[idx][ph_idx]


class TestOFACase1(TestOFA):
    def init_model_and_data(self):
        self.model = ModelLinear()
        self.teacher_model = ModelLinear()
C
ceci3 已提交
332
        data_np = np.random.random((3, 64)).astype(np.int64)
C
ceci3 已提交
333
        self.data = paddle.to_tensor(data_np)
C
ceci3 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347

    def init_config(self):
        default_run_config = {
            'train_batch_size': 1,
            'n_epochs': [[2, 5]],
            'init_learning_rate': [[0.003, 0.001]],
            'dynamic_batch_size': [1],
            'total_images': 1,
        }
        self.run_config = RunConfig(**default_run_config)

        default_distill_config = {
            'lambda_distill': 0.01,
            'teacher_model': self.teacher_model,
C
ceci3 已提交
348 349
            'mapping_op': 'linear',
            'mapping_layers': ['models.3.fn'],
C
ceci3 已提交
350 351
        }
        self.distill_config = DistillConfig(**default_distill_config)
C
ceci3 已提交
352 353 354
        self.elastic_order = None


C
ceci3 已提交
355
class TestOFACase2(TestOFA):
C
ceci3 已提交
356 357 358 359 360
    def init_model_and_data(self):
        self.model = ModelLinear1()
        self.teacher_model = ModelLinear1()
        data_np = np.random.random((3, 64)).astype(np.int64)

C
ceci3 已提交
361
        self.data = paddle.to_tensor(data_np)
C
ceci3 已提交
362

C
ceci3 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    def init_config(self):
        default_run_config = {
            'train_batch_size': 1,
            'n_epochs': [[2, 5]],
            'init_learning_rate': [[0.003, 0.001]],
            'dynamic_batch_size': [1],
            'total_images': 1,
        }
        self.run_config = RunConfig(**default_run_config)
        default_distill_config = {
            'teacher_model': self.teacher_model,
            'mapping_layers': ['models.3.fn'],
        }
        self.distill_config = DistillConfig(**default_distill_config)
        self.elastic_order = None

C
ceci3 已提交
379 380 381 382 383 384

class TestOFACase3(unittest.TestCase):
    def test_ofa(self):
        self.model = ModelLinear2()
        ofa_model = OFA(self.model)
        ofa_model.set_net_config({'expand_ratio': None})
C
ceci3 已提交
385 386


C
ceci3 已提交
387
class TestOFACase4(unittest.TestCase):
C
ceci3 已提交
388 389 390 391
    def test_ofa(self):
        self.model = ModelConv2()


392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
class TestExport(unittest.TestCase):
    def setUp(self):
        self._init_model()

    def _init_model(self):
        self.origin_model = ModelOriginLinear()
        model = ModelLinear()
        self.ofa_model = OFA(model)

    def test_ofa(self):
        config = {
            'embedding_1': {
                'expand_ratio': (2.0)
            },
            'linear_3': {
                'expand_ratio': (2.0)
            },
            'linear_4': {},
            'linear_5': {}
        }
        origin_dict = {}
        for name, param in self.origin_model.named_parameters():
            origin_dict[name] = param.shape
        self.ofa_model.export(
            self.origin_model,
            config,
            input_shapes=[[1, 64]],
            input_dtypes=['int64'])
        for name, param in self.origin_model.named_parameters():
            if name in config.keys():
                if 'expand_ratio' in config[name]:
                    assert origin_dict[name][-1] == param.shape[-1] * config[
                        name]['expand_ratio']


C
ceci3 已提交
427 428
if __name__ == '__main__':
    unittest.main()