Horizon 모델 변환 및 PC 시뮬레이션 테스트

특이사항 : 호라이즌 공식문서를 참고하시고, 침해사항이 있을 경우 알려주시고 삭제해주시기 바랍니다. 감사합니다.

전체 변환 코드는 github를 참조하세요. 암호

1개의 도구 체인

  Horizon 도구 체인은 Docker와 수동 설치를 모두 지원합니다. "Horizon에서는 설치 프로세스 중 문제를 방지하기 위해 Docker 방법을 사용할 것을 강력히 권장합니다."
  Horizon에서 제공하는 Docker에는 CPU 버전과 GPU 버전이 있으며, 공식 다운로드 링크 툴체인이 제공됩니다 .
  Horizon 도구 체인은 현재 Caffe 및 ONNX의 로드 및 변환을 지원합니다. 다음은 도구 체인 버전 v1.11.4를 사용하여 ONNX 변환을 예로 사용합니다. 다음 예는 ONNX를 사용하여 설명됩니다.

Docker 이미지를 통해 설치

# 镜像 load
sudo docker load -i docker_cpu_openexplorer_centos_7_xj3_v1.11.4.tar
# 启动镜像
sudo docker run -v `pwd`/convert_model:/data -it hub.hobot.cc/aitools/ai_toolchain_centos_7_xj3:v1.11.4

여기에 이미지 설명을 삽입하세요.

2 모델 변환

  Horizon Toolchain의 전체 모델 개발 프로세스에는 부동 소수점 모델 준비, 모델 검증, 모델 변환, 성능 평가 및 정확도 평가와 같은 몇 가지 중요한 단계가 필요합니다.

2.1 부동 소수점 모델 준비

caffemodel 또는 onnx 모델을 준비합니다. 현재 onnx에서 지원하는 주요 opset 버전은 opset10 및 opset11입니다.

2.2 검증 모델

  Horizon 플랫폼에서 모델이 원활하고 효율적으로 실행될 수 있도록 모델에 사용되는 연산자는 플랫폼의 연산자 제약 사항을 준수해야 합니다.

  각 연산자의 특정 매개변수 제한 사항은 support_op_list_and_restrictions/ 경로 아래의 "supported_op_list_and_restrictions_release" Excel 표를 참조하세요.

  Horizon이 다수의 연산자를 지원한다는 점을 고려하여, 일일이 수동으로 검증하는 수고를 피하기 위해 모델에서 사용되는 연산자의 지원 여부를 검증할 수 있는 hb_mapper 검사기 도구를 제공합니다.

hb_mapper 검사기 도구를 사용하여 모델 확인

hb_mapper checker 参数解释:
--model-type
用于指定检查输入的模型类型,目前只支持设置 caffe 或者 onnx。

--march
用于指定需要适配的AI芯片类型,X/J3芯片应设置为 bernoulli2。

--proto
此参数仅在 model-type 指定 caffe 时有效,取值为Caffe模型的prototxt文件名称。

--model
在 model-type 被指定为 caffe 时,取值为Caffe模型的caffemodel文件名称。 在 model-type 被指定为 onnx 时,取值为ONNX模型文件名称。

--input-shape
可选参数,明确指定模型的输入shape。 取值为 {input_name} {NxHxWxC/NxCxHxW} ,input_name 与shape之间以空格分隔。 例如模型输入名称为 data1,输入shape为 [1,224,224,3], 则配置应该为 --input_shape data1 1x224x224x3。 如果此处配置shape与模型内shape信息不一致,以此处配置为准。

***说明***
注意一个 --input-shape 只接受一个name和shape组合,如果您的模型有多个输入节点, 在命令中多次配置 --input-shape 参数即可。

--output
可选参数,接受设置值为一个日志文件名称。 指定该参数情况下,检查的结果将输出到指定的日志文件。

데모의 01_chek.sh 예제를 사용하면 인쇄 로그에는 모델 및 BPU 지원에 대한 기본 정보가 포함됩니다. 어떤 레이어가 BPU에서 작동하고 어떤 레이어가 CPU에서 실행되는지 효율성을 고려하여 모든 레이어를 BPU. 계속 실행하세요.
여기에 이미지 설명을 삽입하세요.
예제의 모델이 적용되었으므로 모든 레이어는 BPU에서 실행됩니다.
여기에 이미지 설명을 삽입하세요.

2.3 모델 변환

