ONNX Runtime GenAI C++ API
注意:此 API 处于预览阶段,可能会发生变化。
- 概述
- OgaModel
- OgaConfig
- OgaRuntimeSettings
- OgaTokenizer
- OgaTokenizerStream
- OgaSequences
- OgaGeneratorParams
- OgaGenerator
- OgaTensor
- OgaImages
- OgaAudios
- OgaNamedTensors
- OgaAdapters
- OgaMultiModalProcessor
- OgaHandle
- Oga 实用函数
概述
本文档描述了 ONNX Runtime GenAI 的 C++ API。
以下是主要类和方法,并附有代码片段和详细说明。
OgaModel
Create
从配置目录创建模型,可选择包含运行时设置或配置对象。
auto model = OgaModel::Create("path/to/model_dir");
auto model2 = OgaModel::Create("path/to/model_dir", *settings);
auto model3 = OgaModel::Create(*config);
GetType
获取模型的类型。
auto type = model->GetType();
GetDeviceType
获取模型使用的设备类型。
auto device_type = model->GetDeviceType();
OgaConfig
Create
从配置路径创建配置对象。
auto config = OgaConfig::Create("path/to/model_dir");
ClearProviders
清除配置中的所有提供程序。
config->ClearProviders();
AppendProvider
向配置中添加提供程序。
config->AppendProvider("CUDAExecutionProvider");
SetProviderOption
设置配置中的提供程序选项。
config->SetProviderOption("CUDAExecutionProvider", "device_id", "0");
Overlay
将 JSON 字符串覆盖到配置上。
config->Overlay("{\"option\": \"value\"}");
OgaRuntimeSettings
Create
创建一个运行时设置对象。
auto settings = OgaRuntimeSettings::Create();
SetHandle
在运行时设置中设置一个命名的句柄。
settings->SetHandle("custom_handle", handle_ptr);
OgaTokenizer
Create
为给定的模型创建一个分词器。
auto tokenizer = OgaTokenizer::Create(*model);
Encode
对字符串进行编码,并将编码后的 token 序列添加到提供的 OgaSequences 中。
auto sequences = OgaSequences::Create();
tokenizer->Encode("Hello world", *sequences);
EncodeBatch
批量编码字符串。
const char* texts[] = {"Hello", "World"};
auto tensor = tokenizer->EncodeBatch(texts, 2);
ToTokenId
将字符串转换为其对应的 token ID。
int32_t token_id = tokenizer->ToTokenId("Hello");
Decode
将标记序列解码为字符串。
auto str = tokenizer->Decode(tokens, token_count);
ApplyChatTemplate
将聊天模板应用于消息和工具。
auto templated = tokenizer->ApplyChatTemplate("template", "messages", "tools", true);
DecodeBatch
批量解码 token 序列。
auto decoded = tokenizer->DecodeBatch(*tensor);
OgaTokenizerStream
Create
创建用于增量解码的分词器流。
auto stream = OgaTokenizerStream::Create(*tokenizer);
Decode
解码流中的单个 token。如果这生成了一个新词,则会将其返回。
const char* chunk = stream->Decode(token);
OgaSequences
Create
创建一个空的 OgaSequences 对象。
auto sequences = OgaSequences::Create();
Count
返回序列的数量。
size_t n = sequences->Count();
SequenceCount
返回指定索引处序列中的 token 数量。
size_t tokens = sequences->SequenceCount(0);
SequenceData
返回指向指定索引处序列的 token 数据的指针。
const int32_t* data = sequences->SequenceData(0);
Append
向序列中追加一个 token 序列或单个 token。
sequences->Append(tokens, token_count);
sequences->Append(token, sequence_index);
OgaGeneratorParams
Create
为给定的模型创建生成器参数。
auto params = OgaGeneratorParams::Create(*model);
SetSearchOption
设置数值搜索选项。
params->SetSearchOption("max_length", 128);
SetSearchOptionBool
设置布尔值搜索选项。
params->SetSearchOptionBool("do_sample", true);
SetModelInput
设置额外的模型输入。
params->SetModelInput("input_name", *tensor);
SetInputs
将命名的张量设置为输入。
params->SetInputs(*named_tensors);
SetGuidance
设置引导数据。
params->SetGuidance("type", "data");
OgaGenerator
Create
从给定的模型和参数创建生成器。
auto generator = OgaGenerator::Create(*model, *params);
IsDone
检查生成是否完成。
bool done = generator->IsDone();
AppendTokenSequences
向生成器追加 token 序列。
generator->AppendTokenSequences(*sequences);
AppendTokens
向生成器追加 token。
generator->AppendTokens(tokens, token_count);
IsSessionTerminated
检查会话是否已终止。
bool terminated = generator->IsSessionTerminated();
GenerateNextToken
生成下一个标记。
generator->GenerateNextToken();
RewindTo
将序列回退到新的长度。
generator->RewindTo(new_length);
SetRuntimeOption
设置运行时选项。
generator->SetRuntimeOption("terminate_session", "1");
GetSequenceCount
返回指定索引处序列中的 token 数量。
size_t count = generator->GetSequenceCount(0);
GetSequenceData
返回指向指定索引处序列数据的指针。
const int32_t* data = generator->GetSequenceData(0);
GetOutput
获取命名的输出张量。
auto tensor = generator->GetOutput("output_name");
GetLogits
获取 logits 张量。
auto logits = generator->GetLogits();
SetLogits
设置 logits 张量。
generator->SetLogits(*tensor);
SetActiveAdapter
为生成器设置活动适配器。
generator->SetActiveAdapter(*adapters, "adapter_name");
OgaTensor
Create
从缓冲区创建张量。
auto tensor = OgaTensor::Create(data, shape, shape_dims_count, element_type);
Type
返回张量的元素类型。
auto type = tensor->Type();
Shape
返回张量的形状。
auto shape = tensor->Shape();
Data
返回指向张量数据的指针。
void* data = tensor->Data();
OgaImages
Load
从文件路径或内存缓冲区加载图像。
std::vector<const char*> image_paths = {"img1.png", "img2.png"};
auto images = OgaImages::Load(image_paths);
auto images2 = OgaImages::Load(image_data_ptrs, image_sizes, count);
OgaAudios
Load
从文件路径或内存缓冲区加载音频。
std::vector<const char*> audio_paths = {"audio1.wav", "audio2.wav"};
auto audios = OgaAudios::Load(audio_paths);
auto audios2 = OgaAudios::Load(audio_data_ptrs, audio_sizes, count);
OgaNamedTensors
Create
创建命名的张量对象。
auto named_tensors = OgaNamedTensors::Create();
Get
按名称获取张量。
auto tensor = named_tensors->Get("input_name");
Set
按名称设置张量。
named_tensors->Set("input_name", *tensor);
Delete
按名称删除张量。
named_tensors->Delete("input_name");
Count
返回命名张量的数量。
size_t count = named_tensors->Count();
GetNames
获取所有张量的名称。
auto names = named_tensors->GetNames();
OgaAdapters
Create
为给定的模型创建一个适配器管理器。
auto adapters = OgaAdapters::Create(*model);
LoadAdapter
从文件加载适配器。
adapters->LoadAdapter("adapter_file_path", "adapter_name");
UnloadAdapter
按名称卸载适配器。
adapters->UnloadAdapter("adapter_name");
OgaMultiModalProcessor
Create
为给定的模型创建一个多模态处理器。
auto processor = OgaMultiModalProcessor::Create(*model);
ProcessImages
处理图像并返回命名的张量。
auto named_tensors = processor->ProcessImages("prompt", images.get());
ProcessAudios
处理音频并返回命名的张量。
auto named_tensors = processor->ProcessAudios(audios.get());
ProcessImagesAndAudios
同时处理图像和音频。
auto named_tensors = processor->ProcessImagesAndAudios("prompt", images.get(), audios.get());
Decode
将标记序列解码为字符串。
auto str = processor->Decode(tokens, token_count);
OgaHandle
构造函数 / 析构函数
初始化并关闭全局 Oga 运行时。
OgaHandle handle;
Oga 实用函数
SetLogBool
设置布尔日志记录选项。
Oga::SetLogBool("option_name", true);
SetLogString
设置字符串日志记录选项。
Oga::SetLogString("option_name", "value");
SetCurrentGpuDeviceId
设置当前 GPU 设备 ID。
Oga::SetCurrentGpuDeviceId(0);
GetCurrentGpuDeviceId
获取当前 GPU 设备 ID。
int id = Oga::GetCurrentGpuDeviceId();