Windows 使用 Intel(R) Arc(TM) GPU 推理ONNX 模型
这不刚换了一个笔记本电脑,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 模型的更多相关文章
- windows如何查看nvidia显卡(GPU)的利用率和温度
windows如何查看nvidia显卡(GPU)的利用率和温度 nvidia-smi 只要在文件夹C:\Program Files\NVIDIA Corporation\NVSMI里找到文件nvidi ...
- 如何在windows中编写R程序包(转载)
网上有不少R包的编译过程介绍,挑选了一篇比较详细的,做了稍许修改后转载至此,与大家分享 如何在windows中编写R程序包 created by helixcn modified by binaryf ...
- 【狼窝乀野狼】Windows Server 2008 R 配置 Microsoft Server 2008 远程登录连接
如果你已经了解了,或者你已经经历了,那么此篇文章对你是毫无用处.因为文笔深处未必有自己亲身体验来的真实有效. 闲话少说,直接上菜. 最近脑子“抽筋”,想安装一个服务器来玩玩,那么怎么选择呢?我的PC是 ...
- 【原创】Linux基础之去掉windows中的\r
linux换行为\n,windows换行为\r\n,windows环境编辑的shell脚本在linux下执行会报错: line 2: $'\r': command not found 查看 # cat ...
- GPU的线程模型和内存模型
遇见C++ AMP:在GPU上做并行计算 Written by Allen Lee I see all the young believers, your target audience. I see ...
- 使用GPU训练TensorFlow模型
查看GPU-ID CMD输入: nvidia-smi 观察到存在序号为0的GPU ID 观察到存在序号为0.1.2.3的GPU ID 在终端运行代码时指定GPU 如果电脑有多个GPU,Tensorfl ...
- 调整的R方_如何选择回归模型
sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...
- TensorFlow在Windows上的CPU版本和GPU版本的安装指南(亲测有效)
安装说明 平台:Window.Ubuntu.Mac等操作系统 版本:支持GPU版本和CPU版本 安装方式:pip方式.Anaconda方式 attention: 在Windows上目前支持python ...
- Windows Form调用R进行绘图并显示
R软件功能非常强大,可以很好的进行各类统计,并能输出图形.下面介绍一种R语言和C#进行通信的方法,并将R绘图结果显示到WinForm UI界面上. 1 前提准备 安装R软件,需要安装32位的R软件,6 ...
- R 语言 Windows 环境 安装与Windows下制作R的package--Rtools
1.1 预装的软件 (所有软件都可以在 http://www.biosino.org/R/R-doc/Rm/ 和 http://www.biosino.org/R/requiredSoftWar ...
随机推荐
- 【测试平台开发】——07Vue前端框架实战——restful请求
本节主要是前后端接口的调用,以及前端如何进行封装接口 一.创建相关文件 在文件夹下创建http.js.api.js.user.js 1)http.js封装接口: 在src下创建api文件夹 添加htt ...
- .Net 5.0 WebAPI 发布至 CentOS 7 系统
〇.前言 本文主要介绍了在 CentOS 7 上部署 WebAPI 项目的过程. 先安装 .net 5.0 的环境,再创建一个示例项目并发布至 CentOS 上,同时列明了一些注意的点:最后将 dot ...
- 【YashanDB知识库】主备延迟故障分析方法
[标题]主备延迟故障分析方法 [问题分类]故障分析 [关键字]Yashandb.主备延迟 [问题描述]当数据库备机出现回放延迟时,需要通过一些手段分析延迟的原因.通过数据库的系统视图或操作系统监控数据 ...
- [Udemy] AWS Certified Data Analytics Specialty - 3.Processing
Lambda Lambda 经常起胶水的作用,就是粘合不同的service. 如下图例子 另外Requirement #1 也是一个例子,还有Requirement #3 除了Kinesis Data ...
- SQL Server – History Table (Audit/Archive Table)
前言 续上一篇的 Soft Delete 后, 我们继续来看看 History Table (Audit/Archive Table). Archive Table 市场上有了这样叫, 但我觉得它比较 ...
- 适用于 VitePress 的公告插件开发实记
前言 笔者维护的 VitePress 博客主题在近1年多的时间里集成了非常多功能,不少用户希望将里面的部分功能分离出来,方便在其它 VitePress 站点也可以独立使用. 其中分离的第一个组件类型的 ...
- Vue 3 + Vite + SuerMap iClient构建报错Uncaught TypeError utils.inherits is not a function
一.现象 Uncaught TypeError: utils.inherits is not a function 二.问题产生原因 Elasticsearch本身就需要这些东西,以前没有问题是因为W ...
- debian 12 编译 vlc/libvlc 支持 rtsp
debian 官方从11开始,不再提供支持 rtsp 的 VLC deb 包,通过 libvlc 播放 rtsp 也无法实现,因此需要自己编译. # 安装编译环境,编译依赖库以及 contrib 第三 ...
- 2023年6月中国数据库排行榜:OceanBase 连续七月踞榜首,华为阿里谋定快动占先机
群雄逐鹿,酣战墨坛. 2023年6月的 墨天轮中国数据库流行度排行 火热出炉,本月共有273个数据库参与排名.本月排行榜前十变动不大,可以用一句话概括为:OTO 组合连续两月开局,传统厂商GBase南 ...
- M.2移动硬盘打造Win To Go系统:高效分区存储文件全攻略
前言 大家好,我是 Frpee内网穿透 开发者 xnkyn, 曾经的我一直在互联网上学习技术,这次我要在博客园这片净土上给中国互联网技术做贡献,这是我在博客园写的第一篇技术文章,后续我会分享更多的技术 ...