> ## Documentation Index
> Fetch the complete documentation index at: https://dragonwingdocs.qualcomm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 转换和量化 AI 模型

> 使用 SNPE 或 QNN 工具将 PyTorch、TensorFlow、ONNX 或 LiteRT 中的 AI 模型转换并量化,以便部署到 Qualcomm 硬件上。

<Tabs>
  <Tab title="Neural Processing Engine">
    ## 使用 Qualcomm Neural Processing Engine SDK 移植模型

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/snpe-model-porting-flow.png" width="55%" />
    </Frame>

    ### 模型转换

    来自 PyTorch、ONNX、TensorFlow 或 TFLite 的预训练浮点、32 位精度模型作为输入,提供给 SNPE 转换器工具(`snpe-<framework>-to-dlc`),以将模型转换为特定于 Qualcomm 的模型中间表示,称为深度学习容器(DLC)。

    除了来自源框架的输入模型外,转换器还需要有关输入模型的其他详细信息,例如输入节点名称、其对应的输入维度以及任何输出张量名称(对于具有多个输出的模型)。

    有关所有可配置参数,请参阅[转换器](https://docs.qualcomm.com/doc/80-63442-10/topic/SNPE_general_tools.html),或通过运行以下命令查看命令行帮助:

    ```shell theme={null}
    snpe-<framework>-to-dlc --help
    ```

    **输出:**

    ```
    required arguments:

    -d INPUT_NAME INPUT_DIM, --input_dim INPUT_NAME INPUT_DIM
        The names and dimensions of the network input layers specified in the format
        [input_name comma-separated-dimensions], for example:
        'data' 1,224,224,3
         Note that the quotes should always be included in order to handle special
         characters, spaces, etc.
         For multiple inputs specify multiple --input_dim on the command line like:
         --input_dim 'data1' 1,224,224,3 --input_dim 'data2' 1,50,100,3
    --out_node OUT_NAMES, --out_name OUT_NAMES
         Name of the graph's output Tensor Names. Multiple output names should be
         provided separately like:
         --out_name out_1 --out_name out_2
    --input_network INPUT_NETWORK, -i INPUT_NETWORK
         Path to the source framework model.
    ```

    <Note>
      如果您的工作环境中没有 `yaml` 包,请使用以下命令安装:

      ```shell theme={null}
      pip install pyyaml
      ```
    </Note>

    以下示例使用从 [ONNX Model Zoo](https://github.com/onnx/models/blob/main/Computer_Vision/inception_v3_Opset16_timm/inception_v3_Opset16.onnx) 下载的 ONNX 模型(*inception\_v3\_opset16.onnx*)。

    将模型下载为 `inception_v3.onnx` 到您的工作区。在此示例中,我们将模型下载到 `~/models` 目录。

    运行以下命令以生成 `inception_v3.dlc` 模型。

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/snpe-onnx-to-dlc --input_network ~/models/inception_v3.onnx --output_path ~/models/inception_v3.dlc --input_dim 'x' 1,3,299,299
    ```

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/snpe-model-conversion.png" width="55%" />
    </Frame>

    ### 模型量化

    要在 Hexagon Tensor Processor(HTP)上运行模型,转换后的 DLC 必须进行量化。SNPE 提供了一个工具(`snpe-dlc-quant`),使用其自身的量化算法将 DLC 模型量化为 INT8/INT16 DLC。有关 SNPE 量化的更多信息,请参阅[量化模型](https://docs.qualcomm.com/doc/80-63442-10/topic/quantized_models.html)。

    SNPE 中的量化过程需要两个步骤:

    1. **量化模型内的权重和偏置。**

       权重和偏置的量化是一个静态步骤,即无需用户提供额外的输入数据。

    2. **量化激活层(或没有权重的层)。**

       激活层的量化需要来自训练数据集的一组输入图像作为校准数据。这些校准数据集图像作为 `.raw` 格式的预处理图像文件列表输入。这些输入 `.raw` 文件的文件大小必须与模型的输入大小匹配。

    `snpe-dlc-quant` 的输入是转换后的 DLC 模型和一个包含校准数据集图像路径的纯文本文件。此输入列表包含以 `.raw` 格式保存为 NumPy 数组的预处理图像的路径。预处理图像的大小必须与模型的输入分辨率匹配。

    `snpe-dlc-quant` 工具的输出是量化后的 DLC。

    ```
    [ --input_dlc=<val> ]
                 Path to the dlc container
                 containing the model for which fixed-point encoding metadata should be generated.
                 This argument is required.
    [ --input_list=<val> ] Path to a file
                 specifying the trial inputs. This file should be a plain text file, containing one
                 or more absolute file paths per line. These files will be taken to constitute the
                 trial set. Each path is expected to point to a binary file containing one trial
                 input in the 'raw' format, ready to be consumed by the tool without any further
                 modifications. This is similar to how input is provided to snpe-net-run
                 application.
    [ --output_dlc=<val> ] Path at which the
                 metadata-included quantized model container should be written. If this argument is
                 omitted, the quantized model will be written at
                 <unquantized_model_name>_quantized.dlc.
    ```

    <Note>
      使用 [Netron](https://github.com/lutzroeder/netron) 图形可视化工具来识别模型的输入/输出层维度。
    </Note>

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/snpe-model-quant-properties.png" width="55%" />
    </Frame>

    出于演示目的,我们可以使用随机输入文件评估量化过程。可以使用下面显示的简单 Python 脚本为 `inception_v3.onnx` 模型生成输入文件。将脚本另存为 `generate_random_input.py`,保存在工作区 `~/models/` 目录中,并在主机上使用 `python ~/models/generate_random_input.py` 运行。

    以下示例 Python 代码创建一个 input\_list,其中包含用于量化模型的校准数据集图像的路径。

    ```python theme={null}
    import os
    import numpy as np

    input_path_list =[]
    BASE_PATH = "/tmp/RandomInputsForInceptionV3"

    if not os.path.exists(BASE_PATH):
        os.mkdir(BASE_PATH)

    # generate 10 random inputs and save as raw
    NUM_IMAGES = 10

    #binary files
    for img in range(NUM_IMAGES):
        filename = "input_{}.raw".format(img)
        randomTensor = np.random.random((1, 299, 299, 3)).astype(np.float32)
        filename = os.path.join(BASE_PATH, filename)
        randomTensor.tofile(filename)
        input_path_list.append(filename)

    #for saving as input_list text
    with open("input_list.txt", "w") as f:
        for path in input_path_list:
            f.write(path)
            f.write("\n")
    ```

    上述脚本会生成 10 个示例输入文件,保存在 `/tmp/RandomInputsForInceptionV3/` 目录中,并生成一个 `input_list.txt` 文件,其中包含每个生成样本的路径。

    现在,`snpe-dlc-quant` 工具所需的所有输入均已就绪,可以对模型进行量化。

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/snpe-dlc-quant --input_dlc ~/models/inception_v3.dlc --output_dlc ~/models/inception_v3_quantized.dlc --input_list ~/models/input_list.txt
    ```

    这会生成一个量化后的 inception\_v3 DLC 模型(`inception_v3_quantized.dlc`)。默认情况下,模型会被量化为 INT8 位宽。

    通过向 `snpe-dlc-quant` 工具指定 `--act_bitwidth 16` 和/或 `--weights_bitwidth 16` 选项,可以自定义为使用 16 位而不是默认的 INT8。

    请参阅 [snpe-dlc-quant](https://docs.qualcomm.com/doc/80-63442-10/topic/SNPE_general_tools.html#snpe-dlc-quant) 工具文档,或运行 `snpe-dlc-quant --help` 以查看所有可用的自定义选项,包括量化模式、优化等。

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/snpe-model-quantization.png" width="55%" />
    </Frame>

    #### 模型优化

    量化后的模型 DLC 需要一个图准备步骤,以针对 HTP 上的执行进行优化。为准备模型 DLC 以在 HTP 上执行,SNPE 提供了一个 `snpe-dlc-graph-prepare` 工具,它以量化模型和硬件特定详细信息(例如芯片组)作为输入。

    <Note>
      针对 HTP 等硬件的优化取决于芯片组上存在的 HTP 特定版本。为确保对执行图应用正确的优化集,以最佳方式利用 HTP,向 `snpe-dlc-graph-prepare` 工具提供正确的芯片组 ID 非常重要。
    </Note>

    根据 HTP 版本和芯片组 ID,该工具会创建一个缓存,其中包含在 HTP 硬件上执行模型 DLC 的执行策略。如果没有此步骤,由于 SNPE 运行时必须动态创建执行策略,网络初始化时会有额外的开销。

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/snpe-dlc-graph-prepare --input_dlc ~/models/inception_v3_quantized.dlc --output_dlc ~/models/inception_v3_quantized_with_htp_cache.dlc --htp_socs qcs6490
    ```

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/snpe-model-optimization.png" width="55%" />
    </Frame>

    #### HTP 缓存信息

    完成 `snpe-dlc-graph-prepare` 步骤后,HTP 缓存记录将添加到 DLC 中。可以使用 `snpe-dlc-info` 工具查看此缓存信息。

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/snpe-dlc-info -i ~/models/inception_v3_quantized_with_htp_cache.dlc
    ```

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/snpe-cache.png" width="55%" />
    </Frame>
  </Tab>

  <Tab title="AI Engine Direct">
    ## 使用 AI Engine Direct 移植模型

    ### 模型转换和量化

    来自 PyTorch、ONNX、TensorFlow 或 TFLite 的预训练 FP32 模型作为输入,提供给 QNN 转换器工具(`qnn-<framework>-converter`),以将其转换为可读性高的 C++ 图形式的 QNN 图表示。

    在 HTP 上加速模型时,必须对模型进行量化。模型量化可以在转换的同一步骤中完成。必须提供校准数据集,以执行此静态量化步骤。

    要在转换的同时启用量化,请使用 `--input_list INPUT_LIST` 选项进行静态量化。

    有关更多信息,请参阅[量化支持](https://docs.qualcomm.com/doc/80-63442-10/topic/quantization.html)。

    以下示例使用从 [ONNX Model Zoo](https://github.com/onnx/models/blob/main/Computer_Vision/inception_v3_Opset16_timm/inception_v3_Opset16.onnx) 下载的 ONNX 模型(`inception_v3_opset16.onnx`)。

    将模型下载为 `inception_v3.onnx` 到您的工作区。在此示例中,模型下载到 `~/models` 目录。

    #### 模型转换:CPU 后端

    要转换模型以在 x86/基于 Arm 的 CPU 上运行,请运行以下命令以生成 `inception_v3.cpp` 和 `inception_v3.bin`。

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/qnn-onnx-converter --input_network ~/models/inception_v3.onnx --output_path ~/models/inception_v3.cpp --input_dim 'x' 1,3,299,299
    ```

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/qnn-conversion-output.png" width="55%" />
    </Frame>

    `inception_v3.cpp` 文件包含转换后模型的高层图表示。

    `inception_v3.bin` 文件包含模型的权重/偏置。

    #### 模型转换和量化:HTP 后端

    要在 HTP 上运行模型,需要进行量化步骤。

    对于 AI Engine Direct(QNN)SDK 中的量化,需要将来自训练数据集的 50 至 200 张具有代表性的图像作为校准数据集提供给 QNN 转换器。校准数据集中的图像已经过预处理(调整大小、归一化等),并以 `.raw` 格式保存为 NumPy 数组。这些输入 `.raw` 文件的大小必须与模型的输入大小匹配。

    <Note>
      使用 Netron 图形可视化工具来识别模型的输入/输出层维度。
    </Note>

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/qnn-conversion-model-props.png" width="55%" />
    </Frame>

    出于演示目的,您可以使用随机输入文件评估量化过程。可以使用下面显示的 Python 脚本为 `inception_v3.onnx` 模型生成输入文件。将脚本另存为 `generate_random_input.py`,保存在 `~/models/` 目录中,并使用 `python ~/models/generate_random_input.py` 运行。

    以下 Python 代码创建一个 input\_list,其中包含用于量化模型的校准数据集。

    ```python theme={null}
    import os
    import numpy as np

    input_path_list =[]

    BASE_PATH = "/tmp/RandomInputsForInceptionV3"

    if not os.path.exists(BASE_PATH):
        os.mkdir(BASE_PATH)

    # generate 10 random inputs and save as raw
    NUM_IMAGES = 10

    #binary files
    for img in range(NUM_IMAGES):
        filename = "input_{}.raw".format(img)
        randomTensor = np.random.random((1, 299, 299, 3)).astype(np.float32)
        filename = os.path.join(BASE_PATH, filename)
        randomTensor.tofile(filename)
        input_path_list.append(filename)

    #for saving as input_list text
    with open("input_list.txt", "w") as f:
        for path in input_path_list:
            f.write(path)
            f.write("\n")
    ```

    运行以下命令以进行转换和量化。

    默认情况下,模型会被量化为 INT8 位宽。您可以指定 `--act_bitwidth 16` 和/或 `--weights_bitwidth 16` 以使用 INT16 量化。

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/qnn-onnx-converter --input_network ~/models/inception_v3.onnx --output_path ~/models/inception_v3_quantized.cpp --input_list ~/models/input_list.txt --input_dim "x" 1,3,299,299
    ```

    这会在 `~/models/` 目录中生成 `inception_v3_quantized.cpp` 和 `inception_v3_quantized.bin` 文件。

    请参阅 [qnn-\<framework>-converter](https://docs.qualcomm.com/doc/80-63442-10/topic/general_tools.html) 或运行 `qnn-<framework>-converter --help` 以查看量化的所有可用自定义选项,包括量化模式、优化等。

    ### 模型编译

    转换/量化步骤完成后,使用 `qnn-model-lib-generator` 将生成的 C++ 图编译为共享对象(.so),使应用程序能够动态加载模型以执行推理。

    对于 x86,使用 Clang 编译器工具链将 C++ 图编译为 .so 库。对于嵌入式 Linux 设备(例如 Qualcomm Dragonwing™ RB3 Gen 2 和 IQ-9075),必须使用相应的编译器工具链(`aarch64-oe-linux-gcc11.2`)。

    #### 编译模型以在 x86 上运行

    1. 安装 GCC 版本 12 的 GNU 标准 C++ 库开发包。

       ```shell theme={null}
       sudo apt install libstdc++-12-dev
       ```

       此包包含编译和链接 C++ 程序所需的标准库头文件(如 `<limits>`、`<vector>` 和 `<string>`)、静态库和支持文件。

    2. 生成一个共享对象模型,以在基于 x86 的 Linux 计算机上运行。

       ```shell theme={null}
       ${QAIRT_ROOT}/bin/x86_64-linux-clang/qnn-model-lib-generator -c ~/models/inception_v3.cpp -b ~/models/inception_v3.bin -o ~/models/libs/ -t x86_64-linux-clang
       ```

       这会使用 Clang-14 编译器工具链将 C++ 图编译为与 x86 主机兼容的 QNN 模型 `.so`,从而生成 `inception_v3.so`。

    <Frame>
      <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/AI-Developer-Workflow-Ubuntu/_images/qnn-port-x86.png" width="55%" />
    </Frame>

    #### 编译模型以在目标设备上运行

    在为设备端执行(aarch64 架构)编译模型时,重要的是使用正确的交叉编译器工具链,以确保编译后的共享对象(.so)与设备操作系统兼容。

    以下步骤将安装编译模型 cpp 文件到 .so 库所需的交叉编译器工具链。安装相应交叉编译器工具链的说明可在[下载并安装 Platform SDK](https://imsdkdocs.qualcomm.com/advanced/yocto-build#download-and-install-the-sdk) 下找到。

    在安装 Platform SDK 并在新的命令行终端中设置交叉编译器环境之后。

    1. 检查环境是否已正确设置。

       ```shell theme={null}
       echo $SDKTARGETSYSROOT
       ```

       ```shell theme={null}
       echo $TARGET_PREFIX
       ```

       如果上述环境变量未填充,请在新的命令行终端中重复步骤 1。

    2. 设置 QAIRT 环境。

       ```shell theme={null}
       source ${QAIRT_ROOT}/bin/envsetup.sh
       ```

    #### 编译模型以在基于 Arm 的 CPU 上运行

    交叉编译器设置好后,使用以下命令在 `~/model/libs/aarch64-oe-linux-gcc11.2` 中生成 `libinception_v3.so`。通过命令行参数将此位置提供给 `qnn-model-lib-generator` 工具。

    <Note>
      此处使用的编译器工具链是 `aarch64-oe-linux-gcc11.2`。
    </Note>

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/qnn-model-lib-generator -c ~/models/inception_v3.cpp -b ~/models/inception_v3.bin -o ~/models/libs -t aarch64-oe-linux-gcc11.2
    ```

    #### 编译模型以在 HTP 上运行

    要在 HTP 上运行模型,以下命令会在 `~/models/libs/aarch64-oe-linux-gcc11.2` 中生成 `libinception_v3_quantized.so`。

    <Note>
      此处使用的编译器工具链是 `aarch64-oe-linux-gcc11.2`。
    </Note>

    ```shell theme={null}
    ${QAIRT_ROOT}/bin/x86_64-linux-clang/qnn-model-lib-generator -c ~/models/inception_v3_quantized.cpp -b ~/models/inception_v3_quantized.bin -o ~/models/libs/ -t aarch64-oe-linux-gcc11.2
    ```
  </Tab>
</Tabs>
