pruning_speedup.rst 10.5 KB
Newer Older
J-shang's avatar
J-shang committed
1
2
3
4

.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
5
.. "tutorials/pruning_speedup.py"
J-shang's avatar
J-shang committed
6
7
8
9
10
11
12
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

13
        Click :ref:`here <sphx_glr_download_tutorials_pruning_speedup.py>`
J-shang's avatar
J-shang committed
14
15
16
17
        to download the full example code

.. rst-class:: sphx-glr-example-title

18
.. _sphx_glr_tutorials_pruning_speedup.py:
J-shang's avatar
J-shang committed
19
20


21
Speedup Model with Mask
J-shang's avatar
J-shang committed
22
23
24
25
26
27
28
29
30
31
32
33
========================

Introduction
------------

Pruning algorithms usually use weight masks to simulate the real pruning. Masks can be used
to check model performance of a specific pruning (or sparsity), but there is no real speedup.
Since model speedup is the ultimate goal of model pruning, we try to provide a tool to users
to convert a model to a smaller one based on user provided masks (the masks come from the
pruning algorithms).

There are two types of pruning. One is fine-grained pruning, it does not change the shape of weights,
34
and input/output tensors. Sparse kernel is required to speedup a fine-grained pruned layer.
J-shang's avatar
J-shang committed
35
The other is coarse-grained pruning (e.g., channels), shape of weights and input/output tensors usually change due to such pruning.
36
To speedup this kind of pruning, there is no need to use sparse kernel, just replace the pruned layer with smaller one.
J-shang's avatar
J-shang committed
37
38
39
40
41
42
Since the support of sparse kernels in community is limited,
we only support the speedup of coarse-grained pruning and leave the support of fine-grained pruning in future.

Design and Implementation
-------------------------

43
To speedup a model, the pruned layers should be replaced, either replaced with smaller layer for coarse-grained mask,
J-shang's avatar
J-shang committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
or replaced with sparse kernel for fine-grained mask. Coarse-grained mask usually changes the shape of weights or input/output tensors,
thus, we should do shape inference to check are there other unpruned layers should be replaced as well due to shape change.
Therefore, in our design, there are two main steps: first, do shape inference to find out all the modules that should be replaced;
second, replace the modules.

The first step requires topology (i.e., connections) of the model, we use ``jit.trace`` to obtain the model graph for PyTorch.
The new shape of module is auto-inference by NNI, the unchanged parts of outputs during forward and inputs during backward are prepared for reduct.
For each type of module, we should prepare a function for module replacement.
The module replacement function returns a newly created module which is smaller.

Usage
-----

.. GENERATED FROM PYTHON SOURCE LINES 41-44

Generate a mask for the model at first.
We usually use a NNI pruner to generate the masks then use ``ModelSpeedup`` to compact the model.
But in fact ``ModelSpeedup`` is a relatively independent tool, so you can use it independently.

.. GENERATED FROM PYTHON SOURCE LINES 44-55

.. code-block:: default


    import torch
69
    from nni_assets.compression.mnist_model import TorchModel, device
J-shang's avatar
J-shang committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

    model = TorchModel().to(device)
    # masks = {layer_name: {'weight': weight_mask, 'bias': bias_mask}}
    conv1_mask = torch.ones_like(model.conv1.weight.data)
    # mask the first three output channels in conv1
    conv1_mask[0: 3] = 0
    masks = {'conv1': {'weight': conv1_mask}}








.. GENERATED FROM PYTHON SOURCE LINES 56-57

Show the original model structure.

.. GENERATED FROM PYTHON SOURCE LINES 57-59

