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

编译拥抱人脸模型以在本地 Foundry 上运行

重要

  • Foundry Local 以预览版提供。 公共预览版提供对活动部署中的功能的早期访问。
  • 正式发布 (GA) 之前,功能、方法和流程可能会发生更改或具有受限的功能。

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

若要将 Safetensor 或 PyTorch 格式的现有模型编译为 ONNX 格式,可以使用 Olive。 Olive 是一种将模型优化为 ONNX 格式的工具,使其适合在 Foundry Local 中部署。 它使用 量化图形优化 等技术来提高性能。

本指南介绍如何:

  • 转换和优化 Hugging Face 的模型以在 Foundry Local 中运行。 你将使用 Llama-3.2-1B-Instruct 模型作为示例,但你可以使用 Hugging Face 中的任何生成 AI 模型。
  • 使用 Foundry Local 运行优化模型

先决条件

  • Python 3.10 或更高版本

安装 Olive

Olive 是一种将模型优化为 ONNX 格式的工具。

pip install olive-ai[auto-opt]

小窍门

为了获得最佳效果,请使用 venvconda 在虚拟环境中安装 Olive。

登录到 Hugging Face

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

huggingface-cli login

注释

在继续作之前,必须先 创建拥抱人脸令牌请求模型访问

编译模型

步骤 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、、int4fp32int8
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 对象,其中包含 Foundry Local 在运行时通过用户提示注入的 {Content} 占位符。

{
  "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 库中的方法:

注释

以下示例使用 Python 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 will start the Foundry 
# Local service if it is not already running and load the specified model.
manager = FoundryLocalManager(modelId)

# The remaining code us es 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 请求的任何语言。 有关详细信息,请阅读集成推理 SDK 与 Foundry Local 一文。

即将完成

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

foundry cache cd ./foundry/cache/models

后续步骤