vai_q_tensorflow2 量化感知训练 - 3.5 简体中文

Vitis AI 用户指南 (UG1414)

Document ID
UG1414
Release Date
2023-09-28
Version
3.5 简体中文

一般,量化可能会导致模型精度略有下降。但对于 MobileNets 之类的特定网络,精度损失可能会更大。为解决这一问题,量化感知训练 (QAT) 提供了一种进一步提高量化模型精度的解决方案。

QAT 与训练/微调浮点模型类似,不过在训练开始前,vai_q_tensorflow2 会重写浮点计算图,将其转换为量化模型。您可在此处找到完整示例。

QAT 的典型工作流程如下所述:

  1. 准备浮点模型、数据集和训练脚本:

    开始 QAT 前,准备下列文件:

    表 1. vai_q_tensorflow2 QAT 的输入文件
    编号 名称 描述
    1 浮点模型 作为起点的浮点模型文件。如果您从头开始训练,可以忽略此步骤。
    2 数据集 含标记的训练数据集。
    3 训练脚本 用于运行模型训练/微调的 Python 脚本。
  2. (可选)评估浮点模型。

    在执行 QAT 之前,首先评估浮点模型,以检查脚本和数据集是否精确。浮点检查点的精度和损失值也可作为 QAT 的基线。

  3. 修改训练脚本并运行 QAT。

    使用 vai_q_tensorflow2 API VitisQuantizer.get_qat_model 将模型转换为量化模型,然后利用它进行训练/微调。下面给出了 1 个示例:

    
    model = tf.keras.models.load_model('float_model.h5')
    
    
    # *Call Vai_q_tensorflow2 api to create the quantize training model
    from tensorflow_model_optimization.quantization.keras import vitis_quantize
    quantizer = vitis_quantize.VitisQuantizer(model)
    qat_model = quantizer.get_qat_model(
        init_quant=True, # Do init PTQ quantization will help us to get a better initial state for the quantizers, especially for the  `pof2s_tqt` strategy. Must be used together with calib_dataset
        calib_dataset=calib_dataset)
    
    # Then run the training process with this qat_model to get the quantize finetuned model.
    # Compile the model
    qat_model.compile(
            optimizer= RMSprop(learning_rate=lr_schedule), 
            loss=tf.keras.losses.SparseCategoricalCrossentropy(),
            metrics=keras.metrics.SparseTopKCategoricalAccuracy())
    
    
    # Start the training/finetuning
    qat_model.fit(train_dataset)
    
    
    注释: Vitis AI 从 2.0 版本起支持 pof2s_tqt 量化策略。它在量化器中使用经过训练的阈值,可能会改善 QAT 的结果。默认使用 Straight-Through-Estimator。8bit_tqt 方法只能用于 QAT,并且应设置 'init_quant=True' 以获得最佳性能。利用 PTQ 量化进行初始化可以为量化器参数生成更好的初始状态,对于 pof2s_tqt 尤其如此。否则,训练可能不会收敛。
  4. 保存模型。

    调用 model.save() 以保存训练模型,或者在 model.fit() 中使用回调来定期保存模型。例如:

    # save model manually
    qat_model.save('trained_model.h5')
    
    # save the model periodically during fit using callbacks
    qat_model.fit(
    	train_dataset, 
    	callbacks = [
          		keras.callbacks.ModelCheckpoint(
              	filepath='./quantize_train/'
              	save_best_only=True,
              	monitor="sparse_categorical_accuracy",
              	verbose=1,
          )])
    
  5. 转换为可部署量化模型。

    修改经过训练/微调的模型以满足编译器要求。例如,如果 train_with_bn 设为 TRUE,那么训练期间批量归一层会保持不折叠状态,在部署前必须折叠。某些量化器参数在训练期间可能会改变,超过编译器限制的范围。部署之前必须纠正这些情况。

    使用 get_deploy_model() 函数执行这些转换,并生成可部署模型,如以下示例所示:

    quantized_model = vitis_quantizer.get_deploy_model(qat_model) quantized_model.save('quantized_model.h5') 
  6. (可选)评估量化模型

    eval_dataset 上调用 model.evaluate() 以评估量化模型,就像浮点模型评估一样。

    
    from tensorflow_model_optimization.quantization.keras import vitis_quantize
    quantized_model = tf.keras.models.load_model('quantized_model.h5')
    
    quantized_model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(),
            metrics= keras.metrics.SparseTopKCategoricalAccuracy())
    quantized_model.evaluate(eval_dataset)