Skip to content

RKLLM Model Deployment API Reference

Revision History

NOVersionRevision DetailsDate
1Ver1.0New document2026/06/23

The information in this document may be changed without prior notice for document improvement. Please refer to the company website for the latest version.

Reproduction in any form without written permission from Nissho Technology Co., Ltd. is strictly prohibited.

1. callbackfunction定義

  callbackfunctionは、モデルのリアルタイムoutput結果を受け取るin order toにis used。RKLLM のinitialization時にcallbackfunctionをバインドし、model inference中は結果が継続的にcallbackfunctionへoutputされます。各callbackでは 1 つの token のみが返されます。

the followingsample codeでは、callbackfunctionによってinference結果をリアルタイムにterminalへoutputします。

int callback(RKLLMResult* result, void* userdata, LLMCallState
state)
{
if(state == LLM_RUN_NORMAL){
printf("%s", result->text);
}
if (state == LLM_RUN_FINISH) {
printf("finish\n");
} else if (state == LLM_RUN_ERROR){
printf("\run error\n");
}
return 0;
}

(1)LLMCallState は状態フラグです。具体的な定義はas follows。

表 1 LLMCallState 状態フラグdescription

ItemDescription
enumeration definitionLLMCallState
descriptioncurrentの RKLLM のexecution状態をindicates。
enumeration valueLLM_RUN_NORMAL:RKLLM モデルがcurrentinference中であることを示します。
LLM_RUN_FINISH:RKLLM モデルがcurrentのinputに対するすべてのinferenceを完了したことを示します。
LLM_RUN_WAITING:current RKLLM がデcodeした文字が完全な UTF-8 エンcodeではなく、次回のデcode結果との結合を待つ必要があることを示します。
LLM_RUN_ERROR:RKLLM モデルのinferenceでエラーが発生したことを示します。

userは、callbackfunctionを設計する際に、LLMCallState の状態に応じて異なる後処理を設定can。

(2)RKLLMResult はreturn valueのstructureです。具体的な定義はas follows。

表 2 RKLLMResult return valuestructuredescription

ItemDescription
structure定義RKLLMResult
descriptioncurrentのinferencegeneration結果をreturns。
fieldconst char text*:currentのinferenceでgenerationされたtext内容をindicates。
int32_t token_id:currentのinferenceでgenerationされた token ID をindicates。
RKLLMResultLogits logits:currentのinferenceでgenerationされた logits 情報をindicates。RKLLMInferMode が RKLLM_INFER_GET_LOGITS に設定されているwhenにのみ返されます。
RKLLMPerfStat perf:currentのinference終了時の性能統計dataをindicates。RKLLM_RUN_FINISH 状態のwhenにのみdataが返されます。

(3)RKLLMResultLogits はreturn valueのstructureです。具体的な定義はas follows。

表 3 RKLLMResultLogits return valuestructuredescription

ItemDescription
structure定義RKLLMResultLogits
descriptioncurrentのinferenceでgenerationされた logits をreturns。
fieldconst float logits*:currentのinferenceでgenerationされた logits をindicates。
int vocab_size:語彙表のサイズをindicates。
int num_tokens:返却される token numberをindicates。userは vocab_size と num_tokens に基づいて logits のサイズを算出can。

userは、callbackfunctionを設計する際に、RKLLMResult 内のvalueに応じて異なる後処理を設定can。

2. parameterstructure RKLLMParam 定義

structure RKLLMParam は、RKLLM の詳細情報を記述and定義するin order toにis used。具体的な定義はas follows。

表 4 RKLLMParam structureparameterdescription

