test_model_speedup.py 20 KB
Newer Older
chicm-ms's avatar
chicm-ms committed
1
2
3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

Ningxin Zheng's avatar
Ningxin Zheng committed
4
import logging
chicm-ms's avatar
chicm-ms committed
5
import os
Ningxin Zheng's avatar
Ningxin Zheng committed
6
import gc
7
import psutil
8
import sys
chicm-ms's avatar
chicm-ms committed
9
10
import numpy as np
import torch
11
import torchvision.models as models
chicm-ms's avatar
chicm-ms committed
12
13
import torch.nn as nn
import torch.nn.functional as F
Ningxin Zheng's avatar
Ningxin Zheng committed
14
from torchvision.models.vgg import vgg16, vgg11
chicm-ms's avatar
chicm-ms committed
15
from torchvision.models.resnet import resnet18
Ningxin Zheng's avatar
Ningxin Zheng committed
16
from torchvision.models.mobilenet import mobilenet_v2
17
import unittest
chicm-ms's avatar
chicm-ms committed
18
19
from unittest import TestCase, main

liuzhe-lz's avatar
liuzhe-lz committed
20
from nni.compression.pytorch import ModelSpeedup, apply_compression_results
Ningxin Zheng's avatar
Ningxin Zheng committed
21
from nni.algorithms.compression.pytorch.pruning import L1FilterPruner, LevelPruner
22
from nni.algorithms.compression.pytorch.pruning.weight_masker import WeightMasker
23
from nni.algorithms.compression.pytorch.pruning.dependency_aware_pruner import DependencyAwarePruner
chicm-ms's avatar
chicm-ms committed
24

chicm-ms's avatar
chicm-ms committed
25
torch.manual_seed(0)
26
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
Ningxin Zheng's avatar
Ningxin Zheng committed
27

28
29
30
31
32
33
34
35
36
37
BATCH_SIZE = 2
# the relative distance
RELATIVE_THRESHOLD = 0.01
# Because of the precision of floating-point numbers, some errors
# between the original output tensors(without speedup) and the output
# tensors of the speedup model are normal. When the output tensor itself
# is small, such errors may exceed the relative threshold, so we also add
# an absolute threshold to determine whether the final result is correct.
# The error should meet the RELATIVE_THREHOLD or the ABSOLUTE_THRESHOLD.
ABSOLUTE_THRESHOLD = 0.0001
38
39


chicm-ms's avatar
chicm-ms committed
40
41
42
43
class BackboneModel1(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 1, 1, 1)
44

chicm-ms's avatar
chicm-ms committed
45
46
47
    def forward(self, x):
        return self.conv1(x)

48

