PaddlePaddle|CV疫情特輯(六):PaddleSlim模型壓縮

PaddlePaddle|CV疫情特輯(六):PaddleSlim模型壓縮

本節內容來自:百度AIstudio課程
做一個記錄。

資料
做作業時可以參考以下資料。

  • PaddleSlim代碼地址: https://github.com/PaddlePaddle/PaddleSlim
  • 文檔地址:https://paddlepaddle.github.io/PaddleSlim/

選擇題

  • 【1】定點化量化的優點有哪些?

A.低內存帶寬 B. 低功耗 C. 低計算資源 D. 低存儲體積

  • 【2】在常規蒸餾任務中,以下說法正確的是:

A. 只有teacher model的參數需要更新

B. 只有student model的參數需要更新

C. teacher model和student model 的參數都需要更新

D.teacher model和student model 的參數都不需要更新

  • 【3】是否能用MobileNetv1蒸餾ResNet50?

A: 能

B: 不能

  • 【4】下面方法哪些可以減少模型推理時間?

A. 只對權重weight進行量化

B. 對ResNet50模型進行蒸餾提高精度

C. 對模型進行裁剪,減少通道數

D. 對權重weight和激活進行量化,預測採用INT8計算

  • 【5】NAS的三個關鍵要素是:

A. 搜索空間

B. 搜索算法

C. 模型優化

D. 模型評估

選擇題答題卡

(僅供參考)
請將每道選擇題的答案寫在這裏:

  • 【1】A、B、C、D
  • 【2】C
  • 【3】A
  • 【4】A、B、C、D
  • 【5】A、B、D

圖像分類模型量化教程

該教程以圖像分類模型MobileNetV1爲例,說明如何快速使用量化訓練接口。 該示例包含以下步驟:

  • 1.導入依賴
  • 2.構建模型
  • 3.定義輸入數據
  • 4.訓練模型
  • 5.量化模型 這個步驟中需要添加代碼
  • 6.訓練和測試量化後的模型

以下章節依次介紹每個步驟的內容。

0. 安裝paddleslim

!pip install paddleslim
Looking in indexes: https://pypi.mirrors.ustc.edu.cn/simple/
Collecting paddleslim
  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/69/3c/880afac020e3393da5a55b4e0b504d2b644a7ebe91092d953185f09660d1/paddleslim-1.0.1-py2.py3-none-any.whl (103kB)
    100% |████████████████████████████████| 112kB 12.2MB/s ta 0:00:01
Requirement already satisfied: tqdm in /opt/conda/envs/python27-paddle120-env/lib/python2.7/site-packages (from paddleslim) (4.36.1)
Installing collected packages: paddleslim
Successfully installed paddleslim-1.0.1

1. 導入依賴

PaddleSlim依賴Paddle1.7版本,請確認已正確安裝Paddle,然後按以下方式導入Paddle和PaddleSlim:

import paddle
import paddle.fluid as fluid
import paddleslim as slim
import numpy as np

2. 構建模型

該章節構造一個用於對MNIST數據進行分類的分類模型,選用MobileNetV1,並將輸入大小設置爲[1, 28, 28],輸出類別數爲10。 爲了方便展示示例,我們在paddleslim.models下預定義了用於構建分類模型的方法,執行以下代碼構建分類模型:

3 定義輸入數據

爲了快速執行該示例,我們選取簡單的MNIST數據,Paddle框架的paddle.dataset.mnist包定義了MNIST數據的下載和讀取。 代碼如下:

import paddle.dataset.mnist as reader
train_reader = paddle.batch(
        reader.train(), batch_size=128, drop_last=True)
test_reader = paddle.batch(
        reader.test(), batch_size=128, drop_last=True)
data_feeder = fluid.DataFeeder(inputs, place)
Cache file /home/aistudio/.cache/paddle/dataset/mnist/train-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/train-images-idx3-ubyte.gz 
Begin to download
....................
Download finished
Cache file /home/aistudio/.cache/paddle/dataset/mnist/train-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/train-labels-idx1-ubyte.gz 
Begin to download
........
Download finished
Cache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-images-idx3-ubyte.gz 
Begin to download
....................
Download finished
Cache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-labels-idx1-ubyte.gz 
Begin to download
..
Download finished

