ONNX Runtime处理CuPy数组预测遇错误,求解决方法及GPU版本安装方案
问题解决指南
一、输入类型错误的原因与解决
错误原因
CPU版本的ONNX Runtime仅支持NumPy数组或CPU端张量作为输入,无法直接识别CuPy数组(CuPy数组存储在GPU内存中),因此触发类型不匹配的报错。
解决方法
临时兼容方案(仅预处理GPU加速,推理仍在CPU)
在将CuPy数组传入ONNX Runtime前,通过get()方法将其转换为NumPy数组(数据从GPU拷贝到CPU):def predict(path): img = get_cuimage(path) img = preprocess_gpu(img) # 转换CuPy数组为NumPy数组 ort_inputs = {session.get_inputs()[0].name: img.get()} preds = session.run(None, ort_inputs)[0] preds = np.squeeze(preds) a = np.argsort(preds)[::-1] print('class=%s ; probability=%f' %(labels[a[0]], preds[a[0:1]]))完整GPU加速方案(预处理+推理全GPU)
必须安装GPU版本的ONNX Runtime,它支持直接接收CuPy数组(无需数据拷贝),实现端到端GPU加速。
二、Conda无法找到onnxruntime-gpu的解决办法
使用conda-forge频道安装
conda默认频道可能没有onnxruntime-gpu,添加conda-forge频道后再安装:conda install -c conda-forge onnxruntime-gpu匹配CUDA版本安装
onnxruntime-gpu与CUDA版本强绑定,先检查系统CUDA版本:nvcc --version根据CUDA版本选择对应onnxruntime-gpu版本,若Conda渠道无匹配版本,改用pip安装:
pip install onnxruntime-gpu==<对应版本号>环境前置检查
- 确保Conda环境为64位(32位环境不支持GPU版ONNX Runtime)
- Windows用户需先安装对应版本的CUDA Toolkit(可通过Conda安装:
conda install -c nvidia cuda-toolkit)
内容的提问来源于stack exchange,提问作者JOKKINATOR
相关产品推荐
相关产品推荐

