你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

编译 Hugging Face 模型以在 Foundry Local 上运行

重要

  • Foundry Local 以预览版形式提供。 通过公共预览版,可以提前访问正处于开发状态的功能。
  • 正式发布 (GA) 之前,功能、方法和流程可能会发生更改或功能受限。

Foundry Local 在设备上运行具有高性能的 ONNX 模型。 虽然模型目录提供现成的预编译选项,但任何 ONNX 格式的模型都可以使用。

使用 Olive 将 Safetensor 或 PyTorch 格式的模型编译为 ONNX。 Olive 优化 ONNX 的模型,使其适合在 Foundry Local 中部署。 它使用量化和图形优化等技术来提高性能。

本指南演示如何:

  • 将 Hugging Face 的模型转换和优化,以便在 Foundry Local 中运行。 这些示例使用 Llama-3.2-1B-Instruct 模型,但 Hugging Face 中的任何生成 AI 模型都有效。
  • 使用 Foundry Local 运行优化的模型。

先决条件

  • Python 3.10 或更高版本

安装 Olive

奥利弗 优化模型并将其转换为 ONNX 格式。

pip install olive-ai[auto-opt]

小窍门

使用 venvconda 在虚拟环境中安装 Olive。

登录到 Hugging Face

模型 Llama-3.2-1B-Instruct 需要 Hugging Face 的身份验证。

huggingface-cli login

注释

在继续之前创建 Hugging Face 令牌请求模型访问

编译模型

步骤 1:运行 Olive 自动选择命令

使用 Olive auto-opt 命令下载、转换、量化和优化模型:

olive auto-opt \
    --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \
    --trust_remote_code \
    --output_path models/llama \
    --device cpu \
    --provider CPUExecutionProvider \
    --use_ort_genai \
    --precision int4 \
    --log_level 1

注释

编译过程大约需要 60 秒,以及下载时间。

该命令使用以下参数:

参数 DESCRIPTION
model_name_or_path 模型源:Hugging Face ID、本地路径或 Azure AI 模型注册表 ID
output_path 保存优化模型的位置
device 目标硬件: cpugpunpu
provider 执行提供程序(例如 CPUExecutionProviderCUDAExecutionProvider
precision 模型精度:fp16、、fp32int4int8
use_ort_genai 创建推理配置文件

小窍门

如果你有本地模型副本,则可以使用本地路径而不是 Hugging Face ID。 例如,--model_name_or_path models/llama-3.2-1B-Instruct。 Olive 会自动处理转换、优化和量化。

步骤 2:重命名输出模型

Olive 创建一个通用 model 目录。 重命名它,以便更轻松地重复使用:

cd models/llama
mv model llama-3.2

步骤 3:创建聊天模板文件

聊天模板是一种结构化格式,用于定义如何为聊天 AI 模型处理输入和输出消息。 它指定角色(例如系统、用户、助理)和聊天结构,确保模型了解上下文并生成适当的响应。

Foundry Local 需要一个名为 inference_model.json 的 JSON 聊天模板文件来生成响应。 该模板包括模型名称和对象 PromptTemplate 。 该对象包含一个占位符 {Content},Foundry Local 在运行时通过用户提示注入。

{
  "Name": "llama-3.2",
  "PromptTemplate": {
    "assistant": "{Content}",
    "prompt": "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nCutting Knowledge Date: December 2023\nToday Date: 26 Jul 2024\n\nYou are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{Content}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
  }
}

使用 apply_chat_template Hugging Face 库的方法创建聊天模板文件:

注释

此示例使用 Hugging Face 库(Olive 的依赖项)创建聊天模板。 如果使用的是同一 Python 虚拟环境,则无需安装它。 在其他环境中,使用 pip install transformers 安装它。

# generate_inference_model.py
# This script generates the inference_model.json file for the Llama-3.2 model.
import json
import os
from transformers import AutoTokenizer

model_path = "models/llama/llama-3.2"

tokenizer = AutoTokenizer.from_pretrained(model_path)
chat = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "{Content}"},
]


template = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)

json_template = {
  "Name": "llama-3.2",
  "PromptTemplate": {
    "assistant": "{Content}",
    "prompt": template
  }
}

json_file = os.path.join(model_path, "inference_model.json")

with open(json_file, "w") as f:
    json.dump(json_template, f, indent=2)

使用以下内容运行脚本:

python generate_inference_model.py

运行模型

使用 Foundry Local CLI、REST API 或 OpenAI Python SDK 运行已编译的模型。 首先,将模型缓存目录更改为在上一步中创建的模型目录:

foundry cache cd models
foundry cache ls  # should show llama-3.2

谨慎

完成后,将模型缓存更改回默认目录:

foundry cache cd ./foundry/cache/models

使用 Foundry 本地命令行界面 (CLI)

foundry model run llama-3.2 --verbose

使用 OpenAI Python SDK

使用 OpenAI Python SDK 与 Foundry 本地 REST API 进行交互。 安装步骤如下:

pip install openai
pip install foundry-local-sdk

然后使用以下代码运行模型:

import openai
from foundry_local import FoundryLocalManager

modelId = "llama-3.2"

# Create a FoundryLocalManager instance. This starts the Foundry Local service if it's not already running and loads the specified model.
manager = FoundryLocalManager(modelId)

# The remaining code uses the OpenAI Python SDK to interact with the local model.

# Configure the client to use the local Foundry service
client = openai.OpenAI(
    base_url=manager.endpoint,
    api_key=manager.api_key  # API key is not required for local usage
)

# Set the model to use and generate a streaming response
stream = client.chat.completions.create(
    model=manager.get_model_info(modelId).id,
    messages=[{"role": "user", "content": "What is the golden ratio?"}],
    stream=True
)

# Print the streaming response
for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="", flush=True)

小窍门

使用支持 HTTP 请求的任何语言。 有关详细信息,请参阅 使用 Foundry Local 集成推理 SDK

重置模型缓存

使用完自定义模型后,将模型缓存重置为默认目录:

foundry cache cd ./foundry/cache/models