ItemDescription
structure定義RKLLMParam
descriptionRKLLM モデルの各種詳細parameterを定義します。
fieldconst char model_path*:モデルfileの格納pathです。
int32_t max_context_len:inference時の最大コンtext長をsets。
int32_t max_new_tokens:model inference時にgenerationする token numberの上限をsets。
int32_t top_k:top-k サンプリングはtextgeneration手法の一つで、モデルが予測した確率の高い上位 k 個の token のみfromthe following token を選択します。この手法は、低確率alsoは意味の乏しい token のgenerationリスクを低減するのに有効です。valueを大きくすると(例:100)より多くの token 候補を考慮するin order to、generation文は多様になります。valueを小さくすると(例:10)最も可能性の高い token に集中するin order to、より保守的な文になります。デフォルトvalueは 40 です。
float top_p:top-p サンプリングは nucleus sampling とも呼ばれるtextgeneration手法で、累積確率が少なくとも p となる token 集合fromthe following token を選択します。token の確率とサンプリング対象numberの両方を考慮することで、多様性と品質のバランスを取ります。valueを大きくすると(例:0.95)generation文はより多様になり、valueを小さくすると(例:0.5)より保守的な文になります。デフォルトvalueは 0.9 です。
float temperature:generationtextのランダム性を制御するハイパーparameterです。モデルoutput token の確率分布を調整することでfunctionします。温度が高いwhen(例:1.5)、outputはよりランダムで創造的になり、次 token の選択時に低確率の候補もより多く考慮されるin order to、多様で予想外のoutputが得られます。温度が低いwhen(例:0.5)、outputはより集中し保守的になります。温度が 0 の極端なwhen、モデルは常に最も確率の高い次 token を選択するin order to、executionごとに完全に同じoutputになります。ランダム性と決定性のバランスを保つin order to、デフォルトvalueは 0.8 です。
float repeat_penalty:generationtext内で token シーケンスが繰り返される度合いを制御し、モデルが反復的alsoは単調な文をgenerationすることを防ぎます。valueを大きくすると(例:1.5)繰り返しに対するペナルティが強くなり、valueを小さくすると(例:0.9)より寛容になります。デフォルトvalueは 1.1 です。
float frequency_penalty:単語alsoはフレーズの出現頻度に対するペナルティ係numberです。全体as頻出する単語やフレーズの出現確率を下げ、低頻度の単語やフレーズが使用される可能性を高めます。generation文の多様性を向上させる可能性がありますが、理解しにくい、alsoは期待に沿わない文になるwhenもあります。設定範囲は [-2.0, 2.0] で、デフォルトvalueは 0 です。
int32_t mirostat:textgeneration中にgeneration文の品質を期待範囲内に能動的に維持するアルゴリズムです。過度な繰り返し(boring trap)や不連続性(confusion trap)による低品質outputを避け、整合性と多様性のバランスを取ることを目的とします。valueは {0, 1, 2} で、0 は無効、1 は mirostat、2 は mirostat 2.0 をis used。
float mirostat_tau:mirostat の目標エントロピーをsets。generationtextの期待 perplexity を表し、整合性と多様性のバランスを制御します。valueを小さくすると文はより集中し一貫性が高くなり、valueを大きくするとより多様になりますが、一貫性が低下する可能性があります。デフォルトvalueは 5.0 です。
float mirostat_eta:mirostat の学習率をsets。学習率は、generationtextfromのフィードバックに対するアルゴリズムの応答速度に影響します。valueを小さくすると調整は遅くなり、valueを大きくするとより敏感になります。デフォルトvalueは 0.1 です。
bool skip_special_token:inference終了記号 などの特殊 token をoutput時にスキップするかどうかを指定します。
bool is_async:非同期モードを使用するかどうかを指定します。
const char img_start*:マルチモーダルinputにおける画像エンcodeの開始マーカーをsets。マルチモーダルinputモードでは設定が必要です。
const char img_end*:マルチモーダルinputにおける画像エンcodeの終了マーカーをsets。マルチモーダルinputモードでは設定が必要です。
const char img_content*:マルチモーダルinputにおける画像エンcodeの内容マーカーをsets。マルチモーダルinputモードでは設定が必要です。
n_keep:kv cache をクリアする際に先頭に保持する cache numberです。マルチターン対話では、設定する n_keep valueは system_prompt のlength以上でなければなりません。
RKLLMExtendParam extend_param:inferenceを制御する特殊parameterです。

表 5 RKLLMExtendParam structureparameterdescription

ItemDescription
structure定義RKLLMExtendParam
descriptioninferenceを制御する特殊parameterです。
fieldint32_t base_domain_id:RKLLM モデルをどの domain frominitializationするかを制御します。デフォルトは 0 です。
int8_t embed_flash:モデルの語彙表を flash にsaveしてmemoryを節約するかどうかを制御します。0 は無効、1 は有効です。
int8_t enabled_cpus_num:inference時に使用する CPU numberをsets。設定可能範囲はチップby異なります。RK3588/3576 では 1〜8、RK3562 では 1〜4 で、デフォルトは 4 です。
uint32_t enabled_cpus_mask:使用する CPU コアをビットマスクで指定します。rkllm.h には CPU 番号を表すマクロが定義されており、CPU4|CPU5|CPU6|CPU7 の形式でsets。
uint8_t n_batch:parallelinferenceの batch numberをsets。デフォルトは 1 です。
int8_t use_cross_attn:Cross Attention を有効にするかどうかをsets。

