Foundry Local 在你的裝置上運行 ONNX 模型。 用 Olive 把模型從 Hugging Face(Safetensors 或 PyTorch) 轉換並優化成 ONNX,這樣你就能用 Foundry Local 執行它們。
重要
Olive CLI 與優化設定會隨時間改變,單一命令列範例可能無法適用於所有模型、裝置或執行提供者。
想要最可靠和最新的示例,請從 Olive Recipes 資料庫開始。 它提供一組針對不同模型的目標配方,針對不同硬體和不同的優化設定進行優化。
- 如需更多此模型的 Olive CLI 設定,請參閱 recipe 資料夾: https://github.com/microsoft/olive-recipes/tree/main/meta-llama-Llama-3.2-1B-Instruct/olive。
本指南說明如何:
- 將 Hugging Face 的模型轉換並優化,讓它們能在 Foundry Local 執行。 範例中都有使用這個
Llama-3.2-1B-Instruct模型,但許多擁抱臉的模型也能運作。 - 用 Foundry Local 跑你的優化模型。
先決條件
- Python 3.10 或更新版本(Olive 編譯必備)
- 需要一個 Hugging Face 帳戶,以及一個具有存取
meta-llama/Llama-3.2-1B-Instruct權限的權杖。
安裝 Olive 與依賴項
Olive 優化模型並將其轉換為 ONNX 格式。
pip install olive-ai
pip install transformers onnxruntime-genai
確認安裝:olive --help 印出使用資訊。
登入 Hugging Face
該 Llama-3.2-1B-Instruct 模型需要 Hugging Face 認證。
hf auth login
註
在繼續前,請建立一個 Hugging Face 代幣並申請模型存取權。
提示
如果 hf 找不到,請執行 pip install -U huggingface_hub。
編譯模型
本節將逐步說明手動編譯。 Olive optimize 指令可以下載、轉換、量化並優化模型。
註
以下腳本是一個手動範例,可能需要針對不同型號或硬體目標進行調整。
執行 Olive
optimize指令:olive optimize \ --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ --trust_remote_code \ --output_path models/llama \ --device cpu \ --provider CPUExecutionProvider \ --precision int4 \ --log_level 1指令使用以下參數:
參數 描述 model_name_or_path模型來源:Hugging Face ID、本地路徑或 Azure AI 模型登錄檔 ID output_path優化模型該在哪裡儲存 device目標硬體: cpu、、gpu或npuprovider執行提供者(例如, CPUExecutionProvider, )CUDAExecutionProviderprecision模型精度: fp16、fp32、int4或int8提示
如果你有本地模型副本,請使用本地路徑代替 Hugging Face ID。 例如,
--model_name_or_path models/llama-3.2-1B-Instruct。 Olive 會自動處理轉換、優化和量化。註
編譯過程約需 60 秒,加上下載時間。
透過在模型目錄中建立
inference_model.json檔案,將模型暴露給 Foundry 本地。# generate_inference_model.py import json import os model_path = "models/llama" json_template = { "Name": "llama-3.2:1" # set the model name as you like, the default version is 1 } 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驗證該檔案是否存在:
models/llama/inference_model.json。
執行編譯好的模型
使用 Foundry Local C# SDK 載入並執行已編譯的模型,並搭配原生聊天完成 API。 這種方法不需要 REST 伺服器——SDK 直接與執行時溝通。
先決條件
- .NET 8.0 SDK 或更新版本
安裝套件
如果你正在開發或在Windows上部署,請選擇
GitHub 倉庫裡的 C# 範例都是預先設定好的專案。 如果你是從零開始建立,建議閱讀 Foundry Local SDK 參考資料 ,了解更多如何用 Foundry Local 設定 C# 專案的細節。
對已編譯的模型執行推論
將 Program.cs 的內容替換為以下代碼:
using Microsoft.AI.Foundry.Local;
using Betalgo.Ranul.OpenAI.ObjectModels.RequestModels;
using Microsoft.Extensions.Logging;
CancellationToken ct = CancellationToken.None;
// Point ModelCacheDir at the directory containing your compiled model
var config = new Configuration
{
AppName = "run-compiled-model",
LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information,
ModelCacheDir = "../models"
};
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
});
var logger = loggerFactory.CreateLogger<Program>();
await FoundryLocalManager.CreateAsync(config, logger);
var mgr = FoundryLocalManager.Instance;
var catalog = await mgr.GetCatalogAsync();
// List cached models to find your compiled model
var cachedModels = await catalog.GetCachedModelsAsync();
Console.WriteLine("Cached models:");
foreach (var m in cachedModels)
{
Console.WriteLine($" {m.Id}");
}
// Select your compiled model from the cached list
var model = cachedModels.FirstOrDefault(m => m.Id.Contains("llama-3.2:1"))
?? throw new Exception("Compiled model not found. Verify the ModelCacheDir path.");
await model.LoadAsync();
// Use native chat completions
var chatClient = await model.GetChatClientAsync();
List<ChatMessage> messages = new()
{
new ChatMessage { Role = "user", Content = "What is the golden ratio?" }
};
var streamingResponse = chatClient.CompleteChatStreamingAsync(messages, ct);
await foreach (var chunk in streamingResponse)
{
Console.Write(chunk.Choices[0].Delta.Content);
Console.Out.Flush();
}
Console.WriteLine();
await model.UnloadAsync();
執行應用程式:
dotnet run
使用 Foundry Local JavaScript SDK 載入並執行已編譯的模型,搭配原生聊天完成 API。
先決條件
- Node.js 20 或更高版本已安裝。
安裝套件
如果你正在開發或在Windows上部署,請選擇
對已編譯的模型執行推論
將以下程式碼複製並貼上到一個名為 app.js 的 JavaScript 檔案中:
import { FoundryLocalManager } from 'foundry-local-sdk';
// Initialize the Foundry Local SDK with custom model cache directory
const manager = FoundryLocalManager.create({
appName: 'run-compiled-model',
logLevel: 'info',
modelCacheDir: '../models'
});
// List cached models to find your compiled model
const cachedModels = await manager.catalog.getCachedModels();
console.log('Cached models:');
for (const m of cachedModels) {
console.log(` ${m.id}`);
}
// Select your compiled model from the cached list
const model = cachedModels.find(m => m.id.includes('llama-3.2:1'));
if (!model) {
throw new Error('Compiled model not found. Verify the modelCacheDir path.');
}
// Load the model
await model.load();
// Create a chat client
const chatClient = model.createChatClient();
// Generate a response
const completion = await chatClient.completeChat([
{ role: 'user', content: 'What is the golden ratio?' }
]);
console.log(completion.choices[0]?.message?.content);
// Unload the model
await model.unload();
執行應用程式:
node app.js
使用 Foundry Local Python SDK 載入並執行已編譯的模型,並搭配原生聊天完成 API。
先決條件
- Python 3.11 或更新版本安裝。
安裝套件
如果你正在開發或在Windows上部署,請選擇
對已編譯的模型執行推論
將以下程式碼複製並貼上到一個名為 app.py 的Python檔案中:
import asyncio
from foundry_local_sdk import Configuration, FoundryLocalManager
async def main():
# Point model_cache_dir at the directory containing your compiled model
config = Configuration(
app_name="run-compiled-model",
model_cache_dir="../models",
)
FoundryLocalManager.initialize(config)
manager = FoundryLocalManager.instance
# List cached models to find your compiled model
cached_models = manager.catalog.get_cached_models()
print("Cached models:")
for m in cached_models:
print(f" {m.id}")
# Select your compiled model from the cached list
model = next((m for m in cached_models if "llama-3.2:1" in m.id), None)
if model is None:
raise Exception("Compiled model not found. Verify the model_cache_dir path.")
# Load the model
model.load()
# Get a chat client
client = model.get_chat_client()
# Stream the response
messages = [{"role": "user", "content": "What is the golden ratio?"}]
for chunk in client.complete_streaming_chat(messages):
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
print()
# Tidy up - unload the model
model.unload()
if __name__ == "__main__":
asyncio.run(main())
執行應用程式:
python app.py
使用 Foundry Local Rust SDK 載入並執行已編譯的模型,搭配原生聊天完成 API。
先決條件
- 已安裝 Rust 與 Cargo(Rust 1.70.0 或更新版本)。
安裝套件
如果你正在開發或在Windows上部署,請選擇
cargo add foundry-local-sdk --features winml
cargo add tokio --features full
cargo add tokio-stream anyhow
對已編譯的模型執行推論
將 src/main.rs 的內容替換為以下代碼:
use foundry_local_sdk::{
ChatCompletionRequestMessage, ChatCompletionRequestUserMessage,
FoundryLocalConfig, FoundryLocalManager,
};
use std::io::Write;
use tokio_stream::StreamExt;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Point model_cache_dir at the directory containing your compiled model
let config = FoundryLocalConfig::new("run-compiled-model")
.with_model_cache_dir("../models");
let manager = FoundryLocalManager::create(config)?;
// List cached models to find your compiled model
let cached_models = manager.catalog().get_cached_models().await?;
println!("Cached models:");
for m in &cached_models {
println!(" {}", m.id());
}
// Select your compiled model from the cached list
let model = cached_models
.iter()
.find(|m| m.id().contains("llama-3.2:1"))
.ok_or_else(|| anyhow::anyhow!("Compiled model not found. Verify the model_cache_dir path."))?;
// Load the model
model.load().await?;
// Create a chat client
let client = model.create_chat_client().temperature(0.7).max_tokens(256);
// Stream the response
let messages: Vec<ChatCompletionRequestMessage> = vec![
ChatCompletionRequestUserMessage::new("What is the golden ratio?").into(),
];
let mut stream = client.complete_streaming_chat(&messages, None).await?;
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if let Some(content) = &chunk.choices[0].delta.content {
print!("{}", content);
std::io::stdout().flush()?;
}
}
println!();
// Tidy up - unload the model
model.unload().await?;
Ok(())
}
執行應用程式:
cargo run
故障排除
- 若
olive optimize因認證或存取錯誤失敗,請確認你的 Hugging Face 令牌並確認模型存取申請已獲批准。 - 如果找不到
hf命令,請執行pip install -U huggingface_hub來安裝。 - 如果已編譯的模型在快取模型清單中找不到,請確認
ModelCacheDir你Configuration所在的路徑指向包含模型資料夾的父目錄。 - 如果您遇到參考
net8.0的 .NET 建置錯誤,請安裝 .NET 8.0 SDK。