2.3.1 교정 데이터 준비

  모델 변환을 수행할 때 교정 단계에는 약 100개의 샘플 입력이 필요하며 각 샘플은 독립적인 데이터 파일입니다. 변환된 모델의 정확성을 보장하기 위해 이러한 교정 샘플은 모델을 훈련하는 데 사용되는 훈련 세트 또는 검증 세트에서 가져와야 하며 장면 적용 범위는 최대한 풍부해야 합니다. 컬러 사진, 감지 대상이나 분류 대상이 없는 사진, 잠깐만요.

데이터 변환을 위해 02_preprocess.sh를 사용합니다.
  모델 변환의 다음 단계에서 구성 파일의 preprocess_on 매개변수를 변경합니다. 이 매개변수가 활성화 및 비활성화되면 두 가지 다른 전처리 샘플 요구 사항에 해당합니다. preprocess_on이 꺼진 경우 훈련 세트/검증 세트에서 가져온 샘플은 추론 전과 동일한 방식으로 사전 처리되어야 하며, 처리된 교정 샘플은 동일한 데이터 유형(input_type_train), 크기(input_shape) 및 레이아웃을 갖습니다. 원본 모델로(input_layout_train).

다음은 rgb 형식 입력을 예로 사용하고 전처리된 데이터는 cal_data 파일에 저장됩니다. 전처리를 위한 특정 코드는 data_preprocess.py 파일에 있습니다.

특별 참고 사항: 다음 예에서 모델이 사용하는 실제 입력은 bgr 이미지입니다. 예에서 .jpg 이미지는 cal_dataw 폴더에 직접 배치됩니다.
여기에 이미지 설명을 삽입하세요.

2.3.2 hb_mappermakertbin 도구를 사용하여 모델 변환

hb_mapper makertbin参数解释:
--model-type
用于指定转换输入的模型类型,目前支持设置 caffe 或者 onnx。

--config
模型编译的配置文件,内容采用yaml格式,文件名使用.yaml后缀。一份完整的配置文件模板如下:

说明:
此处配置文件仅作展示,在实际模型配置文件中 caffe_model 与 onnx_model 两个参数只存在其中之一。 即,要么是Caffe模型,要么是ONNX模型。

변환은 03_build.sh 스크립트를 이용하세요
여기에 이미지 설명을 삽입하세요.
변환 완료 예 : 로그 출력
INFO 런타임 bin 파일로 변환 성공 INFO 모델 종료 생성된 모델
변환
여기에 이미지 설명을 삽입하세요.

여기에 이미지 설명을 삽입하세요.

구성 파일 설명:

# 模型转化相关的参数
# ------------------------------------
# model conversion related parameters
model_parameters:
  # Onnx浮点网络数据模型文件
  # -----------------------------------------------------------
  # the model file of floating-point ONNX neural network data
  onnx_model: './model/yolov5_p6_512x512_6head.onnx'

  # 适用BPU架构
  # --------------------------------
  # the applicable BPU architecture
  march: "bernoulli2"

  # 指定模型转换过程中是否输出各层的中间结果,如果为True,则输出所有层的中间输出结果,
  # --------------------------------------------------------------------------------------
  # specifies whether or not to dump the intermediate results of all layers in conversion
  # if set to True, then the intermediate results of all layers shall be dumped
  layer_out_dump: False

  # 日志文件的输出控制参数,
  # debug输出模型转换的详细信息
  # info只输出关键信息
  # warn输出警告和错误级别以上的信息
  # ----------------------------------------------------------------------------------------
  # output control parameter of log file(s),
  # if set to 'debug', then details of model conversion will be dumped
  # if set to 'info', then only important imformation will be dumped
  # if set to 'warn', then information ranked higher than 'warn' and 'error' will be dumped
  log_level: 'debug'

  # 模型转换输出的结果的存放目录
  # -----------------------------------------------------------
  # the directory in which model conversion results are stored
  working_dir: 'model_output'

  # 模型转换输出的用于上板执行的模型文件的名称前缀
  # -----------------------------------------------------------------------------------------
  # model conversion generated name prefix of those model files used for dev board execution
  output_model_file_prefix: 'yolov5_p6_512x512'

