Arm Ethos‑U65:YOLOv8n 模型准备与 Vela 编译

发布时间:2026/7/18 13:49:48
Arm Ethos‑U65:YOLOv8n 模型准备与 Vela 编译 本文是 Arm Ethos‑U65 学习笔记的第四篇接下来两篇将基于 U65 实现一个 YOLO v8n 目标检测实例其中本篇完成模型准备与 Vela 编译生成命令流下一篇将命令流导入芯片仿真环境执行推理验证整个示例以芯片验证仿真为主线同时对裸机环境下的软件开发也有一定参考价值。模型选取YOLO v8n正常流程需要将模型按照 Tensorflow lite 格式量化这里直接使用现成 YOLO v8n tflite 模型https://github.com/camthink-ai/ne302/blob/main/Model/weights/yolov8n_256_quant_pc_ui_od_coco.tflite查看模型可以看到输入是256x256x3 uint8输出是1x84x1344 int8对应80个分类1344个框。需要注意 tflite 模型是不包含后处理的后处理需要外部实现阈值比较、排序和 NMS同时需要给模型提供前处理后的数据resize 和格式转换。检测程序python程序下面完成基于 YOLO v8n tflite 实现目标检测的python程序大体流程为a)将图像resize成256x256再量化为uint8。b)执行推理通过tf.lite.Interpreter方法运行tfllite网络得到输出结果。c)将输出反量化为浮点。d)对于每个窗找到80个置信度中最大值再和阈值比对筛选出大于阈值的点。e)进行nms去掉重合的窗。f)框坐标resize恢复添加到图片中。后面芯片仿真验证流程还需要复用程序的 c~f 也就是后处理部分。tfile_model_run_yolov8n.pyimportcv2importnumpyasnpimporttensorflowastf# ---------- 配置 ----------MODEL_PATH./tfile_model/yolov8n_256_quant_pc_ui_od_coco.tfliteIMAGE_PATHbike.jpgCONFIDENCE_THRESHOLD0.5# 置信度阈值IOU_THRESHOLD0.45# NMS 的 IOU 阈值INPUT_SIZE256# 模型输入尺寸 (256x256)# 只关心这些类别的索引 (COCO: person0, bicycle1, car2)TARGET_CLASS_IDS [0, 1, 2]TARGET_CLASS_NAMES[person,bicycle,car]# ---------- 加载模型 ----------interpretertf.lite.Interpreter(model_pathMODEL_PATH)interpreter.allocate_tensors()input_detailsinterpreter.get_input_details()output_detailsinterpreter.get_output_details()# 获取输入类型应为 uint8input_dtypeinput_details[0][dtype]input_shapeinput_details[0][shape]# [1, 256, 256, 3]# ---------- 后处理函数 ----------defsigmoid(x):return1/(1np.exp(-x))defdecode_yolov8_output(output,input_width,input_height,conf_threshold):# 去除 batch 维度predsnp.transpose(output,(0,2,1))[0]# preds shape: (num_anchors, 84)boxes[]scores[]class_ids[]forpredinpreds:# 前4个是 bbox (cx, cy, w, h) 归一化到 0~1 cx, cy, w, h pred[:4]# 后80个是类别得分class_scorespred[4:]# 最大得分及其类别class_idnp.argmax(class_scores)scoreclass_scores[class_id]# 过滤低置信度ifscoreconf_threshold:continue# 只关心指定类别ifclass_idnotinTARGET_CLASS_IDS:continue# 将中心坐标和宽高转换为左上角和右下角 (x1,y1,x2,y2) 归一化到 0~1 x1cx-w/2y1cy-h/2x2cxw/2y2cyh/2# 限制在 [0,1] 范围内x1max(0,min(1,x1))y1max(0,min(1,y1))x2max(0,min(1,x2))y2max(0,min(1,y2))boxes.append([x1,y1,x2,y2])scores.append(float(score))class_ids.append(class_id)returnboxes,scores,class_idsdefnms(boxes,scores,iou_threshold): 非极大值抑制返回保留的索引列表 iflen(boxes)0:return[]boxesnp.array(boxes)# 计算每个框的面积areas(boxes[:,2]-boxes[:,0])*(boxes[:,3]-boxes[:,1])# 按置信度降序排序indicesnp.argsort(scores)[::-1]keep[]whilelen(indices)0:currentindices[0]keep.append(current)iflen(indices)1:break# 计算当前框与其余框的IOUotherindices[1:]xx1np.maximum(boxes[current,0],boxes[other,0])yy1np.maximum(boxes[current,1],boxes[other,1])xx2np.minimum(boxes[current,2],boxes[other,2])yy2np.minimum(boxes[current,3],boxes[other,3])wnp.maximum(0,xx2-xx1)hnp.maximum(0,yy2-yy1)intersectionw*h iouintersection/(areas[current]areas[other]-intersection)# 保留IOU低于阈值的框indicesindices[1:][iouiou_threshold]returnkeep# ---------- 主程序 ----------if__name____main__:# 读取图像imgcv2.imread(IMAGE_PATH)orig_h,orig_wimg.shape[:2]# 预处理调整大小并转换为 uint8 (模型期望)img_rgbcv2.cvtColor(img,cv2.COLOR_BGR2RGB)resizedcv2.resize(img_rgb,(INPUT_SIZE,INPUT_SIZE))input_tensornp.expand_dims(resized,axis0).astype(np.uint8)# 推理interpreter.set_tensor(input_details[0][index],input_tensor)interpreter.invoke()# 获取输出# 可能模型有多个输出但通常只有一个先取第一个outputinterpreter.get_tensor(output_details[0][index])# 处理量化输出需要反量化scale,zero_pointoutput_details[0][quantization]# 反量化float_val (quant_val - zero_point) * scaleoutput(output.astype(np.float32)-zero_point)*scaleprint(f原始输出形状:{output.shape})# 解码输出boxes,scores,class_idsdecode_yolov8_output(output,INPUT_SIZE,INPUT_SIZE,CONFIDENCE_THRESHOLD)# 执行 NMS (对所有类别一起做)keep_indicesnms(boxes,scores,IOU_THRESHOLD)final_boxes[boxes[i]foriinkeep_indices]final_scores[scores[i]foriinkeep_indices]final_class_ids[class_ids[i]foriinkeep_indices]# 绘制检测结果for(x1,y1,x2,y2),score,cls_idinzip(final_boxes,final_scores,final_class_ids):# 将归一化坐标转换为原图尺寸x1int(x1*orig_w)y1int(y1*orig_h)x2int(x2*orig_w)y2int(y2*orig_h)# 绘制矩形和标签labelf{TARGET_CLASS_NAMES[TARGET_CLASS_IDS.index(cls_id)]}{score:.2f}cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)cv2.putText(img,label,(x1,y1-5),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2)# 显示图像cv2.imshow(Result,img)cv2.waitKey(0)cv2.destroyAllWindows()运行程序对人、汽车、自行车进行了识别。Vela编译Vela 安装和执行Vela 是 ARM 开发的一款编译器工具可以将 TensorFlow Lite 模型.tflite文件编译为Ethos U65 可以执行的命令流编译同时会对模型会进行权重压缩、内存分配等优化这个优化过程不会有精度损失。Vela 以 python 软件包形式使用首先通过 pip 安装。pip install ethos-u-vela安装后可以直接在端口执行指定模型、NPU版本和输出路径。vela ./tfile_model/yolov8n_256_quant_pc_ui_od_coco.tflite --accelerator-config ethos-u65-512 --output-dir ./output运行后会生成带 _vela 后缀的 tflite 格式文件生成文件并不是网络只是借用了 .tflite 格式文件实际内容是命令流权重下图中的1和2命令流可以通过hex格式打开查看权重因为经过压缩直接看会对不上。Vela指令运行 Vela 指令的同时会打印 log 信息能看到存储和带宽使用情况还可以通过添加指令后缀调整存储使用和优化策略、查看更多信息项。vela -h 可以显示所有命令后缀更推荐的是直接查看 Vela 官方文档。https://gitlab.arm.com/artificial-intelligence/ethos-u/ethos-u-vela通过 --memory-mode 可以指定存储使用模式支持 Shared_Sram 和 Dedicated Sram通过 --config 可以指定配置文件通过 --system-config 可以指定系统配置。后两者可以在vela安装目录找到参考 …\Lib\site-packages\ethosu\config_files\Arm\vela.ini。--memory-mode Shared_Sram --config Arm/vela.ini --system-config Ethos_U55_High_End_Embedded调试信息有2条比较有用的调试指令后缀。--verbose-high-level-command-stream high-level-command.log --verbose-register-command-stream register-command.log通过high-level-command可以看到优化后的网络结构可以看到原尺寸已经被拆分成 Block 尺寸。通过register-command可以直接看到带注释的命令行。