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 ...
随机推荐
- 小程序bindinput和bindblur赋值延迟问题解决
小程序bindinput和bindblur赋值延迟问题解决 问题链接:https://developers.weixin.qq.com/community/develop/doc/000a0ebdc4 ...
- RxJS 系列 – Join Operators
前言 前几篇介绍过了 Creation Operators Filtering Operators Join Creation Operators Error Handling Operators T ...
- Magic Quadrant 魔力象限
前言 在做 Web Application Firewall research 的时候看见了一张图. 这格式之前也看见过, 但没怎么上心, 现在才注意到它很好表达了行业或者产品的市场格局. 于是特地 ...
- Identity – Authorize Custom Authorization Policy Providers
前言 上一篇讲完了基本使用 Policy-Based. 这一篇另外说一说怎么动态调用它. 参考: Custom Authorization Policy Providers using IAuthor ...
- JavaScript习题之选择题
console.log( (2==true)+1 )会弹出A trueB falseC 1D 2正确答案: C2 ==true为假,此时值为0 在JS中,"1555"+3的运行结果 ...
- BOOST库array使用 类似std库的vector
BOOST库的array, 类似std库的vector. 下图所示书籍的下载地址,我的另一篇博客内有记载: https://www.cnblogs.com/happybirthdaytoyou/p/ ...
- manim边学边做--图形间集合关系
几何图形间的集合关系,是数学和几何学中的一个基本概念, 通过计算不同形状(如圆形.矩形.三角形等)的交集和并集等关系,可以实现复杂的图形处理和视觉效果. manim中提供了4种计算几何形状间集合关系的 ...
- JDK线程池详解(全网最全-原理解析、源码详解)
频繁创建新线程的缺点? 不受控风险 系统资源有限,每个人针对不同业务都可以手动创建线程,并且创建标准不一样(比如线程没有名字).当系统运行起来,所有线程都在疯狂抢占资源,毫无规则,不好管控. 另外,过 ...
- LINQ 统计字符频率
var arr = new string[] {"test","zhulongxu","asdfdgd","yangmi" ...
- 04-react的基本:条件渲染
import reactDom from "react-dom" // 条件渲染 if else let loading = false // 写一个函数用于加载 const lo ...