# 模型输入相关参数, 若输入多个节点, 则应使用';'进行分隔, 使用默认缺省设置则写None
# --------------------------------------------------------------------------
# model input related parameters,
# please use ";" to seperate when inputting multiple nodes,
# please use None for default setting
input_parameters:

  # (选填) 模型输入的节点名称, 此名称应与模型文件中的名称一致, 否则会报错, 不填则会使用模型文件中的节点名称
  # --------------------------------------------------------------------------------------------------------
  # (Optional) node name of model input,
  # it shall be the same as the name of model file, otherwise an error will be reported,
  # the node name of model file will be used when left blank
  input_name: ""

  # 网络实际执行时,输入给网络的数据格式,包括 nv12/rgb/bgr/yuv444/gray/featuremap,
  # ------------------------------------------------------------------------------------------
  # the data formats to be passed into neural network when actually performing neural network
  # available options: nv12/rgb/bgr/yuv444/gray/featuremap,
  input_type_rt: 'rgb'

  # 网络实际执行时输入的数据排布, 可选值为 NHWC/NCHW
  # 若input_type_rt配置为nv12,则此处参数不需要配置
  # ------------------------------------------------------------------
  # the data layout formats to be passed into neural network when actually performing neural network, available options: NHWC/NCHW
  # If input_type_rt is configured as nv12, then this parameter does not need to be configured
  input_layout_rt: 'NCHW'

  # 网络训练时输入的数据格式,可选的值为rgb/bgr/gray/featuremap/yuv444
  # --------------------------------------------------------------------
  # the data formats in network training
  # available options: rgb/bgr/gray/featuremap/yuv444
  input_type_train: 'rgb'

  # 网络训练时输入的数据排布, 可选值为 NHWC/NCHW
  # ------------------------------------------------------------------
  # the data layout in network training, available options: NHWC/NCHW
  input_layout_train: 'NCHW'

  # (选填) 模型网络的输入大小, 以'x'分隔, 不填则会使用模型文件中的网络输入大小,否则会覆盖模型文件中输入大小
  # -------------------------------------------------------------------------------------------
  # (Optional)the input size of model network, seperated by 'x'
  # note that the network input size of model file will be used if left blank
  # otherwise it will overwrite the input size of model file
  input_shape: ''

  # 网络实际执行时,输入给网络的batch_size, 默认值为1
  # ---------------------------------------------------------------------
  # the data batch_size to be passed into neural network when actually performing neural network, default value: 1
  #input_batch: 1
  
  # 网络输入的预处理方法,主要有以下几种:
  # no_preprocess 不做任何操作
  # data_mean 减去通道均值mean_value
  # data_scale 对图像像素乘以data_scale系数
  # data_mean_and_scale 减去通道均值后再乘以scale系数
  # -------------------------------------------------------------------------------------------
  # preprocessing methods of network input, available options:
  # 'no_preprocess' indicates that no preprocess will be made 
  # 'data_mean' indicates that to minus the channel mean, i.e. mean_value
  # 'data_scale' indicates that image pixels to multiply data_scale ratio
  # 'data_mean_and_scale' indicates that to multiply scale ratio after channel mean is minused
  norm_type: 'data_scale'

  # 图像减去的均值, 如果是通道均值,value之间必须用空格分隔
  # --------------------------------------------------------------------------
  # the mean value minused by image
  # note that values must be seperated by space if channel mean value is used
  mean_value: ''

  # 图像预处理缩放比例,如果是通道缩放比例,value之间必须用空格分隔
  # ---------------------------------------------------------------------------
  # scale value of image preprocess
  # note that values must be seperated by space if channel scale value is used
  scale_value: 0.003921568627451

# 模型量化相关参数
# -----------------------------
# model calibration parameters
calibration_parameters:

  # 模型量化的参考图像的存放目录,图片格式支持Jpeg、Bmp等格式,输入的图片
  # 应该是使用的典型场景,一般是从测试集中选择20~100张图片,另外输入
  # 的图片要覆盖典型场景,不要是偏僻场景,如过曝光、饱和、模糊、纯黑、纯白等图片
  # 若有多个输入节点, 则应使用';'进行分隔
  # -------------------------------------------------------------------------------------------------
  # the directory where reference images of model quantization are stored
  # image formats include JPEG, BMP etc.
  # should be classic application scenarios, usually 20~100 images are picked out from test datasets
  # in addition, note that input images should cover typical scenarios
  # and try to avoid those overexposed, oversaturated, vague, 
  # pure blank or pure white images
  # use ';' to seperate when there are multiple input nodes
  cal_data_dir: './cal_data'

  # 如果输入的图片文件尺寸和模型训练的尺寸不一致时,并且preprocess_on为true,
  # 则将采用默认预处理方法(skimage resize),
  # 将输入图片缩放或者裁减到指定尺寸,否则,需要用户提前把图片处理为训练时的尺寸
  # ---------------------------------------------------------------------------------
  # In case the size of input image file is different from that of in model training
  # and that preprocess_on is set to True,
  # shall the default preprocess method(skimage resize) be used
  # i.e., to resize or crop input image into specified size
  # otherwise user must keep image size as that of in training in advance
  preprocess_on: True

  # 模型量化的算法类型,支持kl、max、default、load,通常采用default即可满足要求, 若为QAT导出的模型, 则应选择load
  # ----------------------------------------------------------------------------------
  # types of model quantization algorithms, usually default will meet the need
  # available options:kl, max, default and load
  # if converted model is quanti model exported from QAT , then choose `load`
  calibration_type: 'default'

