模型量化具备降低内存、提高计算速度等有点,并且是一种比较成熟的方案,已经得到广泛应用。
OpenVINO提供了两种量化方式
参考自 官网 https://docs.openvino.ai/latest/openvino_docs_model_optimization_guide.html

  • Post-training Optimization w/POT。 通过post-traning方法,对模型进行量化,比如post-training 8-Bit量化,无需对模型进行重新训练或者fine-tuning
  • Training-time Optimization w/NNCF。 在DL框架内,训练时间段进行模型优化。比如可以基于Pytorch和TensorFlow框架内,支持量化感知训练和裁剪。

下图为量化的流程

  1. 训练一个全精度的模型
  2. 运行Model Optimizer或者NNCF模块,得到 IR模型或者量化后的框架模型
  3. 运行POT模块对模型进行量化,或者运行Model Optimizer模块获取优化后的IR模型

二、Post-training Optimization Tool

优势:

  • 无需重新训练模型
  • 将全精度IR模型转换为低精度数据类型INT8,可以减少模型大小、降低latency
  • 会降低一些精度,也可能降低的比较多

下图是PTO的量化流程
输入模型->经过MO后得到IR文件->运行PTO工具(可输入数据)->得到量化后的模型

2.1 运用MO工具获取OpenVINO的IR模型