.. code-block:: default

    print(model)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    TorchModel(
      (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
      (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
      (fc1): Linear(in_features=256, out_features=120, bias=True)
      (fc2): Linear(in_features=120, out_features=84, bias=True)
      (fc3): Linear(in_features=84, out_features=10, bias=True)
109
110
111
112
113
114
      (relu1): ReLU()
      (relu2): ReLU()
      (relu3): ReLU()
      (relu4): ReLU()
      (pool1): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
      (pool2): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
J-shang's avatar
J-shang committed
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
    )




.. GENERATED FROM PYTHON SOURCE LINES 60-61

Roughly test the original model inference speed.

.. GENERATED FROM PYTHON SOURCE LINES 61-66

.. code-block:: default

    import time
    start = time.time()
    model(torch.rand(128, 1, 28, 28).to(device))
    print('Original Model - Elapsed Time : ', time.time() - start)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

141
    Original Model - Elapsed Time :  0.1178426742553711
J-shang's avatar
J-shang committed
142
143
144
145
146
147




.. GENERATED FROM PYTHON SOURCE LINES 67-68

148
Speedup the model and show the model structure after speedup.
J-shang's avatar
J-shang committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

.. GENERATED FROM PYTHON SOURCE LINES 68-72

.. code-block:: default

    from nni.compression.pytorch import ModelSpeedup
    ModelSpeedup(model, torch.rand(10, 1, 28, 28).to(device), masks).speedup_model()
    print(model)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

166
    /home/ningshang/anaconda3/envs/nni-dev/lib/python3.8/site-packages/torch/_tensor.py:1013: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the .grad field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations. (Triggered internally at  aten/src/ATen/core/TensorBody.h:417.)
J-shang's avatar
J-shang committed
167
168
169
170
171
172
173
      return self._grad
    TorchModel(
      (conv1): Conv2d(1, 3, kernel_size=(5, 5), stride=(1, 1))
      (conv2): Conv2d(3, 16, kernel_size=(5, 5), stride=(1, 1))
      (fc1): Linear(in_features=256, out_features=120, bias=True)
      (fc2): Linear(in_features=120, out_features=84, bias=True)
      (fc3): Linear(in_features=84, out_features=10, bias=True)
174
175
176
177
178
179
      (relu1): ReLU()
      (relu2): ReLU()
      (relu3): ReLU()
      (relu4): ReLU()
      (pool1): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
      (pool2): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
J-shang's avatar
J-shang committed
180
181
182
183
184
185
186
    )




.. GENERATED FROM PYTHON SOURCE LINES 73-74

187
Roughly test the model after speedup inference speed.
J-shang's avatar
J-shang committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

.. GENERATED FROM PYTHON SOURCE LINES 74-78

.. code-block:: default

    start = time.time()
    model(torch.rand(128, 1, 28, 28).to(device))
    print('Speedup Model - Elapsed Time : ', time.time() - start)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

205
    Speedup Model - Elapsed Time :  0.003069639205932617
J-shang's avatar
J-shang committed
206
207
208
209




210
.. GENERATED FROM PYTHON SOURCE LINES 79-240
J-shang's avatar
J-shang committed
211
212

For combining usage of ``Pruner`` masks generation with ``ModelSpeedup``,
213
please refer to :doc:`Pruning Quick Start <pruning_quick_start_mnist>`.
J-shang's avatar
J-shang committed
214
215
216
217
218
219
220
221
222

NOTE: The current implementation supports PyTorch 1.3.1 or newer.

Limitations
-----------

For PyTorch we can only replace modules, if functions in ``forward`` should be replaced,
our current implementation does not work. One workaround is make the function a PyTorch module.

223
If you want to speedup your own model which cannot supported by the current implementation,
J-shang's avatar
J-shang committed
224
225
226
227
228
you need implement the replace function for module replacement, welcome to contribute.

Speedup Results of Examples
---------------------------

229
The code of these experiments can be found :githublink:`here <examples/model_compress/pruning/legacy/speedup/model_speedup.py>`.
J-shang's avatar
J-shang committed
230

231
These result are tested on the `legacy pruning framework <https://nni.readthedocs.io/en/v2.6/Compression/pruning.html>`_, new results will coming soon.
J-shang's avatar
J-shang committed
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

slim pruner example
^^^^^^^^^^^^^^^^^^^

on one V100 GPU,
input tensor: ``torch.randn(64, 3, 32, 32)``

.. list-table::
   :header-rows: 1
   :widths: auto

   * - Times
     - Mask Latency
     - Speedup Latency
   * - 1
     - 0.01197
     - 0.005107
   * - 2
     - 0.02019
     - 0.008769
   * - 4
     - 0.02733
     - 0.014809
   * - 8
     - 0.04310
     - 0.027441
   * - 16
     - 0.07731
     - 0.05008
   * - 32
     - 0.14464
     - 0.10027

fpgm pruner example
^^^^^^^^^^^^^^^^^^^

on cpu,
input tensor: ``torch.randn(64, 1, 28, 28)``\ ,
too large variance

.. list-table::
   :header-rows: 1
   :widths: auto

   * - Times
     - Mask Latency
     - Speedup Latency
   * - 1
     - 0.01383
     - 0.01839
   * - 2
     - 0.01167
     - 0.003558
   * - 4
     - 0.01636
     - 0.01088
   * - 40
     - 0.14412
     - 0.08268
   * - 40
     - 1.29385
     - 0.14408
   * - 40
     - 0.41035
     - 0.46162
   * - 400
     - 6.29020
     - 5.82143

l1filter pruner example
^^^^^^^^^^^^^^^^^^^^^^^

on one V100 GPU,
input tensor: ``torch.randn(64, 3, 32, 32)``

.. list-table::
   :header-rows: 1
   :widths: auto

   * - Times
     - Mask Latency
     - Speedup Latency
   * - 1
     - 0.01026
     - 0.003677
   * - 2
     - 0.01657
     - 0.008161
   * - 4
     - 0.02458
     - 0.020018
   * - 8
     - 0.03498
     - 0.025504
   * - 16
     - 0.06757
     - 0.047523
   * - 32
     - 0.10487
     - 0.086442

APoZ pruner example
^^^^^^^^^^^^^^^^^^^

on one V100 GPU,
input tensor: ``torch.randn(64, 3, 32, 32)``

.. list-table::
   :header-rows: 1
   :widths: auto

   * - Times
     - Mask Latency
     - Speedup Latency
   * - 1
     - 0.01389
     - 0.004208
   * - 2
     - 0.01628
     - 0.008310
   * - 4
     - 0.02521
     - 0.014008
   * - 8
     - 0.03386
     - 0.023923
   * - 16
     - 0.06042
     - 0.046183
   * - 32
     - 0.12421
     - 0.087113

SimulatedAnnealing pruner example
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In this experiment, we use SimulatedAnnealing pruner to prune the resnet18 on the cifar10 dataset.
We measure the latencies and accuracies of the pruned model under different sparsity ratios, as shown in the following figure.
The latency is measured on one V100 GPU and the input tensor is  ``torch.randn(128, 3, 32, 32)``.

.. image:: ../../img/SA_latency_accuracy.png


.. rst-class:: sphx-glr-timing

377
   **Total running time of the script:** ( 0 minutes  15.253 seconds)
J-shang's avatar
J-shang committed
378
379


380
.. _sphx_glr_download_tutorials_pruning_speedup.py:
J-shang's avatar
J-shang committed
381

382
.. only:: html
J-shang's avatar
J-shang committed
383

384
  .. container:: sphx-glr-footer sphx-glr-footer-example
J-shang's avatar
J-shang committed
385
386


387
    .. container:: sphx-glr-download sphx-glr-download-python
J-shang's avatar
J-shang committed
388

389
      :download:`Download Python source code: pruning_speedup.py <pruning_speedup.py>`
J-shang's avatar
J-shang committed
390

391
    .. container:: sphx-glr-download sphx-glr-download-jupyter
J-shang's avatar
J-shang committed
392

393
      :download:`Download Jupyter notebook: pruning_speedup.ipynb <pruning_speedup.ipynb>`
J-shang's avatar
J-shang committed
394
395
396
397
398
399
400


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_