実際のcode構築では、RKLLMParam は rkllm_createDefaultParam() functionでinitializationし、必要に応じて該当するモデルparameterをsets。sample codeはas follows。

RKLLMParam param = rkllm_createDefaultParam();
param.model_path = "model.rkllm";
param.top_k = 1;
param.max_new_tokens = 256;
param.max_context_len = 512;

3. inputstructure定義

異なる形式のinputdataに対応するin order to、RKLLMInput inputstructureが定義されています。current、text、画像とtext、Token ID、エンcodeベクトルの 4 種類のinput形式を受け付けます。具体的な定義はas follows。

表 6 RKLLMInput structureparameterdescription

ItemDescription
structure定義RKLLMInput
description異なる形式のinputdataを受け取ります。
fieldRKLLMInputType input_type:inputモードです。
const char role*:inputロールです。選択可能valueは [“user”, “tool”] です。
bool enable_thinking:Qwen3 モデルで thinking モードを使用するかどうかを指定します。
union:異なるinputdata型を格納します。具体的にはthe following形式を含みます。
- const char prompt_input*:textプロンプトinputです。自然言語textを渡します。
- RKLLMEmbedInput embed_input:埋め込みベクトルinputです。処理済みの特徴ベクトルをindicates。
- RKLLMTokenInput token_input:Token inputです。トークナイズ済みの Token シーケンスを渡します。
- RKLLMMultiModelInput multimodal_input:マルチモーダルinputです。画像とtextの結合inputなど、マルチモーダルdataを渡します。

表 7 RKLLMInputType inputタイプdescription

ItemDescription
enumeration definitionRKLLMInputType
descriptioninputdataタイプをindicates。
enumeration valueRKLLM_INPUT_PROMPT:inputdataが純粋なtextであることを示します。
RKLLM_INPUT_TOKEN:inputdataが Token ID であることを示します。
RKLLM_INPUT_EMBED:inputdataがエンcodeベクトルであることを示します。
RKLLM_INPUT_MULTIMODAL:inputdataが画像とtextであることを示します。

inputdataが純粋なtextのwhenは、input_data を使用して直接inputします。inputdataが Token ID、エンcodeベクトル、alsoは画像とtextのwhen、RKLLMInput は RKLLMTokenInput、RKLLMEmbedInput、RKLLMMultiModelInput の 3 つのinputstructureと組み合わせてis used。具体的なdescriptionはas follows。

(1)RKLLMTokenInput は Token ID を受け取るinputstructureです。具体的な定義はas follows。

表 8 RKLLMTokenInput structureparameterdescription

ItemDescription
structure定義RKLLMTokenInput
descriptionToken ID dataを受け取ります。
fieldint32_t input_ids*:input token IDs のmemoryポインタです。
size_t n_tokens:inputdataの token numberです。

(2)RKLLMEmbedInput はエンcodeベクトルを受け取るinputstructureです。具体的な定義はas follows。

表 9 RKLLMEmbedInput structureparameterdescription

ItemDescription
structure定義RKLLMEmbedInput
descriptionEmbedding dataを受け取ります。
fieldfloat embed*:input token embedding のmemoryポインタです。
size_t n_tokens:inputdataの token numberです。

(3)RKLLMMultiModelInput は画像とtextを受け取るinputstructureです。具体的な定義はas follows。

表 10 RKLLMMultiModelInput structureparameterdescription

ItemDescription
structure定義RKLLMMultiModelInput
description画像とtextのマルチモーダルdataを受け取ります。
fieldchar prompt*:inputtextのmemoryポインタです。
float image_embed*:input画像 embedding のmemoryポインタです。
size_t n_image_tokens:input画像 embedding の token numberです。
size_t n_image:input画像numberです。連続した複numberフレーム画像のinputをsupports。
size_t image_width:input画像の embedding 計算時の幅です。mrope 計算parameterにis used。
size_t image_height:input画像の embedding 計算時の高さです。mrope 計算parameterにis used。

RKLLM は複numberのinferenceモードをサポートしており、RKLLMInferParam structureが定義されています。current、inference中にプリloadされた LoRA モデルと組み合わせてinferenceする、alsoは Prompt Cache をsaveして後続inferenceを高速化することがcan。具体的な定義はas follows。

表 11 RKLLMInferParam structureparameterdescription

