quantization_speedup.rst 10.6 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/quantization_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_quantization_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_quantization_speedup.py:
J-shang's avatar
J-shang committed
19
20


21
SpeedUp Model with Calibration Config
J-shang's avatar
J-shang committed
22
23
24
25
26
27
28
29
======================================


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

Deep learning network has been computational intensive and memory intensive 
which increases the difficulty of deploying deep neural network model. Quantization is a 
30
fundamental technology which is widely used to reduce memory footprint and speedup inference 
J-shang's avatar
J-shang committed
31
32
process. Many frameworks begin to support quantization, but few of them support mixed precision 
quantization and get real speedup. Frameworks like `HAQ: Hardware-Aware Automated Quantization with Mixed Precision <https://arxiv.org/pdf/1811.08886.pdf>`__\, only support simulated mixed precision quantization which will 
33
not speedup the inference process. To get real speedup of mixed precision quantization and 
J-shang's avatar
J-shang committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
help people get the real feedback from hardware, we design a general framework with simple interface to allow NNI quantization algorithms to connect different 
DL model optimization backends (e.g., TensorRT, NNFusion), which gives users an end-to-end experience that after quantizing their model 
with quantization algorithms, the quantized model can be directly speeded up with the connected optimization backend. NNI connects 
TensorRT at this stage, and will support more backends in the future.


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

To support speeding up mixed precision quantization, we divide framework into two part, frontend and backend.  
Frontend could be popular training frameworks such as PyTorch, TensorFlow etc. Backend could be inference 
framework for different hardwares, such as TensorRT. At present, we support PyTorch as frontend and 
TensorRT as backend. To convert PyTorch model to TensorRT engine, we leverage onnx as intermediate graph 
representation. In this way, we convert PyTorch model to onnx model, then TensorRT parse onnx 
model to generate inference engine. 


Quantization aware training combines NNI quantization algorithm 'QAT' and NNI quantization speedup tool.
J-shang's avatar
J-shang committed
52
Users should set config to train quantized model using QAT algorithm(please refer to :doc:`NNI Quantization Algorithms <../compression/quantizer>`  ).
J-shang's avatar
J-shang committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
After quantization aware training, users can get new config with calibration parameters and model with quantized weight. By passing new config and model to quantization speedup tool, users can get real mixed precision speedup engine to do inference.


After getting mixed precision engine, users can do inference with input data.


Note


* Recommend using "cpu"(host) as data device(for both inference data and calibration data) since data should be on host initially and it will be transposed to device before inference. If data type is not "cpu"(host), this tool will transpose it to "cpu" which may increases unnecessary overhead.
* User can also do post-training quantization leveraging TensorRT directly(need to provide calibration dataset).
* Not all op types are supported right now. At present, NNI supports Conv, Linear, Relu and MaxPool. More op types will be supported in the following release.


Prerequisite
------------
CUDA version >= 11.0

TensorRT version >= 7.2

Note

* If you haven't installed TensorRT before or use the old version, please refer to `TensorRT Installation Guide <https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html>`__\  

Usage
-----

80
.. GENERATED FROM PYTHON SOURCE LINES 64-92
J-shang's avatar
J-shang committed
81
82
83
84
85
86
87
88
89
90
91

.. code-block:: default

    import torch
    import torch.nn.functional as F
    from torch.optim import SGD
    from scripts.compression_mnist_model import TorchModel, device, trainer, evaluator, test_trt

    config_list = [{
        'quant_types': ['input', 'weight'],
        'quant_bits': {'input': 8, 'weight': 8},
92
        'op_types': ['Conv2d']
J-shang's avatar
J-shang committed
93
94
95
    }, {
        'quant_types': ['output'],
        'quant_bits': {'output': 8},
96
        'op_types': ['ReLU']
J-shang's avatar
J-shang committed
97
98
99
    }, {
        'quant_types': ['input', 'weight'],
        'quant_bits': {'input': 8, 'weight': 8},
100
        'op_names': ['fc1', 'fc2']
J-shang's avatar
J-shang committed
101
102
103
104
105
    }]

    model = TorchModel().to(device)
    optimizer = SGD(model.parameters(), lr=0.01, momentum=0.5)
    criterion = F.nll_loss
