qkeras 量子化モデル - モデルを直接構築するための量子化対応トレーニング

量子化フレームワーク qkeras:

qkeras は、Google の知覚トレーニング用の量子化フレームワークであり、次のような機能があります。

1. keras モデルから qkeras モデルへのインポートをサポートします。

2. 枝刈りと量子化をサポートし、tensorflow lite を一緒に使用します。使用はそれほど簡単ではありません。

3. 量子化関数、量子化ビット数、量子化小数点の左側のビット数、対称性などの指定をサポートします。

4. 拡張が簡単。keras 設計原則を使用してビルディング ブロックをカスタマイズし、keras 機能を拡張し、sota モデルを開発できます。


qkeras の量子化:

1. keras を使用して構築されたモデルは、qkeras の量子化モデルに直接変換できます。

2. pytorch や mxnet などの他のフレームワークを使用して構築されたモデルは、qkeras によって構築されたモデルに手動で変換できます。


例:
公式サイト上でインスタンスを直接実行すると色々問題が発生するので、インポート方法を変更して問題を解決し、コア部分は残して無駄なステートメントを削除します。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
from qkeras import *
from qkeras.utils import model_save_quantized_weights
import numpy as np


np.random.seed(42)

NB_EPOCH = 100
BATCH_SIZE = 64
VERBOSE = 1
NB_CLASSES = 10
OPTIMIZER = tf.keras.optimizers.legacy.Adam(lr=0.0001, decay=0.000025)
VALIDATION_SPLIT = 0.1
train = 1

# 1、导入数据;
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
RESHAPED = 784
x_test_orig = x_test
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train = x_train[..., np.newaxis]
x_test = x_test[..., np.newaxis]
x_train /= 256.0
x_test /= 256.0

y_train = tf.keras.utils.to_categorical(y_train, NB_CLASSES)
y_test = tf.keras.utils.to_categorical(y_test, NB_CLASSES)

# 2、搭建量化模型;
x = x_in = tf.keras.layers.Input(
    x_train.shape[1:-1] + (1,), name="input")
x = QConv2D(
    32, (2, 2), strides=(2,2),
    kernel_quantizer=quantized_bits(4,0,1),
    bias_quantizer=quantized_bits(4,0,1),
    name="conv2d_0_m")(x)
x = QActivation("quantized_relu(4,0)", name="act0_m")(x)
x = QConv2D(
    64, (3, 3), strides=(2,2),
    kernel_quantizer=quantized_bits(4,0,1),
    bias_quantizer=quantized_bits(4,0,1),
    name="conv2d_1_m")(x)
x = QActivation("quantized_relu(4,0)", name="act1_m")(x)
x = QConv2D(
    64, (2, 2), strides=(2,2),
    kernel_quantizer=quantized_bits(4,0,1),
    bias_quantizer=quantized_bits(4,0,1),
    name="conv2d_2_m")(x)
x = QActivation("quantized_relu(4,0)", name="act2_m")(x)
x = tf.keras.layers.Flatten()(x)
x = QDense(NB_CLASSES, kernel_quantizer=quantized_bits(4,0,1),
           bias_quantizer=quantized_bits(4,0,1),
           name="dense")(x)
x = tf.keras.layers.Activation("softmax", name="softmax")(x)

model = tf.keras.Model(inputs=[x_in], outputs=[x])
model.summary()
model.compile(
    loss="categorical_crossentropy", optimizer=OPTIMIZER, metrics=["accuracy"])

# 3、训练模型;
if train:
    history = model.fit(
      x_train, y_train, batch_size=BATCH_SIZE,
      epochs=NB_EPOCH, initial_epoch=1, verbose=VERBOSE,
      validation_split=VALIDATION_SPLIT)
	
    # 4、计算测试准确度;
    score = model.evaluate(x_test, y_test, verbose=VERBOSE)
    print("Test score:", score[0])
    print("Test accuracy:", score[1])

    # 5、保存量化模型;
    model_save_quantized_weights(model)

    #6、打印模型参数shape;
    for layer in model.layers:
      for w, weight in enumerate(layer.get_weights()):
        print(layer.name, w, weight.shape)
	print_qstats(model)

基本的な論理ステップ:

1. データをインポートします。

2. 定量的モデルを構築する。

3. トレーニングモデル。

4. テスト精度を計算します。

5. 定量的モデルを保存します。

6. モデルパラメータの形状を印刷します。


依存関係のバージョン:

# This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: win-64
ca-certificates=2023.01.10=haa95532_0
certifi=2022.12.7=py37haa95532_0
openssl=1.1.1t=h2bbff1b_0
pip=22.3.1=py37haa95532_0
python=3.7.16=h6244533_0
setuptools=65.6.3=py37haa95532_0
sqlite=3.41.2=h2bbff1b_0
vc=14.2=h21ff451_1
vs2015_runtime=14.27.29016=h5e58377_2
wheel=0.38.4=py37haa95532_0
wincertstore=0.2=py37haa95532_2

トレーニングプロセス:
ここに画像の説明を挿入


参考:

GitHub - google/qkeras: QKeras: Tensorflow Keras の量子化深層学習ライブラリ

おすすめ

転載: blog.csdn.net/KPer_Yang/article/details/130736191