ItemDescription
structure定義RKLLMInferParam
description異なるinferenceモードを定義します。
fieldRKLLMInferMode mode:inferenceモードです。通常inferenceモード RKLLM_INFER_GENERATE と、追加で logits valueを取得するinferenceモード RKLLM_INFER_GET_LOGITS をsupports。
RKLLMLoraParam lora_params*:inference時に使用する LoRA のparameter設定です。複numberの LoRA をloadしているwhenに、inference対象の LoRA を選択するin order toにis used。LoRA をloadしないwhenは NULL をsets。
RKLLMPromptCacheParam prompt_cache_params*:inference時に使用する Prompt Cache のparameter設定です。Prompt Cache をgenerationしないwhenは NULL をsets。
keep_history:inference時に履歴コンtextを保持する必要があるかどうかを指定します。マルチターン対話では 1 に設定するis required。

表 12 RKLLMLoraParam structureparameterdescription

structure定義RKLLMLoraParam
descriptioninference時に使用する LoRA のparameterを定義します。
fieldconst char* lora_adapter_name:inference時に使用する LoRA 名称です。

表 13 RKLLMPromptCacheParam structureparameterdescription

ItemDescription
structure定義RKLLMPromptCacheParam
descriptioninference時に使用する Prompt Cache のparameterを定義します。
fieldint save_prompt_cache:inference時に Prompt Cache をsaveするかどうかを指定します。1 はsaveする、0 はsaveしないことを示します。
const char prompt_cache_path*:Prompt Cache のsavepathです。未設定のwhenはデフォルトで ”./prompt_cache.bin” にsaveされます。

RKLLMPromptCacheParam の使用例はas follows。

// Prompt Cache パラメータを初期化して設定します(prompt cache
を使用する場合)
RKLLMPromptCacheParam prompt_cache_params;
prompt_cache_params.save_prompt_cache = true; // prompt cache
を保存するかどうか
prompt_cache_params.prompt_cache_path = "./prompt_cache.bin"; //
prompt cache を保存する場合は cache ファイルパスを指定
rkllm_infer_params.prompt_cache_params =
&prompt_cache_params;

4. model initialization

モデルをinitializationする前に、あらかじめ LLMHandle ハンドルを定義するis required。このハンドルは、モデルのinitialization、inference、リソースreleaseの各処理でis used。正しいmodel inferenceflowでは、これら 3 つの処理で同一の LLMHandle ハンドルオブジェクトを使用するis required。model inference前に、userは rkllm_init() functionを通じてmodel initializationを完了します。具体的なfunction定義はas follows。

表 14 rkllm_init functioninterface description

ItemDescription
function namerkllm_init
descriptionRKLLM モデルの具体的なparameterand関連するinference設定をinitializationします。
引numberLLMHandle handle*:モデルを該当ハンドルに登録し、後続のinferenceandrelease呼び出しでis used。
RKLLMParam param*:モデル定義のparameterstructureです。
LLMResultCallback callback:モデルのリアルタイムoutputを受け取り処理するin order toのcallbackfunctionです。
return value0 はinitialization処理が正常に完了したことを示します。-1 はinitialization失敗を示します。

sample codeはas follows。

LLMHandle llmHandle = nullptr;
rkllm_init(&llmHandle, &param, callback);

5. model inference

RKLLM モデルのinitialization処理が完了したら、rkllm_run() functionを使用してmodel inferenceをexecutioncan。also、initialization時に事前定義したcallbackfunctionby、リアルタイムinference結果を処理can。rkllm_run() の具体的なfunction定義はas follows。

表 15 rkllm_run functioninterface description

ItemDescription
function namerkllm_run
descriptioninitialization済みの RKLLM モデルを呼び出してinference結果をgenerationします。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
RKLLMInput rkllm_input*:model inferenceのinputdataです。
RKLLMInferParam rkllm_infer_params*:model inferenceプロセスで渡すparameterです。
void userdata*:user定義のfunctionポインタです。デフォルトでは NULL にsets。
return value0 はmodel inferenceが正常にexecutionされたことを示します。-1 はmodel inference呼び出し失敗を示します。

6. model abort

model inference中、userは rkllm_abort() functionを呼び出してinferenceプロセスを中断can。具体的なfunction定義はas follows。

表 16 rkllm_abort functioninterface description

function namerkllm_abort
descriptionRKLLM モデルのinferenceプロセスを中断します。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
return value0 は RKLLM モデルの中断に成功したことを示します。-1 はmodel abort失敗を示します。

sample codeはas follows。

// llmHandle はモデル初期化時に渡されたハンドルです
rkllm_abort(llmHandle);

7. releasing model resources

すべてのmodel inference呼び出しが完了した後、userは rkllm_destroy() functionを呼び出して RKLLM モデルを破棄し、確保された CPU and NPU 計算リソースをreleaseします。これby、他のプロセスやモデルが計算リソースを利用できるようになります。具体的なfunction定義はas follows。

