这不刚换了一个笔记本电脑,Thinkpad T14P,带有Intel ARC GPU,今天我们来尝试用这个GPU来推理ONNX模型。

环境安装

查阅了相关文档,最好使用py310环境,其他版本可能存在兼容性问题,然后按照以下命令安装:

# conda 环境
conda activate py310
# libuv
conda install libuv conda install -c conda-forge libjpeg-turbo libpng # torch
python -m pip install torch==2.3.1.post0+cxx11.abi torchvision==0.18.1.post0+cxx11.abi torchaudio==2.3.1.post0+cxx11.abi intel-extension-for-pytorch==2.3.110.post0+xpu --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/lnl/cn/ # onnxruntime
pip install onnxruntime-openvino openvino

测试

python -c "import torch; import intel_extension_for_pytorch as ipex; print(torch.__version__); print(ipex.__version__); [print(f'[{i}]: {torch.xpu.get_device_properties(i)}') for i in range(torch.xpu.device_count())];"

2.3.1.post0+cxx11.abi

2.3.110.post0+xpu

[0]: _XpuDeviceProperties(name='Intel(R) Arc(TM) Graphics', platform_name='Intel(R) Level-Zero', type='gpu', driver_version='1.3.31441', total_memory=16837MB, max_compute_units=112, gpu_eu_count=112, gpu_subslice_count=14, max_work_group_size=1024, max_num_sub_groups=128, sub_group_sizes=[8 16 32], has_fp16=1, has_fp64=1, has_atomic64=1)

加载detr模型

我们现在测试一下,使用DETR模型(https://github.com/facebookresearch/detr),我们先将训练好的模型转成onnx格式,然后使用onnxruntime进行推理。

先detr转onnx

def main(args):

    device = torch.device(args.device)

    # fix the seed for reproducibility
seed = args.seed + utils.get_rank()
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed) model, _, _ = build_model(args)
model.to(device) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
print('number of params:', n_parameters) checkpoint = torch.load(args.resume, map_location='cpu')
model.load_state_dict(checkpoint['model']) dynamic_axes={
"inputs": {0: "batch_size", 2: "height", 3: "width"}, # 改成 "inputs",以匹配 input_names
"pred_logits": {0: "batch_size"}, # 改成 "pred_logits" 和 "pred_boxes"
"pred_boxes": {0: "batch_size"}
} torch.onnx.export(
model,
torch.randn(1, 3, 800, 1200).to(device), # 示例输入大小
"model.onnx",
do_constant_folding=True,
opset_version=12,
dynamic_axes=dynamic_axes,
input_names=["inputs"],
output_names=["pred_logits", "pred_boxes"]
)

注意dynamic_axes 设置支持动态大小图片输入。

onnxruntime 推理

先转换为FP16模型,使用OpenVINOExecutionProvider作为推理后端。

from onnxruntime_tools import optimizer
from onnxconverter_common import float16 # 输入和输出模型路径
input_model_path = "./model.onnx"
fp16_model_path = "./model_fp16.onnx" # 加载 ONNX 模型
from onnx import load_model, save_model if not os.path.exists(fp16_model_path):
model = load_model(input_model_path)
# 转换为 FP16
model_fp16 = float16.convert_float_to_float16(model)
# 保存为 FP16 格式
save_model(model_fp16, fp16_model_path)
print(f"FP16 模型已保存至 {fp16_model_path}") ort_session = onnxruntime.InferenceSession(fp16_model_path, providers=['OpenVINOExecutionProvider']) # 公共方法:进行图像预处理和模型推理
def predict_image(image: Image.Image):
w, h = image.size
target_sizes = torch.as_tensor([int(h), int(w)]).unsqueeze(0) # 预处理图片
_trans = transform()
image, _ = _trans(image, target=None) # 记录推理的开始时间
start_time = time.time() # 进行 ONNX 推理
ort_inputs = {"inputs": image.unsqueeze(0).numpy().astype(np.float16)}
outputs = ort_session.run(None, ort_inputs) # 记录推理的结束时间
end_time = time.time()
inference_time = end_time - start_time # 推理耗时 # 解析输出
out_logits = torch.as_tensor(outputs[0])
out_bbox = torch.as_tensor(outputs[1]) prob = F.softmax(out_logits, -1)
scores, labels = prob[..., :-1].max(-1) # 转换坐标
boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
img_h, img_w = target_sizes.unbind(1)
scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
boxes = boxes * scale_fct[:, None, :] # 组织推理结果
results = [{'score': s, 'label': l, 'boxes': b, 'category': categories[l-1]['name']}
for s, l, b in zip(scores[0].tolist(), labels[0].tolist(), boxes[0].tolist()) if s > 0.9] print(f'predict cost {inference_time}') return results, inference_time

这里有个坑, onnxruntime-openvino 推理需要额外添加动态库, 否则报错onnxruntime::ProviderLibrary::Get [ONNXRuntimeError] : 1 : FAIL : LoadLibrary failed with error 126 "" when trying to load "onnxruntime\capi\onnxruntime_providers_openvino.dll" when using ['OpenVINOExecutionProvider'] Falling back to ['CPUExecutionProvider'] and retrying.,这里我使用的是Windows系统,所以需要添加动态库。


import platform # ref https://github.com/microsoft/onnxruntime-inference-examples/issues/117
if platform.system() == "Windows":
import onnxruntime.tools.add_openvino_win_libs as utils
utils.add_openvino_libs_to_path()