# 编译器相关参数
# ----------------------------
# compiler related parameters
compiler_parameters:

  # 编译策略,支持bandwidth和latency两种优化模式;
  # bandwidth以优化ddr的访问带宽为目标;
  # latency以优化推理时间为目标
  # -------------------------------------------------------------------------------------------
  # compilation strategy, there are 2 available optimization modes: 'bandwidth' and 'lantency'
  # the 'bandwidth' mode aims to optimize ddr access bandwidth
  # while the 'lantency' mode aims to optimize inference duration
  compile_mode: 'latency'

  # 设置debug为True将打开编译器的debug模式,能够输出性能仿真的相关信息,如帧率、DDR带宽占用等
  # -----------------------------------------------------------------------------------
  # the compiler's debug mode will be enabled by setting to True
  # this will dump performance simulation related information
  # such as: frame rate, DDR bandwidth usage etc.
  debug: False

  # 编译模型指定核数,不指定默认编译单核模型, 若编译双核模型,将下边注释打开即可
  # -------------------------------------------------------------------------------------
  # specifies number of cores to be used in model compilation 
  # as default, single core is used as this value left blank
  # please delete the "# " below to enable dual-core mode when compiling dual-core model
  # core_num: 2

  # 优化等级可选范围为O0~O3
  # O0不做任何优化, 编译速度最快,优化程度最低,
  # O1-O3随着优化等级提高,预期编译后的模型的执行速度会更快,但是所需编译时间也会变长。
  # 推荐用O2做最快验证
  # ----------------------------------------------------------------------------------------------------------
  # optimization level ranges between O0~O3
  # O0 indicates that no optimization will be made 
  # the faster the compilation, the lower optimization level will be
  # O1-O3: as optimization levels increase gradually, model execution, after compilation, shall become faster
  # while compilation will be prolonged
  # it is recommended to use O2 for fastest verification
  optimize_level: 'O3'

2.3.3 모델 성능 분석 및 튜닝

  이 섹션에서는 모델 성능을 평가하기 위해 Horizon에서 제공하는 도구의 사용을 소개합니다. 이러한 도구는 기본적으로 실제 실행과 동일한 성능 효과를 얻습니다. 현 단계에서 평가 결과가 기대에 미치지 못하는 경우, 다음을 수행하는 것이 좋습니다. 현 단계에서는 Horizon에 맞춰 최적화를 시도해 보세요. 성능 문제를 해결하는 데 권장됩니다.

# 使用 hb_perf
hb_perf yolov5_p6_512x512.bin

여기에 이미지 설명을 삽입하세요.
실행 결과에 대한 자세한 분석은
여기에 이미지 설명을 삽입하세요.
공식 문서를 참조하시기 바랍니다. 여기서는 다루지 않습니다.

2.3.4 모델 정확도 분석 및 튜닝(출력 기반 추론)

추론을 위해 모델 변환의 출력을 사용하는 방법. 앞서 언급했듯이 성공적인 모델 변환의 결과에는 다음 네 가지 부분이 포함됩니다.

***_original_float_model.onnx
***_optimized_float_model.onnx
***_Quantized_model.onnx
***.bin

bin 모델은 AI 칩에 배치될 모델이지만, Ubuntu/CentOS 개발 머신에서 정확도 평가를 완료하는 편의성을 고려하여 정확도 평가 프로세스를 완료하기 위해 **_Quantized_model.onnx를 제공합니다. 양자화된 모델은 양자화를 완료했으며 최종 Bin 모델과 동일한 정확도 효과를 갖습니다.

이 예제는 후처리 코드를 다시 작성합니다. 자세한 내용은 github을 참조하세요. 전체 코드 코드 링크

# 仿真
04_inference.sh 

# 输出检测结果 result.jpg

여기에 이미지 설명을 삽입하세요.

참고자료

[1] 《Horizon AI 툴체인 사용자 가이드》
[2] https://developer.horizon.ai/forumDetail/136488103547258769

추천

출처blog.csdn.net/zhangqian_1/article/details/128243698