语言

使用 Windows ML 使用自己的语言模型生成文本

Important

Windows ML 运行时和文本生成 API 目前是实验性的,不支持在生产环境中使用。 尝试这些 API 的应用不应发布到 Microsoft 应用商店。

Important

Windows ML 运行时和文本生成 API 目前在 C++ 和 Python中提供。 C# 通过复制到项目中的临时包装器获得支持;将来的更新将原生提供 C# API。 请参阅 “设置项目”。

Windows ML 文本生成 API 简化了通过自己的语言模型运行文本生成。 它在 Windows ML Runtime API 之上为你处理令牌化、自回归解码、流式输出和取消,就像 ONNX Runtime GenAI 在 ONNX Runtime 之上简化该流程一样。 Windows 不会为此 API 提供模型;你需要自行选择、打包,并与你的应用一起分发该模型。 它是Windows ML 任务 API之一。

Tip

如果不需要特定模型,只是想要使用 Microsoft 管理的模型在设备上进行文本生成,请改用现成的本地 LLM之一。

在 Windows ML 2.9 中,可以为任务指定模型,如选择任务如何运行你的模型所述。 这是最短的路径:不生成管道,不传递 tokenizer。 或者,可以创建基础运行时对象(模型、执行目标和管道),并将其传递给会话,如本文的其余部分所示。 此路径不隐藏硬件放置;它只是让你无需自己编写令牌循环。

支持的模型

为任务指定模型时,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)。

文本生成 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 加载它,然后再将其指定给任务;请参阅 “选择任务运行模型的方式”。 分词器来自模型的文件,因此你无需提供。
  • 在您构建的管道中,通过 ONNX Runtime 运行 ONNX(.onnx)或 ORT 格式(.ort)模型。 模型必须公开令牌 ID 输入、logits 输出和一个固定容量状态张量对,用于保存键/值缓存和序列位置。 您提供单独的 tokenizer 源(例如,tokenizer.json)。

这些示例根据 Qwen2.5-0.5B-Instruct 模型系列验证此协定,该系列使用特定于任务的图形导出,该图形将键/值缓存和序列位置打包成一个状态对。 公开相同令牌输入、logits 输出和状态协定的其他仅解码器语言模型也应适用。

生成文本

文本生成会话包装 tokenizer 和有状态管道(拥有键/值缓存的模型)。 加载模型和 tokenizer、描述模型的令牌输入、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
  • 提示和生成的令牌计数
  • 完成原因 - 序列结束令牌、停止令牌、请求的令牌限制、序列容量、取消或错误

推测解码

推测解码默认处于关闭状态。 草稿源建议多个令牌,模型在一个步骤中对其进行验证,任务会保留模型本来会自行选择的令牌。 使用贪婪解码时,文本保持不变,除非两个令牌之间出现罕见的近乎平局的情况。 在验证配置之前,请在推测选项中选择一种方法:PROMPT_LOOKUP、MODEL或DRAFT_MODEL。 模型支持的方法取决于加载模型的方式;请参阅 推测解码。 最终结果会报告生效的方法,以及草拟和接受的令牌数量。

C#、C++ 和 Python

本机 API 通过 WinMLTasks.h 公开,并在 winml/tasks/text_generation/TextGeneration.hpp 下提供类型化的 C++ 辅助程序。 Python 应用程序使用 windowsml.tasks 投影以及 windowsml.runtime。 C# 应用程序通过复制到项目中的包装器使用 CsWin32 绑定;请参阅 “设置项目”。

Windows ML 示例包括 C++、C# 和Python文本生成示例。 这些示例显示文本生成配置旁边的完整运行时设置,以便查看抽象的开始位置以及如何自定义基础工作流。

另请参阅