test_ofa.py 13.0 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__()
C
ceci3 已提交
142 143 144 145 146 147 148 149
        with supernet(expand_ratio=(1, 2, 4)) as ofa_super:
            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

C
ceci3 已提交
170
class ModelLinear1(nn.Layer):
C
ceci3 已提交
171 172 173 174
    def __init__(self):
        super(ModelLinear1, self).__init__()
        with supernet(channel=((64, 128, 256), (64, 128, 256),
                               (64, 128, 256))) as ofa_super:
C
ceci3 已提交
175 176 177 178 179 180 181 182
            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 已提交
183
            models1 = []
C
ceci3 已提交
184
            models1 += [nn.Linear(256, 256)]
C
ceci3 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
            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 已提交
203
class ModelLinear2(nn.Layer):
C
ceci3 已提交
204 205 206
    def __init__(self):
        super(ModelLinear2, self).__init__()
        with supernet(expand_ratio=None) as ofa_super:
C
ceci3 已提交
207
            models = []
C
ceci3 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            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 已提交
227 228
            models += [nn.Linear(128, 256)]
            models = ofa_super.convert(models)
C
ceci3 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
        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 已提交
244 245 246 247 248 249 250 251 252 253
    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 已提交
254
        self.data = paddle.to_tensor(data_np)
C
ceci3 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

    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 已提交
270 271
            'mapping_layers': ['models.0.fn'],
            'mapping_op': 'conv2d'
C
ceci3 已提交
272 273
        }
        self.distill_config = DistillConfig(**default_distill_config)
C
ceci3 已提交
274
        self.elastic_order = ['kernel_size', 'width', 'depth']
C
ceci3 已提交
275 276 277 278

    def test_ofa(self):
        ofa_model = OFA(self.model,
                        self.run_config,
C
ceci3 已提交
279 280
                        distill_config=self.distill_config,
                        elastic_order=self.elastic_order)
C
ceci3 已提交
281 282 283 284 285 286

        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 已提交
287
                adam = paddle.optimizer.Adam(
C
ceci3 已提交
288
                    learning_rate=cur_lr,
C
ceci3 已提交
289
                    parameters=(ofa_model.parameters() + ofa_model.netAs_param))
C
ceci3 已提交
290 291
                for epoch_id in range(start_epoch,
                                      self.run_config.n_epochs[idx][ph_idx]):
C
ceci3 已提交
292 293
                    if epoch_id == 0:
                        ofa_model.set_epoch(epoch_id)
C
ceci3 已提交
294 295 296
                    for model_no in range(self.run_config.dynamic_batch_size[
                            idx]):
                        output, _ = ofa_model(self.data)
C
ceci3 已提交
297
                        loss = paddle.mean(output)
C
ceci3 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
                        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 已提交
316
        data_np = np.random.random((3, 64)).astype(np.int64)
C
ceci3 已提交
317
        self.data = paddle.to_tensor(data_np)
C
ceci3 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331

    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 已提交
332 333
            'mapping_op': 'linear',
            'mapping_layers': ['models.3.fn'],
C
ceci3 已提交
334 335
        }
        self.distill_config = DistillConfig(**default_distill_config)
C
ceci3 已提交
336 337 338
        self.elastic_order = None


C
ceci3 已提交
339
class TestOFACase2(TestOFA):
C
ceci3 已提交
340 341 342 343 344
    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 已提交
345
        self.data = paddle.to_tensor(data_np)
C
ceci3 已提交
346

C
ceci3 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    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 已提交
363 364 365 366 367 368

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 已提交
369 370


C
ceci3 已提交
371
class TestOFACase4(unittest.TestCase):
C
ceci3 已提交
372 373 374 375
    def test_ofa(self):
        self.model = ModelConv2()


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