AI Toolkit for VS Code (AI Toolkit) 是一個 VS Code 延伸模組,可讓您使用您的應用程式或雲端下載、測試、微調及部署 AI 模型。 如需詳細資訊,請參閱 AI 工具組概觀。
在本文中,您將學會如何:
- 安裝適用於的 AI 工具組 VS Code
- 從目錄下載模型
- 使用遊樂場在本機執行模型
- 使用 REST 或 ONNX 執行時間將 AI 模型整合到您的應用程式
必要條件
使用 AI 功能時,建議您檢閱:在 Windows上開發負責任的產生式 AI 應用程式和功能。
安裝
AI 工具組可在 Visual Studio Marketplace 中使用,而且可以像任何其他VS Code延伸模組一樣安裝。 如果您不熟悉安裝 VS Code 擴充功能,請遵循下列步驟:
- 在 [活動列] 中 VS Code ,選取 [擴充功能]
- 在 [擴充功能] 搜尋列中,輸入 “AI Toolkit”
- 選取 [適用於 Visual Studio Code 的 AI 工具組]
- 選取 [安裝]
安裝延伸模組之後,您會看到 AI 工具組圖示出現在您的活動列中。
從目錄下載模型
AI 工具組的主要提要字段會組織成 我的模型、目錄、工具,以及 說明與意見反應。
遊樂場、大量執行、評估和 微調 功能可以在 工具 區域中取得。 要開始,請從 [目錄] 區段中選擇 [模型],以開啟 [模型目錄] 視窗。
中 AI 工具組模型類別目錄視窗的螢幕快照
您可以使用目錄頂端的篩選條件 ,依、Publisher、Tasks和 Model 類型篩選。 另外還有一個 Fine-Tuning 支援 切換開關,只顯示可以微調的模型。
提示
模型類型 篩選條件可讓您顯示僅在 CPU、GPU 或 NPU 上本機執行的模型,或僅支援 遠端存取的模型。 針對至少有一個 GPU 之裝置的優化效能,請選取本機執行 w/ GPU 的模型類型。 這有助於尋找針對 DirectML 加速器優化的模型。
若要檢查您的 Windows 裝置上是否有 GPU,請開啟 [任務管理器 ],然後選取 [效能] 索引標籤。如果您有 GPU(s),它們將會列在 「GPU 0」 或 「GPU 1」 等名稱之下。
下列模型目前適用於具有一或多個 GPU 的 Windows 裝置:
- Mistral 7B (DirectML - 小型,快速)
- Phi 3 迷你 4K (DirectML - 小型,快速)
- Phi 3 迷你 128K (DirectML - 小型,快速)
選取 Phi 3 Mini 4K 模型,然後按一下 下載。
注意
Phi 3 迷你 4K 模型的大小約為 2GB-3GB。 視您的網路速度而定,下載可能需要幾分鐘的時間。
在遊樂場中執行模型
下載模型之後,它會出現在 [本機模型] 底下的 [我的模型] 區段中。 右鍵點擊模型,然後從快顯功能表中選取 [在遊樂場中載入]:
在遊樂場的聊天介面中,輸入下列訊息,後面接著 Enter 鍵:
您應該會看到模型回應已串流回您:
警告
如果您的裝置上沒有可用的 GPU,但您選取了 Phi-3-mini-4k-directml-int4-awq-block-128-onnx 模型,模型回應會非常慢。 您應該改為下載 CPU 優化版本:Phi-3-mini-4k-cpu-int4-rtn-block-32-acc-level-4-onnx。
您也可以變更:
-
內容指示: 協助模型瞭解您要求的大局。 這可能是背景資訊、您想要的範例/示範,或說明工作的目的。
-
推斷參數:
-
回應長度上限:模型將傳回的令牌數目上限。
-
溫度:模型溫度是一個參數,可控制語言模型輸出的隨機程度。 較高的溫度表示模型會承擔更多風險,讓您混合使用各種單字。 另一方面,較低的溫度可讓模型發揮其安全,並堅持更專注且可預測的回應。
-
Top P:也稱為核取樣,是一種設定,可控制預測下一個單字時語言模型所考慮的可能單字或詞組數目
-
頻率懲罰:此參數會影響模型在其輸出中重複單字或片語的頻率。 值愈高(接近 1.0)會鼓勵模型 避免 重複單字或片語。
-
存在懲罰:此參數用於產生 AI 模型中的多樣性和特定性。 較高的值(接近1.0)鼓勵模型包含更新穎且多樣化的令牌。 較低的值較可能讓模型產生一般或陳詞濫調詞組。
將 AI 模型整合到您的應用程式
有兩個選項可將模型整合到您的應用程式:
- AI 工具組隨附使用 OpenAI 聊天完成格式REST本機 API 網頁伺服器。 這可讓您在本機使用端點
http://127.0.0.1:5272/v1/chat/completions
來測試應用程式,而不需要依賴雲端 AI 模型服務。 如果您想要切換至生產中的雲端端點,請使用此選項。 您可以使用 OpenAI 用戶端連結庫來連線到網頁伺服器。
-
使用 ONNX 執行時間。 如果您想要將模型 與應用程式一起隨附於 裝置上的推斷,請使用此選項。
本機 REST API 網頁伺服器
REST本機 API Web 伺服器可讓您在本機建置及測試應用程式,而不需要依賴雲端 AI 模型服務。 您可以使用 或 OpenAI 用戶端連結庫與網頁伺服器 REST互動:
以下是您 REST 要求的範例本文:
{
"model": "Phi-3-mini-4k-directml-int4-awq-block-128-onnx",
"messages": [
{
"role": "user",
"content": "what is the golden ratio?"
}
],
"temperature": 0.7,
"top_p": 1,
"top_k": 10,
"max_tokens": 100,
"stream": true
}'
注意
您可能需要將模型欄位更新為您下載的模型名稱。
您可以使用 PostmanRESTAPI 工具來測試端點:
curl -vX POST http://127.0.0.1:5272/v1/chat/completions -H 'Content-Type: application/json' -d @body.json
安裝 OpenAI Python 連結庫:
pip install openai
from openai import OpenAI
client = OpenAI(
base_url="http://127.0.0.1:5272/v1/",
api_key="x" # required by API but not used
)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "what is the golden ratio?",
}
],
model="Phi-3-mini-4k-directml-int4-awq-block-128-onnx",
)
print(chat_completion.choices[0].message.content)
使用 NuGet 將適用於 .NET 的 Azure OpenAI 用戶端連結庫新增至您的專案:
dotnet add {project_name} package Azure.AI.OpenAI --version 1.0.0-beta.17
將名為 OverridePolicy.cs 的 C# 檔案新增至您的專案,並貼上下列程式代碼:
// OverridePolicy.cs
using Azure.Core.Pipeline;
using Azure.Core;
internal partial class OverrideRequestUriPolicy(Uri overrideUri)
: HttpPipelineSynchronousPolicy
{
private readonly Uri _overrideUri = overrideUri;
public override void OnSendingRequest(HttpMessage message)
{
message.Request.Uri.Reset(_overrideUri);
}
}
接下來,將下列程式代碼貼到 您的Program.cs 檔案中:
// Program.cs
using Azure.AI.OpenAI;
Uri localhostUri = new("http://localhost:5272/v1/chat/completions");
OpenAIClientOptions clientOptions = new();
clientOptions.AddPolicy(
new OverrideRequestUriPolicy(localhostUri),
Azure.Core.HttpPipelinePosition.BeforeTransport);
OpenAIClient client = new(openAIApiKey: "unused", clientOptions);
ChatCompletionsOptions options = new()
{
DeploymentName = "Phi-3-mini-4k-directml-int4-awq-block-128-onnx",
Messages =
{
new ChatRequestSystemMessage("You are a helpful assistant. Be brief and succinct."),
new ChatRequestUserMessage("What is the golden ratio?"),
}
};
StreamingResponse<StreamingChatCompletionsUpdate> streamingChatResponse
= await client.GetChatCompletionsStreamingAsync(options);
await foreach (StreamingChatCompletionsUpdate chatChunk in streamingChatResponse)
{
Console.Write(chatChunk.ContentUpdate);
}
注意
如果您下載 Phi3 模型的 CPU 版本,則必須將模型字段更新為 Phi-3-mini-4k-cpu-int4-rtn-block-32-acc-level-4-onnx。
ONNX 執行環境
ONNX 運行時間產生 API 提供 ONNX 模型的產生 AI 迴圈,包括 ONNX 運行時間的推斷、logits 處理、搜尋和取樣,以及 KV 快取管理。 您可以呼叫高階 generate()
方法,或在迴圈中執行模型的每個反覆專案、一次產生一個令牌,以及選擇性地更新迴圈內的產生參數。
它支援貪婪/梁搜尋和 TopP、TopK 取樣,以產生令牌序列和內建的對數處理,例如重複處罰。 下列程式代碼是如何在應用程式中運用 ONNX 執行時間的範例。
請參閱本機 REST API 網頁伺服器中顯示的範例。 AI Toolkit REST Web 伺服器是使用 ONNX Runtime 所建置。
安裝 Numpy:
pip install numpy
接下來,根據您的平臺和 GPU 可用性,將 ONNX Runtime Python 套件安裝到您的專案中:
平台 |
GPU 可用 |
PyPI |
窗戶 |
是的 (AMD、NVIDIA、Intel、Qualcomm 等支援) |
pip install --pre onnxruntime-genai-directml |
Linux |
是的 (Nvidia CUDA) |
pip install --pre onnxruntime-genai-cuda --index-url=https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-genai/pypi/simple/ |
窗戶 Linux |
否 |
pip install --pre onnxruntime-genai |
提示
我們建議使用 venv 或 conda 將 Python 套件安裝到虛擬環境中。
接下來,將下列程式代碼複製並貼到名為 app.py 的 Python 檔案中:
# app.py
import onnxruntime_genai as og
import argparse
def main(args):
print("Loading model...")
model = og.Model(f'{args.model}')
print("Model loaded")
tokenizer = og.Tokenizer(model)
tokenizer_stream = tokenizer.create_stream()
search_options = {
'max_length': 2048
}
chat_template = '<|user|>\n{input} <|end|>\n<|assistant|>'
# Keep asking for input prompts in a loop
while True:
text = input("Input: ")
# If there is a chat template, use it
prompt = f'{chat_template.format(input=text)}'
input_tokens = tokenizer.encode(prompt)
params = og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids = input_tokens
generator = og.Generator(model, params)
print("\nOutput: ", end='', flush=True)
while not generator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token = generator.get_next_tokens()[0]
print(tokenizer_stream.decode(new_token), end='', flush=True)
print()
print()
# Delete the generator to free the captured graph for the next generator, if graph capture is enabled
del generator
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--model', type=str, required=True, help='Onnx model folder path (must contain config.json and model.onnx)')
args = parser.parse_args()
main(args)
若要執行 Python 應用程式,請使用下列程式代碼:
python app.py --model ~/.aitk/models/{path_to_folder_containing_onnx_file}
注意
AI Toolkit 會將模型快取下載到使用者目錄中名為 .aitk
的隱藏資料夾 - 您必須將參數--model
所使用的路徑更新為包含 ONNX 模型檔案的資料夾位置。 例如 ~/.aitk/models/microsoft/Phi-3-mini-4k-instruct-onnx/directml/Phi-3-mini-4k-directml-int4-awq-block-128-onnx/
根據您的平臺和 GPU 可用性,將 ONNX Runtime NuGet 套件安裝到您的專案中:
將下列程式代碼複製並貼到您的 C# 檔案中:
using Microsoft.ML.OnnxRuntimeGenAI;
// update user_name and path placeholders
string modelPath = "C:\\Users\\{user_name}\\.aitk\\models\\{path}";
Console.Write("Loading model from " + modelPath + "...");
using Model model = new(modelPath);
Console.Write("Done\n");
using Tokenizer tokenizer = new(model);
using TokenizerStream tokenizerStream = tokenizer.CreateStream();
while (true)
{
Console.Write("User:");
string? input = Console.ReadLine();
string prompt = "<|user|>\n" + input + "<|end|>\n<|assistant|>";
var sequences = tokenizer.Encode(prompt);
using GeneratorParams generatorParams = new GeneratorParams(model);
generatorParams.SetSearchOption("max_length", 200);
generatorParams.SetInputSequences(sequences);
Console.Out.Write("\nAI:");
using Generator generator = new(model, generatorParams);
while (!generator.IsDone())
{
generator.ComputeLogits();
generator.GenerateNextToken();
Console.Out.Write(tokenizerStream.Decode(generator.GetSequence(0)[^1]));
Console.Out.Flush();
}
Console.WriteLine();
}
注意
AI 工具群組會將模型快取下載到使用者目錄中名為 .aitk
的隱藏資料夾 - 您必須將 程式代碼中的 更新modelPath
為包含 ONNX 模型檔案的資料夾位置。 例如 ~/.aitk/models/microsoft/Phi-3-mini-4k-instruct-onnx/directml/Phi-3-mini-4k-directml-int4-awq-block-128-onnx/
後續步驟