表 17 rkllm_destroy functioninterface description

function namerkllm_destroy
descriptionRKLLM モデルを破棄し、すべての計算リソースをreleaseします。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
return value0 は RKLLM モデルが正常に破棄・releaseされたことを示します。-1 はモデルrelease失敗を示します。

sample codeはas follows。

// llmHandle はモデル初期化時に渡されたハンドルです
rkllm_destroy(llmHandle);

8. LoRA モデルのload

RKLLM は、ベースモデルのinferenceと同時に LoRA モデルをinferenceすることをsupports。rkllm_run インターフェースを呼び出す前に、rkllm_load_lora インターフェースを使用して LoRA モデルをloadcan。RKLLM は複numberの LoRA モデルのloadをサポートしており、rkllm_load_lora を 1 回呼び出すごとに 1 つの LoRA モデルをloadcan。具体的なfunction定義はas follows。

表 18 rkllm_load_lora functioninterface description

ItemDescription
function namerkllm_load_lora
descriptionLoRA モデルをloadします。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
RKLLMLoraAdapter lora_adapter*:LoRA モデルload時のparameter設定です。
return value0 は LoRA モデルが正常にloadされたことを示します。-1 はモデルload失敗を示します。

表 19 RKLLMLoraAdapter structureparameterdescription

ItemDescription
structure定義RKLLMLoraAdapter
descriptionLoRA load時のparameterをsets。
fieldconst char lora_adapter_path*:loadする LoRA モデルのpathです。
const char lora_adapter_name*:loadする LoRA モデルの名称です。userが任意に定義し、後続のinferenceで指定した LoRA を選択するin order toにis used。
float scale:LoRA モデルがinference中にベースモデルのparameterを調整する強度です。

LoRA をloadするsample codeはas follows。

RKLLMLoraAdapter lora_adapter;
memset(&lora_adapter, 0, sizeof(RKLLMLoraAdapter));
lora_adapter.lora_adapter_path = "lora.rkllm";
lora_adapter.lora_adapter_name = "lora_name";
lora_adapter.scale = 1.0;
ret = rkllm_load_lora(llmHandle, &lora_adapter);
if (ret != 0) {
printf("\nload lora failed\n");
}

9. Prompt Cache 管理

model inferenceプロセスでは、Prefill フェーズが大量の計算リソースと時間を消費することがあります。特に Prompt が長いwhen、その影響は大きくなります。この処理を高速化するin order to、RKLLM はfilefromの Prompt Cache loadをサポートしています。cache内の内容を再利用することで、Prefill フェーズの所要時間を大幅に削減し、全体的なinference効率を向上can。rkllm_run インターフェースを呼び出してinferenceを行う前に、prompt_cache_params parameterを正しく設定してください。この設定by、モデルはinference終了後に対応する Prompt Cache fileをgenerationcan。初回inference時、systemは自動的に Prompt Cache fileをgenerationします。このfileには Prefill フェーズに必要な中間結果が含まれ、後続のinferenceで利用can。後続のinferenceタスクでは、rkllm_load_prompt_cache インターフェースを呼び出して、以前にgenerationした Prompt Cache fileをloadcan。

具体的なfunction定義はas follows。

表 20 rkllm_load_prompt_cache functioninterface description

ItemDescription
function namerkllm_load_prompt_cache
descriptionPrompt Cache をloadします。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。4. model initializationをrefer to。
const char prompt_cache_path*:loadする Prompt Cache fileのpathです。
return value0 は Prompt Cache が正常にloadされたことを示します。-1 はload失敗を示します。

表 21 rkllm_release_prompt_cache functioninterface description

function namerkllm_release_prompt_cache
descriptionPrompt Cache をreleaseします。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。4. model initializationをrefer to。
return value0 は Prompt Cache が正常にreleaseされたことを示します。-1 はrelease失敗を示します。

注意:

RKLLM は、inputと prompt_cache 内で同一の部分を先頭from検出します。input形式が PROMPT_PREFIX + text + PROMPT_POSTFIX のように固定されているwhen、PROMPT_PREFIX 部分のみで Prompt Cache をgenerationcan。load後の後続inferenceでは、この部分の結果を再利用can。
RKLLM は複numberの Prompt Cache filegenerationをsupports。異なる Prompt Cache を使用するwhenは、対応するfileをloadするだけで利用can。別の Prompt Cache fileへ切り替えるwhen、alsoはload済みの Prompt Cache が不要になったwhenは、rkllm_release_prompt_cache インターフェースを明示的に呼び出してreleaseしてください。