测试下:

INFO:     127.0.0.1:64793 - "POST /predict HTTP/1.1" 200 OK
predict cost 0.3524954319000244

0.35秒,还行,马马虎虎!

Windows 使用 Intel(R) Arc(TM) GPU 推理ONNX 模型的更多相关文章

  1. windows如何查看nvidia显卡(GPU)的利用率和温度

    windows如何查看nvidia显卡(GPU)的利用率和温度 nvidia-smi 只要在文件夹C:\Program Files\NVIDIA Corporation\NVSMI里找到文件nvidi ...

  2. 如何在windows中编写R程序包(转载)

    网上有不少R包的编译过程介绍,挑选了一篇比较详细的,做了稍许修改后转载至此,与大家分享 如何在windows中编写R程序包 created by helixcn modified by binaryf ...

  3. 【狼窝乀野狼】Windows Server 2008 R 配置 Microsoft Server 2008 远程登录连接

    如果你已经了解了,或者你已经经历了,那么此篇文章对你是毫无用处.因为文笔深处未必有自己亲身体验来的真实有效. 闲话少说,直接上菜. 最近脑子“抽筋”,想安装一个服务器来玩玩,那么怎么选择呢?我的PC是 ...

  4. 【原创】Linux基础之去掉windows中的\r

    linux换行为\n,windows换行为\r\n,windows环境编辑的shell脚本在linux下执行会报错: line 2: $'\r': command not found 查看 # cat ...

  5. GPU的线程模型和内存模型

    遇见C++ AMP:在GPU上做并行计算 Written by Allen Lee I see all the young believers, your target audience. I see ...

  6. 使用GPU训练TensorFlow模型

    查看GPU-ID CMD输入: nvidia-smi 观察到存在序号为0的GPU ID 观察到存在序号为0.1.2.3的GPU ID 在终端运行代码时指定GPU 如果电脑有多个GPU,Tensorfl ...

  7. 调整的R方_如何选择回归模型

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  8. TensorFlow在Windows上的CPU版本和GPU版本的安装指南(亲测有效)

    安装说明 平台:Window.Ubuntu.Mac等操作系统 版本:支持GPU版本和CPU版本 安装方式:pip方式.Anaconda方式 attention: 在Windows上目前支持python ...

  9. Windows Form调用R进行绘图并显示

    R软件功能非常强大,可以很好的进行各类统计,并能输出图形.下面介绍一种R语言和C#进行通信的方法,并将R绘图结果显示到WinForm UI界面上. 1 前提准备 安装R软件,需要安装32位的R软件,6 ...

  10. R 语言 Windows 环境 安装与Windows下制作R的package--Rtools

    1.1    预装的软件 (所有软件都可以在 http://www.biosino.org/R/R-doc/Rm/ 和 http://www.biosino.org/R/requiredSoftWar ...

随机推荐

  1. 2024 NepCTF

    NepCTF NepMagic -- CheckIn 直接玩游戏就能出 注意有一关要把隐藏的方块全找到 NepCamera 先使用tshark读取数据 结果文件中发现大量jpeg头ffd8ffe0. ...

  2. 第1章-JSP 简介

    目录 什么是JSP 安装配置JSP运行环境 JSP页面 JSP页面简介 设置Web服务目录 JSP运行原理 JSP 与Java Servlet的关系 HTML与JavaScript 什么是JSP ★ ...

  3. AI实战 | 领克汽车线上营销助手:全面功能展示与效果分析

    助手介绍 我就不自我介绍了,在我的智能体探索之旅中,很多人已经通过coze看过我的教程.今天,我专注于分享我所开发的一款助手--<领克汽车线上营销>. 他不仅仅是一个销售顾问的替身,更是一 ...

  4. ASP.NET Core – Web API 冷知识

    Under/Over Posting 参考: .NET Core WebApi Action is executed even with missing properties in the reque ...

  5. LiveChat vs LiveAgent vs Front vs Email

    它们是什么? LiveChat, LiveAgent 算是同类产品. LiveChat 的核心(或者说起点)是 live chat 这个功能, 而 LiveAgent 的核心是 ticket. 如果拿 ...

  6. Flutter(able) 的单例模式

    文/ 杨加康,CFUG 社区成员,<Flutter 开发之旅从南到北>作者,小米工程师 单例设计模式(Singleton Design Pattern)理解起来非常简单. 一个类只允许创建 ...

  7. 30. 串联所有单词的子串 Golang实现

    题目描述: 给定一个字符串 s 和一个字符串数组 words. words 中所有字符串 长度相同 . s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串. 例如, ...

  8. 多Master节点的k8s集群部署-完整版

    多Master节点的k8s集群部署 一.准备工作 1.准备五台主机(三台Master节点,一台Node节点,一台普通用户)如下: 角色 IP 内存 核心 磁盘 Master01 192.168.116 ...

  9. 仿函数(Functor)是什么?

    仿函数(Functor) 仿函数是通过重载()运算符的类或结构体的对象.这样一个对象可以像普通函数一样被调用. 仿函数通常用于需要在对象内部保留状态或多次调用时有特定行为的情况. 特点: 仿函数是一个 ...

  10. Android usb广播 ACTION_USB_DEVICE_ATTACHED流程源码分析

    整体流程图 大概意思就是UsbHostManager启动监控线程,monitorUsbHostBus会调用usb_host_run函数(使用inotify来监听USB设备的插拔)不停的读取bus总线, ...