Elffuss BraidHub

kikocis/ncnn public

master · 2.7 KiBRenderedRawPermalink
1# Post Training Quantization Tools
2
3To support int8 model deployment on mobile devices,we provide the universal post training quantization tools which can convert the float32 model to int8 model.
4
5## User Guide
6
7Example with mobilenet, just need three steps.
8
9### 1. Optimize model
10
11```shell
12./ncnnoptimize mobilenet.param mobilenet.bin mobilenet-opt.param mobilenet-opt.bin 0
13```
14
15### 2. Create the calibration table file
16
17We suggest that using the verification dataset for calibration, which is more than 5000 images.
18
19Some imagenet sample images here https://github.com/nihui/imagenet-sample-images
20
21```shell
22find images/ -type f > imagelist.txt
23./ncnn2table mobilenet-opt.param mobilenet-opt.bin imagelist.txt mobilenet.table mean=[104,117,123] norm=[0.017,0.017,0.017] shape=[224,224,3] pixel=BGR thread=8 method=kl
24```
25
26* mean and norm are the values you passed to ```Mat::substract_mean_normalize()```
27* shape is the blob shape of your model, [w,h] or [w,h,c]
28
29>
30 * if w and h both are given, image will be resized to exactly size.
31 * if w and h both are zero or negative, image will not be resized.
32 * if only h is zero or negative, image's width will scaled resize to w, keeping aspect ratio.
33 * if only w is zero or negative, image's height will scaled resize to h
34
35* pixel is the pixel format of your model, image pixels will be converted to this type before ```Extractor::input()```
36* thread is the CPU thread count that could be used for parallel inference
37* method is the post training quantization algorithm, kl and aciq are currently supported
38
39If your model has multiple input nodes, you can use multiple list files and other parameters
40
41```shell
42./ncnn2table mobilenet-opt.param mobilenet-opt.bin imagelist-bgr.txt,imagelist-depth.txt mobilenet.table mean=[104,117,123],[128] norm=[0.017,0.017,0.017],[0.0078125] shape=[224,224,3],[224,224,1] pixel=BGR,GRAY thread=8 method=kl
43```
44
45### 3. Quantize model
46
47```shell
48./ncnn2int8 mobilenet-opt.param mobilenet-opt.bin mobilenet-int8.param mobilenet-int8.bin mobilenet.table
49```
50
51If you don’t need static quantization, ncnn supports RNN/LSTM/GRU dynamic quantization. In this case, you can omit the table file.
52
53```shell
54./ncnn2int8 rnn-model.param rnn-model.bin rnn-model-int8.param rnn-model-int8.bin
55```
56
57## use ncnn int8 inference
58
59the ncnn library would use int8 inference automatically, nothing changed in your code
60
61```cpp
62ncnn::Net mobilenet;
63mobilenet.load_param("mobilenet-int8.param");
64mobilenet.load_model("mobilenet-int8.bin");
65```
66
67## mixed precision inference
68
69Before quantize your model, comment the layer weight scale line in table file, then the layer will do the float32 inference
70
71```
72conv1_param_0 156.639840536
73```
74
75```
76#conv1_param_0 156.639840536
77```