chicm-ms's avatar
chicm-ms committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class BackboneModel2(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5, 1)
        self.conv2 = nn.Conv2d(20, 50, 5, 1)
        self.bn1 = nn.BatchNorm2d(self.conv1.out_channels)
        self.bn2 = nn.BatchNorm2d(self.conv2.out_channels)
        self.fc1 = nn.Linear(4 * 4 * 50, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(x.size(0), -1)
65

chicm-ms's avatar
chicm-ms committed
66
67
68
69
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

70

chicm-ms's avatar
chicm-ms committed
71
72
73
74
75
class BigModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.backbone1 = BackboneModel1()
        self.backbone2 = BackboneModel2()
76
        self.fc3 = nn.Sequential(
chicm-ms's avatar
chicm-ms committed
77
78
79
80
81
            nn.Linear(10, 10),
            nn.BatchNorm1d(10),
            nn.ReLU(inplace=True),
            nn.Linear(10, 2)
        )
82

chicm-ms's avatar
chicm-ms committed
83
84
85
86
87
88
    def forward(self, x):
        x = self.backbone1(x)
        x = self.backbone2(x)
        x = self.fc3(x)
        return x

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

class TransposeModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 20, 5)
        self.conv2 = nn.ConvTranspose2d(20, 50, 5, groups=2)
        self.bn1 = nn.BatchNorm2d(self.conv1.out_channels)
        self.bn2 = nn.BatchNorm2d(self.conv2.out_channels)
        self.fc1 = nn.Linear(8 * 8 * 50, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        # x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.bn2(self.conv2(x)))
        # x = F.max_pool2d(x, 2, 2)
        x = x.view(x.size(0), -1)

        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x


Ningxin Zheng's avatar
Ningxin Zheng committed
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
class TupleUnpack_backbone(nn.Module):
    def __init__(self, width):
        super(TupleUnpack_backbone, self).__init__()
        self.model_backbone = mobilenet_v2(
            pretrained=False, width_mult=width, num_classes=3)

    def forward(self, x):
        x1 = self.model_backbone.features[:7](x)
        x2 = self.model_backbone.features[7:14](x1)
        x3 = self.model_backbone.features[14:18](x2)
        return [x1, x2, x3]


class TupleUnpack_FPN(nn.Module):
    def __init__(self):
        super(TupleUnpack_FPN, self).__init__()

        self.conv1 = nn.Conv2d(32, 48, kernel_size=(
            1, 1), stride=(1, 1), bias=False)
        self.conv2 = nn.Conv2d(96, 48, kernel_size=(
            1, 1), stride=(1, 1), bias=False)
        self.conv3 = nn.Conv2d(320, 48, kernel_size=(
            1, 1), stride=(1, 1), bias=False)

        # self.init_weights()

    def forward(self, inputs):
        """Forward function."""
        laterals = []

        laterals.append(self.conv1(inputs[0]))  # inputs[0]==x1
        laterals.append(self.conv2(inputs[1]))  # inputs[1]==x2
        laterals.append(self.conv3(inputs[2]))  # inputs[2]==x3

        return laterals


class TupleUnpack_Model(nn.Module):
    def __init__(self):
        super(TupleUnpack_Model, self).__init__()
        self.backbone = TupleUnpack_backbone(1.0)
        self.fpn = TupleUnpack_FPN()

    def forward(self, x):
        x1 = self.backbone(x)
        out = self.fpn(x1)
        return out


chicm-ms's avatar
chicm-ms committed
161
dummy_input = torch.randn(2, 1, 28, 28)
chicm-ms's avatar
chicm-ms committed
162
SPARSITY = 0.5
chicm-ms's avatar
chicm-ms committed
163
164
MODEL_FILE, MASK_FILE = './11_model.pth', './l1_mask.pth'

165

chicm-ms's avatar
chicm-ms committed
166
167
168
169
170
171
172
def prune_model_l1(model):
    config_list = [{
        'sparsity': SPARSITY,
        'op_types': ['Conv2d']
    }]
    pruner = L1FilterPruner(model, config_list)
    pruner.compress()
chicm-ms's avatar
chicm-ms committed
173
    pruner.export_model(model_path=MODEL_FILE, mask_path=MASK_FILE)
chicm-ms's avatar
chicm-ms committed
174

175

176
def generate_random_sparsity(model):
177
178
179
180
181
182
183
184
    _start = 0.5
    _end = 0.99
    if isinstance(model, models.mobilenet.MobileNetV2):
        # mobilenet models have great propagation characteristics
        # so we use smaller sparsity ratio to avoid pruning the whole
        # layer out
        _start = 0.01
        _end = 0.3
185
186
187
    cfg_list = []
    for name, module in model.named_modules():
        if isinstance(module, nn.Conv2d):
188
            sparsity = np.random.uniform(_start, _end)
189
190
191
192
            cfg_list.append({'op_types': ['Conv2d'], 'op_names': [name],
                             'sparsity': sparsity})
    return cfg_list

Ningxin Zheng's avatar
Ningxin Zheng committed
193

194
195
196
197
def generate_random_sparsity_v2(model):
    """
    Only select 50% layers to prune.
    """
198
199
200
201
202
203
204
205
    _start = 0.5
    _end = 0.99
    if isinstance(model, models.mobilenet.MobileNetV2):
        # mobilenet models have great propagation characteristics
        # so we use smaller sparsity ratio to avoid pruning the whole
        # layer out
        _start = 0.01
        _end = 0.3
206
207
208
209
    cfg_list = []
    for name, module in model.named_modules():
        if isinstance(module, nn.Conv2d):
            if np.random.uniform(0, 1.0) > 0.5:
210
                sparsity = np.random.uniform(_start, _end)
211
                cfg_list.append({'op_types': ['Conv2d'], 'op_names': [name],
Ningxin Zheng's avatar
Ningxin Zheng committed
212
                                 'sparsity': sparsity})
213
    return cfg_list
214

Ningxin Zheng's avatar
Ningxin Zheng committed
215

216
217
218
219
def zero_bn_bias(model):
    with torch.no_grad():
        for name, module in model.named_modules():
            if isinstance(module, nn.BatchNorm2d) \
220
221
                    or isinstance(module, nn.BatchNorm3d) \
                    or isinstance(module, nn.BatchNorm1d):
222
223
224
225
226
227
                shape = module.bias.data.size()
                device = module.bias.device
                module.bias.data = torch.zeros(shape).to(device)
                shape = module.running_mean.data.size()
                module.running_mean = torch.zeros(shape).to(device)

228

229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class L1ChannelMasker(WeightMasker):
    def __init__(self, model, pruner):
        self.model = model
        self.pruner = pruner

    def calc_mask(self, sparsity, wrapper, wrapper_idx=None):
        msg = 'module type {} is not supported!'.format(wrapper.type)
        #assert wrapper.type == 'Conv2d', msg
        weight = wrapper.module.weight.data
        bias = None
        if hasattr(wrapper.module, 'bias') and wrapper.module.bias is not None:
            bias = wrapper.module.bias.data

        if wrapper.weight_mask is None:
            mask_weight = torch.ones(weight.size()).type_as(weight).detach()
        else:
            mask_weight = wrapper.weight_mask.clone()
        if bias is not None:
            if wrapper.bias_mask is None:
                mask_bias = torch.ones(bias.size()).type_as(bias).detach()
            else:
                mask_bias = wrapper.bias_mask.clone()
        else:
            mask_bias = None
        base_mask = {'weight_mask': mask_weight, 'bias_mask': mask_bias}

        num_total = weight.size(1)
        num_prune = int(num_total * sparsity)

        if num_total < 2 or num_prune < 1:
            return base_mask
        w_abs = weight.abs()
        if wrapper.type == 'Conv2d':
            w_abs_structured = w_abs.sum((0, 2, 3))
263
264
265
266
            threshold = torch.topk(
                w_abs_structured, num_prune, largest=False)[0].max()
            mask_weight = torch.gt(w_abs_structured, threshold)[
                None, :, None, None].expand_as(weight).type_as(weight)
267
268
269
270
271
            return {'weight_mask': mask_weight.detach()}
        else:
            # Linear
            assert wrapper.type == 'Linear'
            w_abs_structured = w_abs.sum((0))
272
273
274
275
            threshold = torch.topk(
                w_abs_structured, num_prune, largest=False)[0].max()
            mask_weight = torch.gt(w_abs_structured, threshold)[
                None, :].expand_as(weight).type_as(weight)
276
277
            return {'weight_mask': mask_weight.detach(), 'bias_mask': mask_bias}

278

279
class L1ChannelPruner(DependencyAwarePruner):
280
281
282
    def __init__(self, model, config_list, optimizer=None, dependency_aware=False, dummy_input=None):
        super().__init__(model, config_list, pruning_algorithm='l1', optimizer=optimizer,
                         dependency_aware=dependency_aware, dummy_input=dummy_input)
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    def validate_config(self, model, config_list):
        pass


def channel_prune(model):
    config_list = [{
        'sparsity': SPARSITY,
        'op_types': ['Conv2d', 'Linear']
    }, {
        'op_names': ['conv1'],
        'exclude': True
    }]

    pruner = L1ChannelPruner(model, config_list)
    masker = L1ChannelMasker(model, pruner)
    pruner.masker = masker
    pruner.compress()
    pruner.export_model(model_path=MODEL_FILE, mask_path=MASK_FILE)

303

chicm-ms's avatar
chicm-ms committed
304
305
306
307
308
class SpeedupTestCase(TestCase):

    def test_speedup_bigmodel(self):
        prune_model_l1(BigModel())
        model = BigModel()
chicm-ms's avatar
chicm-ms committed
309
310
311
312
        apply_compression_results(model, MASK_FILE, 'cpu')
        model.eval()
        mask_out = model(dummy_input)

chicm-ms's avatar
chicm-ms committed
313
        model.train()
314
        ms = ModelSpeedup(model, dummy_input, MASK_FILE, confidence=8)
chicm-ms's avatar
chicm-ms committed
315
        ms.speedup_model()
chicm-ms's avatar
chicm-ms committed
316
317
318
319
320
        assert model.training

        model.eval()
        speedup_out = model(dummy_input)
        if not torch.allclose(mask_out, speedup_out, atol=1e-07):
321
322
            print('input:', dummy_input.size(),
                  torch.abs(dummy_input).sum((2, 3)))
chicm-ms's avatar
chicm-ms committed
323
324
325
            print('mask_out:', mask_out)
            print('speedup_out:', speedup_out)
            raise RuntimeError('model speedup inference result is incorrect!')
chicm-ms's avatar
chicm-ms committed
326
327

        orig_model = BigModel()
chicm-ms's avatar
chicm-ms committed
328

329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
        assert model.backbone2.conv1.out_channels == int(
            orig_model.backbone2.conv1.out_channels * SPARSITY)
        assert model.backbone2.conv2.in_channels == int(
            orig_model.backbone2.conv2.in_channels * SPARSITY)
        assert model.backbone2.conv2.out_channels == int(
            orig_model.backbone2.conv2.out_channels * SPARSITY)
        assert model.backbone2.fc1.in_features == int(
            orig_model.backbone2.fc1.in_features * SPARSITY)

    def test_convtranspose_model(self):
        ori_model = TransposeModel()
        dummy_input = torch.rand(1, 3, 8, 8)
        config_list = [{'sparsity': 0.5, 'op_types': ['Conv2d']}]
        pruner = L1FilterPruner(ori_model, config_list)
        pruner.compress()
        ori_model(dummy_input)
        pruner.export_model(MODEL_FILE, MASK_FILE)
        pruner._unwrap_model()
        new_model = TransposeModel()
        state_dict = torch.load(MODEL_FILE)
        new_model.load_state_dict(state_dict)
350
        ms = ModelSpeedup(new_model, dummy_input, MASK_FILE, confidence=8)
351
352
353
354
355
356
357
        ms.speedup_model()
        zero_bn_bias(ori_model)
        zero_bn_bias(new_model)
        ori_out = ori_model(dummy_input)
        new_out = new_model(dummy_input)
        ori_sum = torch.sum(ori_out)
        speeded_sum = torch.sum(new_out)
Ningxin Zheng's avatar
Ningxin Zheng committed
358
359
        print('Tanspose Speedup Test: ori_sum={} speedup_sum={}'.format(
            ori_sum, speeded_sum))
360
        assert (abs(ori_sum - speeded_sum) / abs(ori_sum) < RELATIVE_THRESHOLD) or \
Ningxin Zheng's avatar
Ningxin Zheng committed
361
            (abs(ori_sum - speeded_sum) < ABSOLUTE_THRESHOLD)
362

Ningxin Zheng's avatar
Ningxin Zheng committed
363
364
365
366
367
    def test_speedup_integration_small(self):
        model_list = ['resnet18', 'mobilenet_v2', 'alexnet']
        self.speedup_integration(model_list)

    def test_speedup_integration_big(self):
J-shang's avatar
J-shang committed
368
369
        # TODO: will revert vgg16, resnet50, wide_resnet50_2 after confidence refactor
        model_list = ['vgg11', 'resnet34', 'squeezenet1_1', 'densenet121']
Ningxin Zheng's avatar
Ningxin Zheng committed
370
371
372
373
374
375
        mem_info = psutil.virtual_memory()
        ava_gb = mem_info.available/1024.0/1024/1024
        print('Avaliable memory size: %.2f GB' % ava_gb)
        if ava_gb < 8.0:
            # memory size is too small that we may run into an OOM exception
            # Skip this test in the pipeline test due to memory limitation
376
            return
Ningxin Zheng's avatar
Ningxin Zheng committed
377
        self.speedup_integration(model_list)
378

Ningxin Zheng's avatar
Ningxin Zheng committed
379
    def speedup_integration(self, model_list, speedup_cfg=None):
380
381
382
383
        # Note: hack trick, may be updated in the future
        if 'win' in sys.platform or 'Win'in sys.platform:
            print('Skip test_speedup_integration on windows due to memory limit!')
            return
384
385
        Gen_cfg_funcs = [generate_random_sparsity, generate_random_sparsity_v2]

Ningxin Zheng's avatar
Ningxin Zheng committed
386
387
388
389
        # for model_name in ['vgg16', 'resnet18', 'mobilenet_v2', 'squeezenet1_1', 'densenet121',
        #                    # 'inception_v3' inception is too large and may fail the pipeline
        #                     'resnet50']:
        for model_name in model_list:
390
            for gen_cfg_func in Gen_cfg_funcs:
391
                kwargs = {
392
                    'pretrained': True
393
                }
394
395
396
397
398
399
400
401
402
403
404
405
406
                if model_name == 'resnet50':
                    # testing multiple groups
                    kwargs = {
                        'pretrained': False,
                        'groups': 4
                    }
                Model = getattr(models, model_name)
                net = Model(**kwargs).to(device)
                speedup_model = Model(**kwargs).to(device)
                net.eval()  # this line is necessary
                speedup_model.eval()
                # random generate the prune config for the pruner
                cfgs = gen_cfg_func(net)
Ningxin Zheng's avatar
Ningxin Zheng committed
407
408
409
410
                print("Testing {} with compression config \n {}".format(
                    model_name, cfgs))
                if len(cfgs) == 0:
                    continue
411
412
413
414
415
416
417
418
419
420
                pruner = L1FilterPruner(net, cfgs)
                pruner.compress()
                pruner.export_model(MODEL_FILE, MASK_FILE)
                pruner._unwrap_model()
                state_dict = torch.load(MODEL_FILE)
                speedup_model.load_state_dict(state_dict)
                zero_bn_bias(net)
                zero_bn_bias(speedup_model)

                data = torch.ones(BATCH_SIZE, 3, 128, 128).to(device)
Ningxin Zheng's avatar
Ningxin Zheng committed
421
422
423
                if speedup_cfg is None:
                    speedup_cfg = {}
                ms = ModelSpeedup(speedup_model, data,
J-shang's avatar
J-shang committed
424
425
                                  MASK_FILE, confidence=4, **speedup_cfg)

426
427
428
429
430
431
432
433
434
                ms.speedup_model()

                speedup_model.eval()

                ori_out = net(data)
                speeded_out = speedup_model(data)
                ori_sum = torch.sum(ori_out).item()
                speeded_sum = torch.sum(speeded_out).item()
                print('Sum of the output of %s (before speedup):' %
Ningxin Zheng's avatar
Ningxin Zheng committed
435
436
437
                      model_name, ori_sum)
                print('Sum of the output of %s (after  speedup):' %
                      model_name, speeded_sum)
438
439
                assert (abs(ori_sum - speeded_sum) / abs(ori_sum) < RELATIVE_THRESHOLD) or \
                    (abs(ori_sum - speeded_sum) < ABSOLUTE_THRESHOLD)
Ningxin Zheng's avatar
Ningxin Zheng committed
440
441
                print("Collecting Garbage")
                gc.collect(2)
442

443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    def test_channel_prune(self):
        orig_net = resnet18(num_classes=10).to(device)
        channel_prune(orig_net)
        state_dict = torch.load(MODEL_FILE)

        orig_net = resnet18(num_classes=10).to(device)
        orig_net.load_state_dict(state_dict)
        apply_compression_results(orig_net, MASK_FILE)
        orig_net.eval()

        net = resnet18(num_classes=10).to(device)

        net.load_state_dict(state_dict)
        net.eval()

liuzhe-lz's avatar
liuzhe-lz committed
458
        data = torch.randn(BATCH_SIZE, 3, 128, 128).to(device)
459
        ms = ModelSpeedup(net, data, MASK_FILE, confidence=8)
460
461
462
463
464
465
466
467
468
469
470
471
        ms.speedup_model()
        ms.bound_model(data)

        net.eval()

        ori_sum = orig_net(data).abs().sum().item()
        speeded_sum = net(data).abs().sum().item()

        print(ori_sum, speeded_sum)
        assert (abs(ori_sum - speeded_sum) / abs(ori_sum) < RELATIVE_THRESHOLD) or \
            (abs(ori_sum - speeded_sum) < ABSOLUTE_THRESHOLD)

Ningxin Zheng's avatar
Ningxin Zheng committed
472
473
474
475
476
477
478
479
480
    def test_speedup_tupleunpack(self):
        """This test is reported in issue3645"""
        model = TupleUnpack_Model()
        cfg_list = [{'op_types': ['Conv2d'], 'sparsity':0.5}]
        dummy_input = torch.rand(2, 3, 224, 224)
        pruner = L1FilterPruner(model, cfg_list)
        pruner.compress()
        model(dummy_input)
        pruner.export_model(MODEL_FILE, MASK_FILE)
481
        ms = ModelSpeedup(model, dummy_input, MASK_FILE, confidence=8)
Ningxin Zheng's avatar
Ningxin Zheng committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
        ms.speedup_model()

    def test_finegrained_speedup(self):
        """ Test the speedup on the fine-grained sparsity"""
        class MLP(nn.Module):
            def __init__(self):
                super(MLP, self).__init__()
                self.fc1 = nn.Linear(1024, 1024)
                self.fc2 = nn.Linear(1024, 1024)
                self.fc3 = nn.Linear(1024, 512)
                self.fc4 = nn.Linear(512, 10)

            def forward(self, x):
                x = x.view(-1, 1024)
                x = self.fc1(x)
                x = self.fc2(x)
                x = self.fc3(x)
                x = self.fc4(x)
                return x
        model = MLP().to(device)
        dummy_input = torch.rand(16, 1, 32, 32).to(device)
        cfg_list = [{'op_types': ['Linear'], 'sparsity':0.99}]
        pruner = LevelPruner(model, cfg_list)
        pruner.compress()
        print('Original Arch')
        print(model)
        pruner.export_model(MODEL_FILE, MASK_FILE)
        pruner._unwrap_model()
510
        ms = ModelSpeedup(model, dummy_input, MASK_FILE, confidence=8)
Ningxin Zheng's avatar
Ningxin Zheng committed
511
512
513
514
        ms.speedup_model()
        print("Fine-grained speeduped model")
        print(model)

Ningxin Zheng's avatar
Ningxin Zheng committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    def test_multiplication_speedup(self):
        """
        Model from issue 4540.
        """
        class Net(torch.nn.Module):
            def __init__(self,):
                super(Net, self).__init__()
                self.avgpool = torch.nn.AdaptiveAvgPool2d(1)
                self.input = torch.nn.Conv2d(3, 8, 3)
                self.bn = torch.nn.BatchNorm2d(8)
                self.fc1 = torch.nn.Conv2d(8, 16, 1)
                self.fc2 = torch.nn.Conv2d(16, 8, 1)
                self.activation = torch.nn.ReLU()
                self.scale_activation = torch.nn.Hardsigmoid()
                self.out = torch.nn.Conv2d(8, 12, 1)

            def forward(self, input):
                input = self.activation(self.bn(self.input(input)))
                scale = self.avgpool(input)
                out1 = self.activation(self.fc1(scale))
                out1 = self.scale_activation(self.fc2(out1))
                return self.out(out1 * input)

        model = Net().to(device)
        model.eval()
        im = torch.ones(1, 3, 512, 512).to(device)
        model(im)
        cfg_list = []

        for name, module in model.named_modules():
            if isinstance(module, torch.nn.Conv2d):
                cfg_list.append({'op_types':['Conv2d'], 'sparsity':0.3, 'op_names':[name]})

        pruner = L1FilterPruner(model, cfg_list)
        pruner.compress()
        pruner.export_model(MODEL_FILE, MASK_FILE)
        pruner._unwrap_model()
        ms=ModelSpeedup(model, im, MASK_FILE)
        ms.speedup_model()

chicm-ms's avatar
chicm-ms committed
555
    def tearDown(self):
556
557
558
559
        if os.path.exists(MODEL_FILE):
            os.remove(MODEL_FILE)
        if os.path.exists(MASK_FILE):
            os.remove(MASK_FILE)
Ningxin Zheng's avatar
Ningxin Zheng committed
560
561
        # GC to release memory
        gc.collect(2)
chicm-ms's avatar
chicm-ms committed
562

563

chicm-ms's avatar
chicm-ms committed
564
565
if __name__ == '__main__':
    main()