Language
Important
Windows ML Runtime とテキスト生成 API は現在、実験的な機能であり、運用環境での使用はサポートされていません。 これらの API を試しているアプリは、Microsoft Store に公開しないでください。
Important
Windows ML ランタイム API とテキスト生成 API は現在、C++ および Python で使用できます。 C# は、プロジェクトにコピーする一時的なラッパーによってサポートされます。今後の更新プログラムには、C# API がネイティブに含まれる予定です。 「プロジェクトを設定する」を参照してください。
Windows ML テキスト生成 API を使用すると、独自の言語モデルでテキスト生成を簡単に実行できます。 それは、Windows ML ランタイム API の上で、トークン化、自動回帰デコード、ストリーミング出力、および取り消しをユーザーに代わって処理します。これは、ONNX Runtime GenAI が ONNX Runtime の上でそのループを簡略化するのと同様です。 Windowsには、このAPI用のモデルは同梱されていません。モデルは、ご自身で選択し、アプリに組み込んで配布していただく必要があります。 これは、Windows ML タスク API の 1 つです。
Tip
特定のモデルを必要とせず、Microsoft が管理するモデルによる端末上でのテキスト生成だけを行いたい場合は、すぐに使えるローカル LLM のいずれかをご利用ください。
Windows ML 2.9 では、Task でモデルを実行する方法を選択する で説明されているように、Task に対してモデルを指定できます。 これは最も簡単な方法です。パイプラインをビルドせず、トークナイザーを渡しません。 または、基になるランタイム オブジェクト (モデル、実行ターゲット、パイプライン) を作成し、この記事の残りの部分で示すようにセッションに渡します。 このパスでは、ハードウェアの配置は非表示になりません。独自のトークン ループを記述する必要がなくなるだけです。
サポートされているモデル
タスクのモデルを指定すると、Windows ML によって CGC バックエンドを使用して GPU 用にコンパイルされます。 Llama-3.2-1B-Instruct、Qwen 3.0 0.6B、Gemma 3 1B It、Phi-3.5-mini-instruct、Qwen2.5-0.5B-Instruct (サンプルのモデル)、Qwen3.8-27B (NVIDIA GPU のみ) などの 推奨モデルを、GGUF ファイルとして使い始めます。 非量子化されたsafetensorsまたは GGUF 形式の他の高密度デコーダー モデルは機能する可能性がありますが、まだ検証されていません。 Windows ML でサポートされていないモデルは、HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)で失敗します。
The Text Generation API は以下を受け付けます。
-
SafeTensors チェックポイント フォルダーまたは GGUF ファイル。. 既定では、Windows ML は CGC バックエンドを使用して GPU のモデルをコンパイルします。 Llama-3.2-1B-Instruct、Qwen 3.0 0.6B、Gemma 3 1B It、Phi-3.5-mini-instruct、Qwen2.5-0.5B-Instruct (サンプルのモデル)、Qwen3.8-27B (NVIDIA GPU のみ) などの 推奨モデルから開始します。 他の高密度デコーダー モデルは機能する可能性がありますが、まだ検証されていません。 Windows ML でサポートされていないモデルは、
HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)で失敗します。 代わりにllama.cppで GGUF ファイルを実行するには、タスクに指定する前に、IWinMLLlamaModelLoaderを使用してファイルを読み込みます。「 Task でモデルを実行する方法を選択する」を参照してください。 トークナイザーはモデルのファイルから取得されるため、指定する必要はありません。 -
作成するパイプライン内の ONNX (
.onnx) または ORT 形式 (.ort) モデルは、ONNX ランタイムを介して実行されます。 このモデルでは、トークン ID 入力、logits 出力、およびキー/値キャッシュとシーケンス位置を保持する 1 つの固定容量状態テンソル ペアを公開する必要があります。 個別のトークナイザー ソース (たとえば、tokenizer.json) を用意します。
サンプルでは、キー/値キャッシュとシーケンス位置を 1 つの状態ペアにパックするタスク固有のグラフでエクスポートされた Qwen2.5-0.5B-Instruct モデル ファミリに対してこのコントラクトを検証します。 同じトークン入力、logits 出力、および状態コントラクトを公開する他のデコーダー専用言語モデルも機能するはずです。
テキストを生成する
テキスト生成セッションは、トークナイザーとステートフル パイプライン (キー/値キャッシュを所有するモデル) をラップします。 モデルとトークナイザーを読み込み、モデルのトークン入力、logits 出力、状態コントラクトを記述して、セッションを構築します。
// Temporary: WinMLRuntime and the other wrapper types in the WinMLSamples.Runtime
// namespaces aren't in the Windows ML package yet. Copy the wrapper files from
// https://github.com/microsoft/WindowsML/tree/main/Samples/Runtime/shared/csharp
// into your project. A future update will include the C# APIs natively.
using WinMLSamples.Runtime;
using WinMLSamples.Runtime.Tasks;
// Create the runtime and an execution target (CPU here; GPU/NPU also available).
using WinMLRuntime runtime = WinMLRuntime.Create();
using ExecutionTarget target = runtime.CreateCpuExecutionTarget();
// Load your ONNX model and its tokenizer.
using Model model = runtime.LoadModelFromFile(@"C:\models\qwen2.5-0.5b-instruct\task_model.onnx");
using Tokenizer tokenizer = Tokenizer.CreateFromFile(@"C:\models\qwen2.5-0.5b-instruct\tokenizer.json");
// Find the model's token input and logits output by name.
uint tokenInputIndex;
uint outputIndex;
using (OrtModelSchema schema = model.As<OrtModelSchema>())
{
tokenInputIndex = schema.FindInputIndex("input_ids");
outputIndex = schema.FindOutputIndex("logits");
}
// Describe the model's KV-cache state pair, and build the pipeline.
using PipelineBuilder builder = runtime.CreatePipelineBuilder();
using Stage stage = builder.AddModelStage(model, target, "my-text-generation");
using (StatefulStageOptions stateful = stage.As<StatefulStageOptions>())
{
stateful.AddStateTensorPair(1, 1);
stateful.SequenceCapacityHint = 128;
}
stage.RequestOutput(outputIndex);
using Pipeline pipeline = builder.Build();
// Configure the Task with the pipeline, the token input, the logits output,
// and the stage that owns the state.
using WinMLTasks tasks = WinMLTasks.Create(runtime);
using TextGenerationTask task = tasks.TextGeneration.CreateTextGenerationTask(tokenizer);
using TextGenerationOptions options = tasks.TextGeneration.CreateTextGenerationOptions(64);
using TextGenerationConfiguration configuration =
tasks.TextGeneration.CreateTextGenerationConfiguration();
configuration.Mode = TextGenerationConfigurationMode.Unified;
configuration.SetPipeline(TextGenerationPipelinePhase.Unified, pipeline);
configuration.SetTokenInput(TextGenerationPipelinePhase.Unified, stage, tokenInputIndex);
configuration.SetOutput(
TextGenerationPipelinePhase.Unified, stage, outputIndex, TextGenerationOutputKind.Logits);
configuration.SetStateOwnerStage(stage);
configuration.SetTokenTarget(target);
configuration.SetTokenizer(tokenizer);
configuration.Validate();
// A TextGenerator keeps the session on a thread of its own, because a session
// belongs to the thread that created it, and streams tokens as IAsyncEnumerable<T>.
await using TextGenerator generator = await TextGenerator.CreateAsync(tasks, task, configuration);
ストリーミング操作を開始するプロンプトで GenerateText を呼び出し、完了を報告するまで返されたストリームからフラグメントをプルします。
// Cancelling the token stops generation in the Runtime.
CancellationTokenSource cancellation = new();
// Read generated text one fragment at a time until the stream completes.
await foreach (TextGenerationUpdate update in
generator.GenerateTextAsync("The sky is often", options, cancellation.Token))
{
Console.Write(update.Text);
}
// The result is the authoritative text, token counts, and finish reason.
TextGenerationResult result = generator.LastResult!;
Console.WriteLine($"\nTokens: prompt={result.PromptTokenCount} generated={result.GetTokenIds().Length}");
Console.WriteLine($"Finished because: {result.FinishReason}");
// Closing the session reports a failure that disposing it would not.
await generator.CloseAsync();
完了した結果は次のとおりです:
- 生成された全文とトークン ID
- プロンプトと生成されたトークンの数
- 終了理由 - シーケンス終了トークン、停止トークン、要求されたトークン制限、シーケンス容量、取り消し、またはエラー
投機的デコード
投機的デコードは、既定ではオフになっています。 ドラフト ソースは複数のトークンを提案し、モデルは 1 つのステップでそれらを検証し、タスクはモデル自体が選択したトークンを保持します。 グリーディデコーディングでは、2つのトークンがまれにほぼ同点になる場合を除き、テキストは同じままです。 構成を検証する前に、投機的オプションで方法 ( PROMPT_LOOKUP、 MODEL、または DRAFT_MODEL) を選択します。 モデルがサポートするメソッドは、モデルの読み込み方法によって異なります。 投機的デコードを参照してください。 ターミナルの結果は、有効なメソッドと、ドラフトおよび受け入れ済みのトークン数を報告します。
C#、C++、Python
ネイティブ API は WinMLTasks.h を通じて公開され、winml/tasks/text_generation/TextGeneration.hpp 配下に型付き C++ ヘルパーがあります。 Python アプリケーションでは、windowsml.runtimeプロジェクションをwindowsml.tasksと共に使用します。 C# アプリケーションでは、今のところプロジェクトにコピーするラッパーを介して CsWin32 バインドが使用されます。 「プロジェクトを設定する」を参照してください。
Windows ML のサンプルには、C++、C#、およびPythonテキスト生成のサンプルが含まれます。 サンプルでは、テキスト生成構成の横に完全なランタイム 設定が示されているため、抽象化が開始される場所と、基になるワークフローをカスタマイズする方法を確認できます。