Onnxruntime可以在CPU、GPU和其他加速器设备上运行。要确保Onnxruntime在GPU上运行,需要在代码中设置正确的设备选项。以下是一些示例代码,可以确保Onnxruntime在GPU上运行:

import onnxruntime as ort

# 创建一个session并设置GPU选项
ort_session = ort.InferenceSession('model.onnx', providers=['CUDAExecutionProvider'])

# 获取GPU设备信息
device_info = ort_session.get_providers()[0].get_device()

# 输出GPU设备信息
print(f"Using device: {device_info.description} ({device_info.type})")
#include <iostream>
#include <vector>
#include <chrono>

#include "onnxruntime_cxx_api.h"

int main() {
    Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "test");
    Ort::SessionOptions session_options;
    session_options.SetIntraOpNumThreads(1);
    session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_BASIC);
    
    // 设置GPU选项
    Ort::ThrowOnError(OrtSessionOptionsAppendExecutionProvider_CUDA(session_options, 0));
    
    Ort::Session session(env, "model.onnx", session_options);
    
    // 获取GPU设备信息
    Ort::ThrowOnError(OrtSessionGetInputDeviceName(session, 0, OrtDeviceAllocator, &device_name));
    
    // 输出GPU设备信息
    std::cout << "Using device: " << device_name << std::endl;
    Ort::AllocatorWithDefaultOptions allocator;
    // ...
}

这些示例代码使用了Onnxruntime的Python和C++ API,分别使用了providers参数和OrtSessionOptionsAppendExecutionProvider_CUDA函数来设置GPU选项。在创建session之后,可以使用get_providers()函数(Python)或OrtSessionGetInputDeviceName函数(C++)来获取当前使用的设备信息。

利用Onnxruntime推理其运行在什么设备上代码如何设置可以保证其在GPU上进行运行

原文地址: https://www.cveoy.top/t/topic/brd4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录