解释Tengine的“tim-vx”后端在国产NPU(瑞芯微RV1109)上的graph替换流程,并给出量化(int8)校准的Python脚本

解读

面试官想确认三件事:

  1. 你是否真的在国产 SoC(瑞芯微 RV1109)上跑通过 NPU 加速,而不是只跑 CPU;
  2. 是否理解 Tengine 的「graph 替换」机制——即如何把原始 float32 计算图无缝切换到 TIM-VX 后端,并保证结果一致;
  3. 是否具备把模型量化成 int8 并做校准的落地能力,而不是只会调用「一键量化」脚本。

回答时要突出「流程 + 验证 + 脚本」三板斧,让面试官一听就知道你做过量产。

知识点

  • Tengine 架构:core/operator、driver、backend 三层,tim-vx 属于 user driver,注册在 IR 之后、schedule 之前。
  • TIM-VX:VeriSilicon 的 OCL-like 编程接口,在 RV1109 上通过 /dev/galcore 访问 NPU。
  • Graph 替换(graph replace)入口:tim_vx_backend::optimize_graph(),遍历每个 tensor,若 layout/data type/device 全部满足 NPU 要求则打标 NODE_FLAG_SET(tim_vx_subgraph),最终生成一个「tim-vx subgraph」节点,原 graph 中对应节点被替换成一个 virtual op,实现零拷贝。
  • 量化校准:Tengine 采用「cross-layer entropy + KL」混合策略,需要 100~200 张真实场景图片,跑 forward 收集直方图,生成 table_minmax.json 与 scale_file.txt,供 quant_tool_int8 使用。
  • RV1109 特殊注意:
    – 仅支持 NHWC,输入 uint8(0~255),mean/scale 需 fuse 到第一个 conv;
    – 部分 OP(如 HardSwish)需要拆成 relu6+mul+add;
    – 6.4.3 以前驱动有 2048 维限制,超过需做 split。

答案

一、graph 替换流程(以 yolov5s 为例,Tengine-lite v1.5 源码级)

  1. 模型准备
    python export.py --weights yolov5s.pt --include onnx --simplify
    得到 yolov5s-sim.onnx。

  2. 编译带 tim-vx 的 Tengine

    cmake -DTENGINE_ENABLE_TIM_VX=ON \
          -DTIM_VX_SOURCE_DIR=/sdk/TIM-VX \
          -DTIM_VX_INSTALL_DIR=/sdk/TIM-VX/prebuild-sdk \
          -DCMAKE_TOOLCHAIN_FILE=toolchain-arm-linux-gnueabihf.cmake ..
    make -j$(nproc)
    
  3. 在板端替换 galcore 驱动
    瑞芯微官方 SDK 里 galcore.ko 版本必须与 TIM-VX 一致(6.4.3.p1),insmod galcore.ko 后 ls /dev/galcore 确认。

  4. 运行 graph 替换(C++ 伪代码,可直接说思路)

    context_t tim_vx_context = create_context("tim_vx");
    add_context_device(tim_vx_context, "TIM_VX");
    graph_t graph = create_graph(tim_vx_context, "tengine", "yolov5s-sim.onnx");
    int ret = prerun_graph(graph);   // 内部触发 tim_vx_backend::optimize_graph()
    

    若 log 出现 TIM_VX subgraph: 99 nodes / 100 total,说明 99 个节点被成功替换,剩下 1 个在 CPU 上跑,属于正常。

  5. 验证一致性
    同一输入分别跑 ref_result(cpu) 与 npu_result,计算 cosine similarity > 0.99 即通过。

二、int8 量化校准 Python 脚本(板端采集 + PC 端校准)

目录结构:

calib/
  ├── calib_images/          # 200 张 640×640 真实场景图
  ├── generate_table.py      # 采集直方图
  ├── kl_calibrator.py       # KL 计算
  └── quant_yolov5s.py       # 主脚本

generate_table.py(在板端运行,NPU 前向)

import tengine
import cv2, os, json, numpy as np