4. 訓練和測試

先定義訓練和測試函數,正常訓練和量化訓練時只需要調用函數即可。在訓練函數中執行了一個epoch的訓練,因爲MNIST數據集數據較少,一個epoch就可將top1精度訓練到95%以上。

def train(prog):
    iter = 0
    for data in train_reader():
        acc1, acc5, loss = exe.run(prog, feed=data_feeder.feed(data), fetch_list=outputs)
        if iter % 100 == 0:
            print('train iter={}, top1={}, top5={}, loss={}'.format(iter, acc1.mean(), acc5.mean(), loss.mean()))
        iter += 1
        
def test(prog):
    iter = 0
    res = [[], []]
    for data in test_reader():
        acc1, acc5, loss = exe.run(prog, feed=data_feeder.feed(data), fetch_list=outputs)
        if iter % 100 == 0:
            print('test iter={}, top1={}, top5={}, loss={}'.format(iter, acc1.mean(), acc5.mean(), loss.mean()))
        res[0].append(acc1.mean())
        res[1].append(acc5.mean())
        iter += 1
    print('final test result top1={}, top5={}'.format(np.array(res[0]).mean(), np.array(res[1]).mean()))

調用train函數訓練分類網絡,train_program是在第2步:構建網絡中定義的

train(train_program)
train iter=0, top1=0.1328125, top5=0.5703125, loss=2.62163162231
train iter=100, top1=0.90625, top5=1.0, loss=0.227992996573
train iter=200, top1=0.9296875, top5=1.0, loss=0.184181377292
train iter=300, top1=0.9609375, top5=0.984375, loss=0.152075260878
train iter=400, top1=0.953125, top5=1.0, loss=0.155824646354

調用test函數測試分類網絡,val_program是在第2步:構建網絡中定義的。

test(val_program)
test iter=0, top1=0.96875, top5=1.0, loss=0.0912945345044
final test result top1=0.966846942902, top5=0.999699532986

5. 量化模型

按照配置在train_program和val_program中加入量化和反量化op.

place = exe.place 
quant_program = slim.quant.quant_aware(train_program, exe.place, for_test=False)#請在次數添加你的代碼
val_quant_program = slim.quant.quant_aware(val_program, exe.place, for_test=True)#請在次數添加你的代碼

輸出:

2020-04-05 12:49:39,794-INFO: quant_aware config {'moving_rate': 0.9, 'weight_quantize_type': 'channel_wise_abs_max', 'is_full_quantize': False, 'dtype': 'int8', 'weight_bits': 8, 'window_size': 10000, 'activation_bits': 8, 'quantize_op_types': ['conv2d', 'depthwise_conv2d', 'mul'], 'not_quant_pattern': ['skip_quant'], 'activation_quantize_type': 'moving_average_abs_max', 'for_tensorrt': False}
2020-04-05 12:49:40,854-INFO: quant_aware config {'moving_rate': 0.9, 'weight_quantize_type': 'channel_wise_abs_max', 'is_full_quantize': False, 'dtype': 'int8', 'weight_bits': 8, 'window_size': 10000, 'activation_bits': 8, 'quantize_op_types': ['conv2d', 'depthwise_conv2d', 'mul'], 'not_quant_pattern': ['skip_quant'], 'activation_quantize_type': 'moving_average_abs_max', 'for_tensorrt': False}

6 訓練和測試量化後的模型

微調量化後的模型,訓練一個epoch後測試。

train(quant_program)

輸出:

train iter=0, top1=0.078125, top5=0.484375, loss=2.80661392212
train iter=100, top1=0.953125, top5=0.9921875, loss=0.158855527639
train iter=200, top1=0.953125, top5=1.0, loss=0.133928954601
train iter=300, top1=0.9609375, top5=0.9921875, loss=0.164225846529
train iter=400, top1=0.953125, top5=1.0, loss=0.187246501446

測試量化後的模型,和3.2 訓練和測試中得到的測試結果相比,精度相近,達到了無損量化。

test(val_quant_program)

輸出:

test iter=0, top1=0.9765625, top5=1.0, loss=0.0456145778298
final test result top1=0.970452725887, top5=0.99919873476
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章