プレゼンス ペナルティ: このパラメーターは、生成されるテキストの多様性と具体性を促進するために生成 AI モデルで使用されます。 値が大きい (1.0 に近い) ほど、より斬新で多様なトークンを含めるようモデルに促します。 より小さい値を指定すると、モデルで一般的なありきたりの語句が生成される可能性が高くなります。
AI モデルをアプリに統合する
モデルをアプリケーションに統合するには、次の 2 つのオプションがあります。
AI Toolkit には、OpenAI チャット入力候補形式を使用するローカル REST API Web サーバーが付属しています。 これにより、クラウド AI モデル サービスに依存することなく、エンドポイント http://127.0.0.1:5272/v1/chat/completions を使用してアプリケーションをローカルでテストすることができます。 運用環境でクラウド エンドポイントに切り替える場合は、このオプションを使用します。 OpenAI クライアント ライブラリを使用して、Web サーバーに接続できます。
{
"model": "Phi-3-mini-4k-directml-int4-awq-block-128-onnx",
"messages": [
{
"role": "user",
"content": "what is the golden ratio?"
}
],
"temperature": 0.7,
"top_p": 1,
"top_k": 10,
"max_tokens": 100,
"stream": true
}'
Note
モデル フィールドを、ダウンロードしたモデルの名前に更新することが必要になる場合があります。
Postman や CURL ユーティリティなどの API ツールを使用して、REST エンドポイントをテストできます。
curl -vX POST http://127.0.0.1:5272/v1/chat/completions -H 'Content-Type: application/json' -d @body.json
OpenAI Python ライブラリをインストールします。
pip install openai
from openai import OpenAI
client = OpenAI(
base_url="http://127.0.0.1:5272/v1/",
api_key="x" # required by API but not used
)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "what is the golden ratio?",
}
],
model="Phi-3-mini-4k-directml-int4-awq-block-128-onnx",
)
print(chat_completion.choices[0].message.content)
// OverridePolicy.cs
using Azure.Core.Pipeline;
using Azure.Core;
internal partial class OverrideRequestUriPolicy(Uri overrideUri)
: HttpPipelineSynchronousPolicy
{
private readonly Uri _overrideUri = overrideUri;
public override void OnSendingRequest(HttpMessage message)
{
message.Request.Uri.Reset(_overrideUri);
}
}
次のコードを Program.cs ファイルにコピーします
// Program.cs
using Azure.AI.OpenAI;
Uri localhostUri = new("http://localhost:5272/v1/chat/completions");
OpenAIClientOptions clientOptions = new();
clientOptions.AddPolicy(
new OverrideRequestUriPolicy(localhostUri),
Azure.Core.HttpPipelinePosition.BeforeTransport);
OpenAIClient client = new(openAIApiKey: "unused", clientOptions);
ChatCompletionsOptions options = new()
{
DeploymentName = "Phi-3-mini-4k-directml-int4-awq-block-128-onnx",
Messages =
{
new ChatRequestSystemMessage("You are a helpful assistant. Be brief and succinct."),
new ChatRequestUserMessage("What is the golden ratio?"),
}
};
StreamingResponse<StreamingChatCompletionsUpdate> streamingChatResponse
= await client.GetChatCompletionsStreamingAsync(options);
await foreach (StreamingChatCompletionsUpdate chatChunk in streamingChatResponse)
{
Console.Write(chatChunk.ContentUpdate);
}
Note
CPU バージョンの Phi3 モデルをダウンロードした場合は、モデル フィールドを Phi-3-mini-4k-cpu-int4-rtn-block-32-acc-level-4-onnx に更新することが必要です。
ONNX Runtime
ONNX ランタイム生成 API は、ONNX ランタイムによる推論、ロジット処理、検索とサンプリング、KV キャッシュ管理など、ONNX モデルの生成 AI ループを提供します。 上位レベル generate() のメソッドを呼び出したり、モデルの各イテレーションをループで実行したりして、一度に 1 つのトークンを生成したり、必要に応じてループ内の生成パラメーターを更新したりできます。
# app.py
import onnxruntime_genai as og
import argparse
def main(args):
print("Loading model...")
model = og.Model(f'{args.model}')
print("Model loaded")
tokenizer = og.Tokenizer(model)
tokenizer_stream = tokenizer.create_stream()
search_options = {
'max_length': 2048
}
chat_template = '<|user|>\n{input} <|end|>\n<|assistant|>'
# Keep asking for input prompts in a loop
while True:
text = input("Input: ")
# If there is a chat template, use it
prompt = f'{chat_template.format(input=text)}'
input_tokens = tokenizer.encode(prompt)
params = og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids = input_tokens
generator = og.Generator(model, params)
print("\nOutput: ", end='', flush=True)
while not generator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token = generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
print()
print()
# Delete the generator to free the captured graph for the next generator, if graph capture is enabled
del generator
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--model', type=str, required=True, help='Onnx model folder path (must contain config.json and model.onnx)')
args = parser.parse_args()
main(args)