106
    dummy_input = torch.rand(32, 1, 28, 28).to(device)
J-shang's avatar
J-shang committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129

    from nni.algorithms.compression.pytorch.quantization import QAT_Quantizer
    quantizer = QAT_Quantizer(model, config_list, optimizer, dummy_input)
    quantizer.compress()





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

 Out:

 .. code-block:: none


    TorchModel(
      (conv1): QuantizerModuleWrapper(
        (module): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
      )
      (conv2): QuantizerModuleWrapper(
        (module): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
      )
130
131
132
133
134
135
      (fc1): QuantizerModuleWrapper(
        (module): Linear(in_features=256, out_features=120, bias=True)
      )
      (fc2): QuantizerModuleWrapper(
        (module): Linear(in_features=120, out_features=84, bias=True)
      )
J-shang's avatar
J-shang committed
136
      (fc3): Linear(in_features=84, out_features=10, bias=True)
137
138
139
140
141
142
143
144
145
146
147
148
149
150
      (relu1): QuantizerModuleWrapper(
        (module): ReLU()
      )
      (relu2): QuantizerModuleWrapper(
        (module): ReLU()
      )
      (relu3): QuantizerModuleWrapper(
        (module): ReLU()
      )
      (relu4): QuantizerModuleWrapper(
        (module): 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
151
152
153
154
    )



155
.. GENERATED FROM PYTHON SOURCE LINES 93-94
J-shang's avatar
J-shang committed
156
157
158

finetuning the model by using QAT

159
.. GENERATED FROM PYTHON SOURCE LINES 94-98
J-shang's avatar
J-shang committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

.. code-block:: default

    for epoch in range(3):
        trainer(model, optimizer, criterion)
        evaluator(model)





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

 Out:

 .. code-block:: none

J-shang's avatar
J-shang committed
177
178
179
    Average test loss: 0.5386, Accuracy: 8619/10000 (86%)
    Average test loss: 0.1553, Accuracy: 9521/10000 (95%)
    Average test loss: 0.1001, Accuracy: 9686/10000 (97%)
J-shang's avatar
J-shang committed
180
181
182
183




184
.. GENERATED FROM PYTHON SOURCE LINES 99-100
J-shang's avatar
J-shang committed
185
186
187

export model and get calibration_config

188
.. GENERATED FROM PYTHON SOURCE LINES 100-108
J-shang's avatar
J-shang committed
189
190
191

.. code-block:: default

192
193
    import os
    os.makedirs('log', exist_ok=True)
J-shang's avatar
J-shang committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    model_path = "./log/mnist_model.pth"
    calibration_path = "./log/mnist_calibration.pth"
    calibration_config = quantizer.export_model(model_path, calibration_path)

    print("calibration_config: ", calibration_config)





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

 Out:

 .. code-block:: none

J-shang's avatar
J-shang committed
210
    calibration_config:  {'conv1': {'weight_bits': 8, 'weight_scale': tensor([0.0029], device='cuda:0'), 'weight_zero_point': tensor([98.], device='cuda:0'), 'input_bits': 8, 'tracked_min_input': -0.4242129623889923, 'tracked_max_input': 2.821486711502075}, 'conv2': {'weight_bits': 8, 'weight_scale': tensor([0.0017], device='cuda:0'), 'weight_zero_point': tensor([124.], device='cuda:0'), 'input_bits': 8, 'tracked_min_input': 0.0, 'tracked_max_input': 8.848002433776855}, 'fc1': {'weight_bits': 8, 'weight_scale': tensor([0.0010], device='cuda:0'), 'weight_zero_point': tensor([134.], device='cuda:0'), 'input_bits': 8, 'tracked_min_input': 0.0, 'tracked_max_input': 14.64758586883545}, 'fc2': {'weight_bits': 8, 'weight_scale': tensor([0.0013], device='cuda:0'), 'weight_zero_point': tensor([121.], device='cuda:0'), 'input_bits': 8, 'tracked_min_input': 0.0, 'tracked_max_input': 15.807988166809082}, 'relu1': {'output_bits': 8, 'tracked_min_output': 0.0, 'tracked_max_output': 9.041301727294922}, 'relu2': {'output_bits': 8, 'tracked_min_output': 0.0, 'tracked_max_output': 15.143928527832031}, 'relu3': {'output_bits': 8, 'tracked_min_output': 0.0, 'tracked_max_output': 16.151935577392578}, 'relu4': {'output_bits': 8, 'tracked_min_output': 0.0, 'tracked_max_output': 11.749024391174316}}
J-shang's avatar
J-shang committed
211
212
213
214




215
.. GENERATED FROM PYTHON SOURCE LINES 109-110
J-shang's avatar
J-shang committed
216

217
build tensorRT engine to make a real speedup
J-shang's avatar
J-shang committed
218

219
.. GENERATED FROM PYTHON SOURCE LINES 110-117
J-shang's avatar
J-shang committed
220
221
222
223

.. code-block:: default


224
225
226
227
228
229
230
231
    from nni.compression.pytorch.quantization_speedup import ModelSpeedupTensorRT
    input_shape = (32, 1, 28, 28)
    engine = ModelSpeedupTensorRT(model, input_shape, config=calibration_config, batchsize=32)
    engine.compress()
    test_trt(engine)



J-shang's avatar
J-shang committed
232
233


234
235
236
.. rst-class:: sphx-glr-script-out

 Out:
J-shang's avatar
J-shang committed
237

238
 .. code-block:: none
J-shang's avatar
J-shang committed
239

J-shang's avatar
J-shang committed
240
241
    Loss: 0.10061546401977539  Accuracy: 96.83%
    Inference elapsed_time (whole dataset): 0.04322671890258789s
J-shang's avatar
J-shang committed
242
243
244
245




246
.. GENERATED FROM PYTHON SOURCE LINES 118-169
J-shang's avatar
J-shang committed
247
248
249
250
251

Note that NNI also supports post-training quantization directly, please refer to complete examples for detail.

For complete examples please refer to :githublink:`the code <examples/model_compress/quantization/mixed_precision_speedup_mnist.py>`.

J-shang's avatar
J-shang committed
252
For more parameters about the class 'TensorRTModelSpeedUp', you can refer to :doc:`Model Compression API Reference <../reference/compression/quantization_speedup>`.
J-shang's avatar
J-shang committed
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

Mnist test
^^^^^^^^^^

on one GTX2080 GPU,
input tensor: ``torch.randn(128, 1, 28, 28)``

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

   * - quantization strategy
     - Latency
     - accuracy
   * - all in 32bit
     - 0.001199961
     - 96%
   * - mixed precision(average bit 20.4)
     - 0.000753688
     - 96%
   * - all in 8bit
     - 0.000229869
     - 93.7%

Cifar10 resnet18 test (train one epoch)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

on one GTX2080 GPU,
input tensor: ``torch.randn(128, 3, 32, 32)``

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

   * - quantization strategy
     - Latency
     - accuracy
   * - all in 32bit
     - 0.003286268
     - 54.21%
   * - mixed precision(average bit 11.55)
     - 0.001358022
     - 54.78%
   * - all in 8bit
     - 0.000859139
     - 52.81%


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

J-shang's avatar
J-shang committed
303
   **Total running time of the script:** ( 1 minutes  4.509 seconds)
J-shang's avatar
J-shang committed
304
305


306
.. _sphx_glr_download_tutorials_quantization_speedup.py:
J-shang's avatar
J-shang committed
307
308
309
310
311
312
313
314
315
316
317


.. only :: html

 .. container:: sphx-glr-footer
    :class: sphx-glr-footer-example



  .. container:: sphx-glr-download sphx-glr-download-python

318
     :download:`Download Python source code: quantization_speedup.py <quantization_speedup.py>`
J-shang's avatar
J-shang committed
319
320
321
322
323



  .. container:: sphx-glr-download sphx-glr-download-jupyter

324
     :download:`Download Jupyter notebook: quantization_speedup.ipynb <quantization_speedup.ipynb>`
J-shang's avatar
J-shang committed
325
326
327
328
329
330
331


.. only:: html

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

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