Prompt Cache をloadするsample codeはas follows。

// Prompt Cache パラメータを初期化して設定し、run
インターフェースを呼び出して prompt cache ファイルを生成します
RKLLMPromptCacheParam prompt_cache_params;
// prompt cache を保存するかどうか
prompt_cache_params.save_prompt_cache = true;
// prompt cache を保存する場合は、cache
ファイルの絶対パスを指定します
prompt_cache_params.prompt_cache_path = "/data/prompt_cache.bin";
rkllm_infer_params.prompt_cache_params =
&prompt_cache_params;
rkllm_infer_params.mode = RKLLM_INFER_GENERATE;
rkllm_input.input_type = RKLLM_INPUT_PROMPT;
rkllm_input.prompt_input = (char *)prompt.c_str();
rkllm_run(llmHandle, &rkllm_input, &rkllm_infer_params,
NULL);
// prompt cache ファイルをロードし、prefill
の所要時間を削減します
rkllm_load_prompt_cache(llmHandle, "./prompt_cache.bin");
if (ret != 0) {
printf("\nload Prompt Cache failed\n");
}
rkllm_run(llmHandle, &rkllm_input, &rkllm_infer_params,
NULL);

10. KV Cache 管理

RKLLM は KV cache の手動クリアをサポートしており、シングルターンandマルチターン対話で使用can。cacheクリアfunctionを呼び出す際に keep_system_prompt を 1 に設定すると、system prompt(存在するwhen)を保持します。そうでないwhenは、cache全体をクリアします。function定義はas follows。

表 22 rkllm_clear_kv_cache functioninterface description

ItemDescription
function namerkllm_clear_kv_cache
descriptionkv cache をクリアします。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
keep_system_prompt:system prompt を保持するかどうかを指定します。
start_pos:削除する kv cache の開始 position ID です。start_pos の位置を含みます。使用しないwhenは nullptr を明示的に設定してください。
end_pos:削除する kv cache の終了 position ID です。end_pos の位置は含みません。使用しないwhenは nullptr を明示的に設定してください。
注意:
1. 指定位置の kv cache 削除は、シングルターンモードでinferencepausefunctionを使用するwhenにのみサポートされます。
2. 特定範囲 [start_pos, end_pos) を指定したwhen、keep_system_prompt は無視され、指定範囲内の kv cache がクリアされます。
return value0 は kv cache のクリア成功を示します。-1 はクリア失敗を示します。

11. Chat Template 設定

userがtextinputを使用するwhen、RKLLM はデフォルトtextを前処理します。前処理では、Hugging Face モデルの tokenizer_config.json file内の chat_template fieldに基づいて、プロンプトテンプレートを自動解析して適用します。カスタマイズが必要なwhenは、the followingfunctionで再設定can。system_prompt はモデルの挙動を指示する system prompt、prompt_prefix はuserinput前の接頭辞、prompt_postfix はuserinput後の接尾辞です。具体的なfunction定義はas follows。userがテンプレートを再設定すると、enable_thinking オプションは無効になり、userはcustom prompt 内で設定するis required。

表 23 rkllm_set_chat_template functioninterface description

ItemDescription
function namerkllm_set_chat_template
descriptionプロンプトをsets。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
system_prompt:systemプロンプトです。
prompt_prefix:userinputの接頭辞です。
prompt_postfix:userinputの接尾辞です。
return value0 は chat_template 設定成功を示します。-1 は設定失敗を示します。

12. Function Calling 設定

RKLLM は Function Calling by、モデルと外部systemの構造化された連携を実現します。これby、large language modelの能力範囲を拡張し、知識補完や正確なdata取得などのタスクにおける性能を向上させます。Function Calling モードを有効にすると、アプリケーションはfunction定義をモデルへ渡します。モデルはuserの質問に基づいてfunction呼び出しが必要かどうかを判断し、設定された形式で呼び出しリクエストをoutputします。アプリケーションはモデルの意図に応じて該当functionを呼び出し、結果をreturns。モデルは最終的にその結果に基づいて対話を継続します。

RKLLM がサポートする Function Calling 設定functionの定義はas follows。

表 24 rkllm_set_function_tools functioninterface description

ItemDescription
function namerkllm_set_function_tools
descriptionFunction Calling の設定です。system prompt、ツールfunction定義、ツール応答識別子を含みます。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
system_prompt:systemプロンプトです。
tools:JSON 形式のfunction定義文字列です。使用可能なfunctionの名称、function、parameter形式を記述します。
tool_response_str:ツールfunction呼び出し結果の識別タグです。通常の対話内容と区別するin order toにis used。
return value0 は設定成功を示します。-1 は設定失敗を示します。