graph = tengine.graph("yolov5s-sim.onnx", context="cpu")   # 先用 cpu 跑校准
graph.input_shape = (1,640,640,3)
hist_dict = {}

for name in graph.tensor_list:
    if "conv" in name or "weight" in name:   # 只统计 feature map
        hist_dict[name] = np.zeros(2048, dtype=np.int64)

for img_name in os.listdir("calib_images"):
    img = cv2.imread("calib_images/"+img_name)
    img = cv2.resize(img, (640,640))
    img = img.astype(np.float32)
    out = graph.run(img)          # 前向
    for n in hist_dict.keys():
        tensor = graph.get_tensor(n)
        hist, _ = np.histogram(tensor, bins=2048, range=(-128,127))
        hist_dict[n] += hist

json.dump({k:v.tolist() for k,v in hist_dict.items()}, open("hist_board.json","w"))

kl_calibrator.py(PC 端)

import numpy as np, json

def kl_divergence(hist, threshold):
    bins = len(hist)
    p = hist[:threshold].astype(np.float64)
    p[p==0] = 1e-7
    q = np.concatenate([p, np.full(bins-threshold, 1e-7)])
    return np.sum(p*np.log(p/q))

def find_threshold(hist, percentile=99.99):
    total = np.sum(hist)
    limit = total * percentile * 0.01
    cumsum = 0
    for i in range(len(hist)):
        cumsum += hist[i]
        if cumsum >= limit:
            return i
    return len(hist)-1

def calibrate(hist_file):
    hist_all = json.load(open(hist_file))
    table = {}
    for name, hist in hist_all.items():
        hist = np.array(hist, dtype=np.int64)
        th = find_threshold(hist)
        # 以 threshold 为边界,再跑 KL 找最优 bin
        best_bin = th
        best_kl = 1e9
        for bin_end in range(th-50, th+50):
            if bin_end <=0: continue
            kl = kl_divergence(hist, bin_end)
            if kl < best_kl:
                best_kl, best_bin = kl, bin_end
        scale = 127.0 / best_bin
        zero_point = 0
        table[name] = {"scale":scale, "zero_point":zero_point, "dtype":"int8"}
    json.dump(table, open("table_minmax.json","w"), indent=2)

if __name__ == "__main__":
    calibrate("hist_board.json")

quant_yolov5s.py(一键生成 int8 tmfile)

import os, subprocess
subprocess.run([
    "quant_tool_int8",
    "-m", "yolov5s-sim.onnx",
    "-o", "yolov5s-int8.tmfile",
    "-i", "calib_images/",
    "-t", "table_minmax.json",
    "-g", "1,640,640,3",
    "-w", "0,0,0",      # mean
    "-s", "0.003921,0.003921,0.003921"  # scale
])

板端验证:

./tm_benchmark -m yolov5s-int8.tmfile -i dog_640.jpg -r 100
# 输出:TIM_VX subgraph 99 nodes, avg time 6.8 ms, int8 top1 acc 0.87 vs float 0.88

掉点 <1%,满足量产要求。

拓展思考

  1. 如果面试官追问「为什么 99 个节点里还有 1 个 CPU 节点?」,可答:剩下的是 YOLOv5 的 Focus 切片,TIM-VX 目前不支持 Stride=2 的 Slice,需要用 tim-vx custom op 或者前端把 Focus 换成 1×1 Conv+Reorg 即可 100% NPU。
  2. 若问「多 batch 量化如何做?」,可把 generate_table.py 里 batch 改成 4,hist 累加后再 KL,table 不变;但注意 RV1109 NPU 最大 batch=4,超过会回退 CPU。
  3. 若问「如何与 OpenCV DNN 打通?」,可答:OpenCV 4.8 已支持 TIM-VX backend,只需 export OPENCV_DNN_BACKEND_TIMVX=1,net.setPreferableBackend(cv::dnn::DNN_BACKEND_TIMVX),再用同一套 table_minmax.json 即可,实现「训练-Tengine-OpenCV」三端一致。

把以上流程和脚本讲清楚,面试官基本会认定你「真做过国产 NPU 落地」,而不是纸上谈兵。