C++ API
ONNX Runtime C++ API
Section titled “ONNX Runtime C++ API”ONNX Runtime C++ APIは、ONNXモデルをスコアリングするためのC APIのラッパーです。C APIよりも使いやすい、より高レベルのAPIを提供します。
APIはinclude/onnxruntime/core/session/onnxruntime_cxx_api.hにあります。
これは、APIを使用してONNXモデルをスコアリングする方法を示す簡単な使用例です。完全なコードはこちらです。
#include <onnxruntime_cxx_api.h>
#include <iostream>
int main() { // 環境の初期化 Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "test");
// セッションオプションの初期化 Ort::SessionOptions session_options; session_options.SetIntraOpNumThreads(1);
// CUDA実行プロバイダーを有効にする // OrtCUDAProviderOptions cuda_options; // session_options.AppendExecutionProvider_CUDA(cuda_options);
// モデルのロードとセッションの作成 const char* model_path = "model.onnx"; Ort::Session session(env, model_path, session_options);
// 入力テンソルの作成 Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault); std::vector<int64_t> input_shape = {1, 3, 224, 224}; size_t input_tensor_size = 1 * 3 * 224 * 224; std::vector<float> input_tensor_values(input_tensor_size); // 入力データを初期化 // ... std::vector<Ort::Value> input_tensors; input_tensors.push_back(Ort::Value::CreateTensor<float>(memory_info, input_tensor_values.data(), input_tensor_size, input_shape.data(), input_shape.size()));
// 推論の実行 const char* input_names[] = {"input"}; const char* output_names[] = {"output"}; auto output_tensors = session.Run(Ort::RunOptions{nullptr}, input_names, input_tensors.data(), 1, output_names, 1);
// 出力の取得 float* output_data = output_tensors[0].GetTensorMutableData<float>();
// 出力の処理 // ...
std::cout << "完了" << std::endl;
return 0;}APIリファレンス
Section titled “APIリファレンス”Ort::Env
Section titled “Ort::Env”Ort::Envオブジェクトは、ONNX Runtime環境を表します。これは、ロギングやスレッド処理などのグローバル状態を管理します。
Ort::SessionOptions
Section titled “Ort::SessionOptions”Ort::SessionOptionsオブジェクトは、セッションの作成時に使用されるオプションを構成するために使用されます。これらのオプションには、実行プロバイダー、スレッド処理オプション、およびその他の設定が含まれます。
Ort::Session
Section titled “Ort::Session”Ort::Sessionオブジェクトは、ONNXモデルを表します。モデルのロード、入力のバインド、および推論の実行に使用されます。
Ort::Value
Section titled “Ort::Value”Ort::Valueオブジェクトは、ONNX Runtimeのテンソルを表します。入力および出力データの保持に使用されます。
Ort::MemoryInfo
Section titled “Ort::MemoryInfo”Ort::MemoryInfoオブジェクトは、メモリ割り当てに関する情報を提供します。これは、CPUまたはGPUメモリにテンソルを作成するために使用できます。
スレッド処理
Section titled “スレッド処理”ONNX Runtimeは、推論を並列化するために複数のスレッドを使用できます。スレッドの数は、Ort::SessionOptionsオブジェクトを使用して設定できます。
// 2つのスレッドを使用するようにセッションを設定session_options.SetIntraOpNumThreads(2);実行プロバイダー
Section titled “実行プロバイダー”ONNX Runtimeは、さまざまなハードウェアアクセラレータで推論を実行するための実行プロバイダー(EP)をサポートしています。EPは、Ort::SessionOptionsオブジェクトを使用して有効にできます。
// CUDA実行プロバイダーを有効にするOrtCUDAProviderOptions cuda_options;session_options.AppendExecutionProvider_CUDA(cuda_options);カスタム演算子
Section titled “カスタム演算子”ONNX Runtimeは、カスタム演算子をサポートしています。カスタム演算子は、Ort::SessionOptionsオブジェクトを使用して登録できます。
// カスタム演算子ライブラリを登録session_options.RegisterCustomOpsLibrary("custom_op_library.so");