sample codeはas follows。まず tools をsets。

std::string system_prompt = "あなたは Alibaba Cloud
によって作成された Qwen です。役に立つアシスタントです。\n\n現在の日付:
2024-09-30";
std::string tools = R"([
{
"type": "function",
"function": {
"name": "get_current_temperature",
"description": "指定された場所の現在の気温を取得します。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "気温を取得する場所です。形式は \"City,
State, Country\" です。"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "返却する気温の単位です。デフォルトは
\"celsius\" です。"
}
},
"required": ["location"]
}
}
},
{
"type": "function",
"function": {
"name": "get_temperature_date",
"description": "指定された場所と日付の気温を取得します。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "気温を取得する場所です。形式は \"City,
State, Country\" です。"
},
"date": {
"type": "string",
"description": "気温を取得する日付です。形式は
\"Year-Month-Day\" です。"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "返却する気温の単位です。デフォルトは
\"celsius\" です。"
}
},
"required": ["location", "date"]
}
}
}
])";
rkllm_set_function_tools(llmHandle, system_prompt.c_str(),
tools.c_str(), "tool_response");

next、inferenceプロセスで rkllm_run と組み合わせて呼び出しチェーンを実現します。

// ユーザーからの質問
RKLLMInferParam rkllm_infer_params;
memset(&rkllm_infer_params, 0, sizeof(RKLLMInferParam));
rkllm_infer_params.mode = RKLLM_INFER_GENERATE;
rkllm_infer_params.keep_history = 0;
RKLLMInput rkllm_input;
rkllm_input.input_type = RKLLM_INPUT_PROMPT;
rkllm_input.enable_thinking = false;
rkllm_input.role = "user";
rkllm_input.prompt_input =
"サンフランシスコの現在の気温は何度ですか?明日はどうですか?";
rkllm_run(llmHandle, &rkllm_input, &rkllm_infer_params,
NULL);
// 1 回目の rkllm_run
は、呼び出す必要があるツール関数名を返します
<tool_call>
{"name": "get_current_temperature", "arguments": {"location": "San
Francisco"}}
</tool_call>
<tool_call>
{"name": "get_temperature_date", "arguments": {"location": "San
Francisco", "date": "2024-10-01"}}
</tool_call>
// ツール呼び出し結果を大規模言語モデルへ返します。role は必ず tool
に設定します
rkllm_input.role = "tool";
rkllm_input.prompt_input = R"([
{
"temperature": 26.1,
"location": "San Francisco",
"unit": "celsius"
},
{
"temperature": 25.9,
"location": "San Francisco",
"date": "2024-09-30",
"unit": "celsius"
}
])";
rkllm_run(llmHandle, &rkllm_input, &rkllm_infer_params,
NULL);
// 最終結果
"サンフランシスコの現在の気温は 26.1°C です。明日の気温は 25.9°C
と予想されます。"

13. Cross Attention 設定

RKLLM は Cross Attention inferenceをsupports。userはthe followingfunctionを使用して、encoder がgenerationした K/V cache、mask、and位置情報を decoder へinputし、Cross Attention 計算に利用can。Cross Attention はcustommodel inferenceのみをsupports。モデルの変換methodについては 3.1.6 章をrefer to。

表 25 rkllm_set_cross_attn_params functioninterface description

ItemDescription
function namerkllm_set_cross_attn_params
descriptionCross Attention parameterをsets。
引numberLLMHandle handle:model initialization時に登録された対象ハンドルです。
RKLLMCrossAttnParam cross_attn_params*:Cross Attention parameterです。
return value0 は設定成功を示します。-1 は設定失敗を示します。

表 26 RKLLMCrossAttnParam structureparameterdescription

ItemDescription
structure定義RKLLMCrossAttnParam
descriptionCross Attention parameterです。
field- float encoder_k_cache*:encoder outputの k value cache ポインタです。
- float encoder_v_cache*:encoder outputの v value cache ポインタです。
- float encoder_mask*:encoder の attention mask です。
- int32_t encoder_pos*:encoder input token の位置情報です。
- int num_tokens*:encoder のinput token numberです。

14. マルチ batch parallelinference

RKLLM は複number batch の同時inferenceをsupports(batch numberは 8 the followingを推奨します)。

2 つの batch を使用してinferenceするsample codeはas follows。主なポイントはthe followingのとおりです。

  • model initialization時に param.extend_param.n_batch parameterを 2 にsets。

  • マルチ batch inferenceでは、input RLLLMInput と callback 内の RKLLMResult はいずれも n_batch サイズの配列になります。

  • callback ではすべての batch inference結果が同期して返されます。ある batch で返された token ID が負numberのwhen、その batch のinference終了を示します。すべての batch のinferenceが終了した時点でinferenceが終了します。

  • callback 内で返却textを処理するwhen、必ず返却された text が NULL ポインタでないことを確認してfrom代入処理を行います。

#include <string.h>
#include <unistd.h>
#include <string>
#include "rkllm.h"
#include <fstream>
#include <iostream>
#include <csignal>
#include <vector>
using namespace std;
LLMHandle llmHandle = nullptr;
std::string output_texts[10];
int callback(RKLLMResult *result, void *userdata, LLMCallState
state)
{
if (state == RKLLM_RUN_FINISH) {
printf("\nrkllm run finish\n");
} else if (state == RKLLM_RUN_ERROR) {
printf("\nrkllm run error\n");
} else if (state == RKLLM_RUN_NORMAL) {
RKLLMResult batch1 = result[0];
RKLLMResult batch2 = result[1];
if (batch1.text) {
output_texts[0] += batch1.text;
printf("batch 0 %s\n", output_texts[0].c_str());
}
if (batch2.text) {
output_texts[1] += batch2.text;
printf("batch 1 %s\n", output_texts[1].c_str());
}
}
return 0;
}
int main(int argc, char **argv)
{
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << "
model_path max_new_tokens max_context_len\n";
return 1;
}
RKLLMParam param = rkllm_createDefaultParam();
param.model_path = argv[1];
param.top_k = 1;
param.top_p = 0.95;
param.temperature = 0.8;
param.repeat_penalty = 1.1;
param.frequency_penalty = 0.0;
param.presence_penalty = 0.0;
param.max_new_tokens = std::atoi(argv[2]);
param.max_context_len = std::atoi(argv[3]);
param.skip_special_token = true;
param.extend_param.base_domain_id = 0;
param.extend_param.embed_flash = 1;
param.extend_param.n_batch = 2;
int ret = rkllm_init(&llmHandle, &param, callback);
if (ret == 0) {
printf("rkllm init success\n");
} else {
printf("rkllm init failed\n");
exit_handler(-1);
}
RKLLMInput rkllm_input[2];
memset(&rkllm_input, 0, sizeof(RKLLMInput) * 2);
RKLLMInferParam rkllm_infer_params;
memset(&rkllm_infer_params, 0, sizeof(RKLLMInferParam)); //
全内容を 0 に初期化します
output_texts[0].clear();
output_texts[1].clear();
rkllm_infer_params.mode = RKLLM_INFER_GENERATE;
rkllm_infer_params.keep_history = 0;
rkllm_input[0].input_type = RKLLM_INPUT_PROMPT;
rkllm_input[0].role = "user";
rkllm_input[0].enable_thinking = false;
rkllm_input[0].prompt_input =
"上の句:川辺で幾千もの帆が過ぎ行くのを見慣れている";
rkllm_input[1].input_type = RKLLM_INPUT_PROMPT;
rkllm_input[1].role = "user";
rkllm_input[1].enable_thinking = false;
rkllm_input[1].prompt_input =
"梅を題材に、梅の花や白雪などの要素を含む漢詩を一首作成してください。";
printf("robot: ");
rkllm_run(llmHandle, &rkllm_input[0],
&rkllm_infer_params, NULL);
rkllm_destroy(llmHandle);
return 0;
}

15. model inferenceのpause

RKLLM は、シングルターンモードにおけるinferencepauseをsupports。具体的には、callback 内で return 1 を返すことでpauseします。inferenceをpauseしても kv cache はクリアされないin order to、userはinputを変更したうえで rkllm_run を再度呼び出し、inferenceを再開can。

16. モデル性能dataのcallback

RKLLM はinference終了時に、単一inferenceの性能dataを返すことをsupports。返却dataには、prefill と decode のinference総所要時間、token number、memory使用量が含まれます。返却されるstructureの定義はas follows。

表 27 RKLLMPerfStat structureparameterdescription

ItemDescription
structure定義RKLLMPerfStat
descriptionmodel inference性能dataをreturns。
field- float prefill_time_ms:prefill フェーズの総所要時間です。単位は ms です。
- int prefill_tokens:prefill フェーズの総 token numberです。
- float generate_time_ms:generate フェーズの総所要時間です。
- int generate_tokens:generate フェーズでgenerationされた総 token numberです。
- float memory_usage_mb:inferenceプロセスにおける VmHWM memoryサイズです。単位は MB です。