IR指 Intermediate Representation 中间表示,生成的也是OpenVINO的模型,可以是FP32或者FP16的。
Mo工具是OpenVINO提供的,可以在命令行操作。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
*  * *** *  * *  *
*  *  *   **  *  *
****  *   **  *  *
*  *  *   **  *  *
*  * **  *  * ****                @File    : hello_openvino.py
@Date    : 2022/9/26/026
@Require :
@Author  : https://blog.csdn.net/hjxu2016
@Funtion : """import openvino.inference_engine as ie
import osprint(ie.__version__)
if __name__ == "__main__":import subprocessfile = "F:/PyPro/Classification/weight/res18_5_focal_loss_9954.onnx"#f = str(file).replace('.onnx', '_openvino_model_fp16' + os.sep)## cmd = f"mo --input_model {file} --output_dir {f} --data_type FP16 --log_level NOTSET --input_shape [1,3,224,224]"# cmd = f"mo --help "cmd = f"mo --input_model {file} --output_dir {f} --data_type FP16 --log_level NOTSET"p = os.popen(cmd)print(p.read())# subprocess.check_output(cmd, shell=True)

2.2 DefaultQuantization 与 AccuracyAwareQuantization

PostTraining 提供了两种量化方式
可以通过python脚本执行量化步骤
也可以通过命令行的接口来进行量化,这里只介绍Python量化的流程

整个量化差不多准备三个步骤

  1. 准备数据和数据接口
  2. 设置量化算法参数
  3. 定义和执行量化过程

2.2.1 准备数据和数据接口

在大多数案例中,需要集成openvino.tools.pot.DataLoade 来设置数据。
接口介绍: https://docs.openvino.ai/latest/pot_default_quantization_usage.html
接口可以从数据集中获取数据,并且应用模型的特殊预处理工具,可以按照索引访问。

再看Dataloader接口

  • len(), 返回数据集的size

  • getitem(), 可以按照索引访问数据,它还可以封装特定于模型的预处理逻辑。此方法应以(data,annotation)格式返回数据,其中:数据是在推理时传递给模型的输入,因此应该对其进行适当的预处理。它可以是numpy。数组对象或字典,其中键是模型输入的名称,值是numpy。对应于此输入的数组。默认量化方法不使用annotation。因此,在这种情况下,此对象可以为“None”


class DataLoader(ABC):"""An abstract class representing a dataset.All custom datasets should inherit.``__len__`` provides the size of the dataset and``__getitem__`` supports integer indexing in range from 0 to len(self)"""def __init__(self, config):""" Constructor:param config: data loader specific config"""self.config = config if isinstance(config, Dict) else Dict(config)@abstractmethoddef __getitem__(self, index):pass@abstractmethoddef __len__(self):pass

2.2.2 设置量化参数

默DefaultQuantization量化算子有一些强制性或者可选的参数,这些参数以字典的方式定义
如果选择AccuracyAwareQuantization量化算子,可以设置maximal_drop最大精度下降的的范围,这时候会自动搜索哪些层对量化的精度损失高的层,然后对这些层不进行量化操作

{"name": "DefaultQuantization", # AccuracyAwareQuantization"params": {"target_device": "ANY","stat_subset_size": 300,"stat_batch_size": 1,"maximal_drop":0.01,},
}

默认量化算子存在三个参数

  • target_device 目前只可以选择“ANY”或者“CPU”
  • stat_subset_size 用于计算用于量化的激活统计信息的数据子集的大小。如果未指定参数,则使用整个数据集。建议使用不少于300个样品。
  • stat_batch_size 用于计算用于量化的激活统计信息的批大小。如果未指定参数,则为1。
  • maximal_drop 精度下降的最大值

2.2.3 设置metric评估指标

metric评估指标在DefaultQuantization量化阶段可以用来衡量量化前和量化后的精度对比,当然,在DefaultQuantization量化阶段,可以将这个设置为None
在AccuracyAwareQuantization量化阶段,则必须设置好,因为需要通过这个指标来确定精度下降的范围。
如下实例为分割的IOU评估指标。

class Accuracy(Metric):def __init__(self):super().__init__()self._name = "accuracy"self._matches = []self.intersection = 0.0self.union = 0.0@propertydef value(self):"""Returns accuracy metric value for the last model output."""# print(self._matches[-1])return {self._name: self._matches[-1]}@propertydef avg_value(self):"""Returns accuracy metric value for all model outputs. Results per image are stored inself._matches, where True means a correct prediction and False a wrong prediction.Accuracy is computed as the number of correct predictions divided by the totalnumber of predictions."""miou = 1.0 * self.intersection / self.unionprint('miou', miou)return {self._name: miou}def update(self, output, target):"""Updates prediction matches.:param output: model output:param target: annotations"""predict = output[1]predict = predict[0] > 0.5target = target[0] > 0.5intersection = np.sum((predict) & (target))self.intersection += np.sum((predict) & (target))self.union += np.sum(predict) + np.sum(target) - intersectionself._matches.append([self.intersection/(self.union+0.00001)])def reset(self):"""Resets the Accuracy metric. This is a required method that should initialize allattributes to their initial value."""self.intersection = 0self.union = 0self._matches = []def get_attributes(self):"""Returns a dictionary of metric attributes {metric_name: {attribute_name: value}}.Required attributes: 'direction': 'higher-better' or 'higher-worse''type': metric type"""return {self._name: {"direction": "higher-better", "type": "accuracy"}}

2.2.4 执行量化

参考案例来自
https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/301-tensorflow-training-openvino/301-tensorflow-training-openvino-pot.ipynb
总共有9个步骤,其中精度metric是可选的,DefaultQuantization量化时,metric可以设置为None,也可以用来对比量化前和量化后的精度损失。
在AccuracyAwareQuantization量化阶段,则必须设置metric好,因为需要通过这个指标来确定精度下降的范围

    folder = "F:/DataSet/LyophilizedBall/classification/val/"# step1: 加载模型model = load_model(model_config)original_model = copy.deepcopy(model)# print(model)# step2: 初始化 dataloaderdata_loader = ClassificationDataLoader(folder)# step3: 可选,设置评估指标,可用于和原模型做对比metric = Accuracy()# metric = None# step4: 初始化引擎,通过数据、评估指标计算engine = IEEngine(config=engine_config, data_loader=data_loader, metric=metric)# step5: 创建模型压缩算法的管道pipeline = create_pipeline(algo_config=algorithms, engine=engine)# step6: 执行管道流程compressed_model = pipeline.run(model=model)# step7: 可选:为了减少最后.bin 文件的大希奥,压缩模型权重进度compress_model_weights(model=compressed_model)# step8: 可选:保存模型, 返回保存模型的路径compress_model_path = save_model(model=compressed_model, save_path="./models/weight/ptqModel")print(compress_model_path)# Step 9 (Optional): Evaluate the original and compressed model. Print the resultsoriginal_metric_results = pipeline.evaluate(original_model)if original_metric_results:print(f"Accuracy of the original model:  {next(iter(original_metric_results.values())):.5f}")quantized_metric_results = pipeline.evaluate(compressed_model)if quantized_metric_results:print(f"Accuracy of the quantized model: {next(iter(quantized_metric_results.values())):.5f}")

【OpenVINO 3】POT量化流程相关推荐

  1. yolov5量化部署(基于openvino和tensorrt)

    yolov5 openvino量化部署 首先,下载YOLOv5源码,安装YOLOv5和OpenVINO的python依赖. git clone https://github.com/ultralyti ...

  2. 数据分析:复杂业务场景下,量化评估流程

    本文源码:GitHub·点这里 || GitEE·点这里 一.量化思维 在编程体系中有很多复杂的业务是很难理解的,但是又需要做一个量化分析,给业务人员或者运营,或者用户一个参考标准,例如常见指数,芝麻 ...

  3. 技术分享 | OpenVINO及EdgeX摄像头管理和推理平台

    关于2022 EdgeX中国挑战赛 2022 EdgeX中国挑战赛暨中关村国际前沿科技创新大赛EdgeX专题赛正式拉开帷幕.大赛由北京市科委.中关村管委会指导,由Linux基金会主办,由阿里云.百度智 ...

  4. 使用OpenVINOTM对YOLOv5进行INT8量化

    终于来了一个yolo5的 本身一直停留在v5阶段  这个也是拿来主义 自学 真的为自学 多谢理解啦 如题 .. 使用OpenVINOTM 2022.1 Post-training Optimizati ...

  5. openvino系列 12. Model Optimizer:PaddlePaddle 模型转化 IR 模型

    openvino系列 12. Model Optimizer:PaddlePaddle 模型转化 IR 模型 本案例展示了如何将 MobileNetV3 模型从 PaddleHub加载到本地,最终转换 ...

  6. TensorRT-8量化分析

    TensorRT-8量化分析 本文讲非对称量化.量化方式等等一些细节,不过有一段时间在做基于TensorRT的量化,需要看下TensorRT的量化细节.这次文章是偏实践的一篇,主要过一下TensorR ...

  7. deeplearning模型量化实战

    deeplearning模型量化实战 MegEngine 提供从训练到部署完整的量化支持,包括量化感知训练以及训练后量化,凭借"训练推理一体"的特性,MegEngine更能保证量化 ...

  8. ROS系统——部署OpenVINO版Nanodet超轻量目标检测器

    目录 0 背景 本人的实测效果: 1 环境搭建 2 先熟悉OpenVINO版nanodet的流程 3  在ROS里部署openvino版nanodet的流程 4 源码 4.1 main.cpp内容 4 ...

  9. PyTorch模型量化工具学习

    官方教程(英文): https://pytorch.org/docs/stable/quantization.html​pytorch.org 官方教程(中文): https://pytorch.ap ...

最新文章

  1. MATLAB作二维傅里叶变换所需要注意和知道的东西(im2double、fft2、abs、imshow、二维傅里叶变换的物理意义)
  2. Codeforces Round #267 Div2 C George and Job --DP
  3. STM32F4 HAL库开发 -- 独立看门狗(IWDG)
  4. 为什么运行了java文件老是404_java – 为什么Spring MVC用404响应并报告“在...
  5. c语言在程序中显示现在星期几,C语言程序设计: 输入年月日 然后输出是星期几...
  6. web 后台返回json格式数据的方式(status 406)
  7. Sound recording and encoding in MP3 format.
  8. 学习linux装,一个初学者的Linux学习之旅之Linux安装篇
  9. 3GPP realease 5G realease
  10. 支付宝解释 2019 年账单总额较高;腾讯 QQ 回应新功能可显示对方实时电量;Python 2.7 结束支持 | 极客头条...
  11. 设计模式PHP篇(三)————适配器模式
  12. java的path的设置路径_java安装path设置
  13. lol英雄全皮肤爬取
  14. i7 10700和10700f 10700k这三个CPU有什么区别
  15. Visa联合几大银行测试区块链B2B支付平台
  16. beyond VVC SCC技术学习:
  17. UVa 11178 Morley‘s Theorem(计算几何基础)
  18. CV5200远距离WiFi模组,安防监控数据远程传输方案,支持mesh自组网
  19. 基于ntkoocx.js的在线word编辑
  20. 750W高PF值充电机用电源方案

热门文章

  1. 计算机为什么有个来宾用户名,电脑里面突然多出来一个叫Guest的账户是怎么回事?...
  2. win10 提升来宾账户为管理员账户
  3. JAVA入门:猜大小程序
  4. SAPI ++微信SaaS平台源码v1.8.7.1
  5. Python xlrd读取、处理excel日期类型
  6. 电气图纸关于号码管的命名规则
  7. 数字功放和模拟功放有哪些区别
  8. 高级气泡图——R语言简单实现
  9. python实现RSA数字签名(纯算法实现)
  10. java 判断手机运营商_JS正则表达式判断手机号所属运营商