建立及管理模型
本文說明如何微調及使用自訂翻譯 LLM 模型。
事前準備
開始前,您必須準備監督式微調資料集。視應用情況而定,會有不同的需求。
- 準備用於調整的文字資料集:文字調整
啟用 Vertex AI API
如要微調自訂 TLLM 模型,請完成下列步驟:
啟用 Vertex AI API。
啟用 API 時所需的角色
您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「服務使用情形管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。
支援的模型
translation-llm-002(支援文字調整。預先發布版。)
建立微調工作
您可以使用 REST API 或 Vertex AI SDK for Python,建立監督式微調工作。
REST
如要建立模型微調作業,請使用 tuningJobs.create 方法傳送 POST 要求。部分參數不支援所有模型。請務必只加入要微調模型適用的參數。
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_ID:PROJECT_ID。
- TUNING_JOB_REGION:執行微調工作的區域。這也是上傳微調模型的預設區域。支援的區域:
us-central1。 - BASE_MODEL:要微調的翻譯模型名稱。支援的值:
translation-llm-002。 - TRAINING_DATASET_URI:訓練資料集的 Cloud Storage URI。資料集必須採用 JSONL 檔案格式。為獲得最佳結果,請提供至少 100 到 500 個範例。詳情請參閱「關於監督式微調資料集」。
- VALIDATION_DATASET_URI選用:驗證資料集檔案的 Cloud Storage URI。
- TUNED_MODEL_DISPLAYNAME選用:微調後模型的顯示名稱。如未設定,系統會產生隨機名稱。
HTTP 方法和網址:
POST https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs
JSON 要求內文:
{
"baseModel": "BASE_MODEL",
"supervisedTuningSpec" : {
"trainingDatasetUri": "TRAINING_DATASET_URI",
"validationDatasetUri": "VALIDATION_DATASET_URI",
},
"tunedModelDisplayName": "TUNED_MODEL_DISPLAYNAME"
}
如要傳送要求,請選擇以下其中一個選項:
curl
將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs"
PowerShell
將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs" | Select-Object -Expand Content
您應該會收到類似如下的 JSON 回應。
Python
from vertexai.generative_models import GenerativeModel
sft_tuning_job = sft.SupervisedTuningJob("projects/<PROJECT_ID>/locations/<TUNING_JOB_REGION>/tuningJobs/<TUNING_JOB_ID>")
tuned_model = GenerativeModel(sft_tuning_job.tuned_model_endpoint_name)
print(tuned_model.generate_content(content))
import time
import vertexai
from vertexai.tuning import sft
# TODO(developer): Update and un-comment below line.
# PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"]
vertexai.init(project=PROJECT_ID, location="us-central1")
sft_tuning_job = sft.train(
source_model="translation-llm-002",
train_dataset="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl",
# The following parameters are optional
validation_dataset="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl",
tuned_model_display_name="tuned_translation_llm_002",
)
# Polling for job completion
while not sft_tuning_job.has_ended:
time.sleep(60)
sft_tuning_job.refresh()
print(sft_tuning_job.tuned_model_name)
print(sft_tuning_job.tuned_model_endpoint_name)
print(sft_tuning_job.experiment)
# Example response:
# projects/123456789012/locations/us-central1/models/1234567890@1
# projects/123456789012/locations/us-central1/endpoints/123456789012345
# <google.cloud.aiplatform.metadata.experiment_resources.Experiment object at 0x7b5b4ae07af0>
查看調整工作清單
您可以使用 Google Cloud 控制台、Python 適用的 Vertex AI SDK,或使用 tuningJobs 方法傳送 GET 要求,查看目前專案的微調作業清單。
REST
如要查看模型微調作業清單,請使用 tuningJobs.list 方法傳送 GET 要求。
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_ID:PROJECT_ID。
- TUNING_JOB_REGION:執行微調工作的區域。這也是上傳微調模型的預設區域。
HTTP 方法和網址:
GET https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs
如要傳送要求,請選擇以下其中一個選項:
curl
執行下列指令:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs"
PowerShell
執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs" | Select-Object -Expand Content
您應該會收到類似如下的 JSON 回應。
Python
控制台
如要在 Google Cloud 控制台中查看微調工作,請前往 Vertex AI Studio 頁面。
在「Translation LLM tuned models」(翻譯 LLM 微調模型) 部分下方的表格中,查看翻譯 LLM 微調工作。
取得調整工作的詳細資料
您可以使用 Google Cloud 控制台、Vertex AI SDK for Python,或使用 tuningJobs 方法傳送 GET 要求,取得目前專案中微調工作的詳細資料。
REST
如要查看模型微調作業清單,請使用 tuningJobs.get 方法傳送 GET 要求,並指定 TuningJob_ID。
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_ID:PROJECT_ID。
- TUNING_JOB_REGION:執行微調工作的區域。這也是上傳微調模型的預設區域。
- TUNING_JOB_ID:微調作業的 ID。
HTTP 方法和網址:
GET https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs/TUNING_JOB_ID
如要傳送要求,請選擇以下其中一個選項:
curl
執行下列指令:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs/TUNING_JOB_ID"
PowerShell
執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs/TUNING_JOB_ID" | Select-Object -Expand Content
您應該會收到類似如下的 JSON 回應。
Python
控制台
如要在 Google Cloud 控制台中查看微調模型的詳細資料,請前往「Vertex AI Studio」頁面。
在「Translation LLM tuned models」(翻譯 LLM 微調模型) 表格中,找到您的模型並點按「Details」(詳細資料)。
系統會顯示模型詳細資料。
取消微調工作
如要取消目前專案的微調作業,可以使用 Google Cloud 控制台、Python 適用的 Vertex AI SDK,或使用 tuningJobs 方法傳送 POST 要求。
REST
如要查看模型微調作業清單,請使用 tuningJobs.cancel 方法傳送 GET 要求,並指定 TuningJob_ID。
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_ID:PROJECT_ID。
- TUNING_JOB_REGION:執行微調工作的區域。這也是上傳微調模型的預設區域。
- TUNING_JOB_ID:微調作業的 ID。
HTTP 方法和網址:
POST https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs/TUNING_JOB_ID:cancel
如要傳送要求,請選擇以下其中一個選項:
curl
執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs/TUNING_JOB_ID:cancel"
PowerShell
執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://TUNING_JOB_REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/TUNING_JOB_REGION/tuningJobs/TUNING_JOB_ID:cancel" | Select-Object -Expand Content
您應該會收到類似如下的 JSON 回應。
Python
控制台
如要在 Google Cloud 控制台中取消微調作業,請前往「Vertex AI Studio」頁面。
在「Translation tuned models」(翻譯微調模型) 表格中,按一下「管理執行」。
按一下「取消」。
取得模型相關資訊
訓練完成後,您可以取得模型相關資訊,例如模型 ID。
如要查看可用模型清單,請前往 Vertex AI 端點頁面。
使用微調後的模型
下列範例使用模型 ID 為 1395675701985363739 的自訂模型翻譯文字。如要使用自訂翻譯 LLM,請指定 models/translation-llm-custom/{model-id} 做為模型 ID。
您可以使用 model 查詢參數指定要使用哪個模型執行翻譯作業。
REST
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_ID:您的 Google Cloud 專案 ID
- LOCATION:自訂模型所在的區域,例如
us-central1。
HTTP 方法和網址:
POST https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText
JSON 要求內文:
{
"model": "projects/PROJECT_ID/locations/LOCATION/model/translation-llm-custom/1395675701985363739",
"sourceLanguageCode": "en",
"targetLanguageCode": "ru",
"contents": ["Dr. Watson, please discard your trash. You've shared unsolicited email with me.
Let's talk about spam and importance ranking in a confidential mode."]
}
如要傳送要求,請選擇以下其中一個選項:
curl
將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText"
PowerShell
將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText" | Select-Object -Expand Content
您應該會收到如下的 JSON 回覆:
{
"translation": {
"translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора.
Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о
спаме и важности рейтинга в конфиденциальном режиме.",
"model": "projects/PROJECT_NUMBER/locations/LOCATION/model/translation-llm-custom/1395675701985363739"
}
}
Python
from google.cloud import translate
def translate_text_with_model(
text: str = "YOUR_TEXT_TO_TRANSLATE",
project_id: str = "YOUR_PROJECT_ID",
model_id: str = "YOUR_MODEL_ID",
) -> translate.TranslationServiceClient:
"""Translates a given text using Translation custom model."""
client = translate.TranslationServiceClient()
location = "us-central1"
parent = f"projects/{project_id}/locations/{location}"
model_path = f"{parent}/models/translation-llm-custom/{model_id}"
# Supported language codes: https://cloud.google.com/translate/docs/languages
response = client.translate_text(
request={
"contents": [text],
"target_language_code": "ja",
"model": model_path,
"source_language_code": "en",
"parent": parent,
"mime_type": "text/plain", # mime types: text/plain, text/html
}
)
# Display the translation for each input text provided
for translation in response.translations:
print(f"Translated text: {translation.translated_text}")
return response
調整及驗證指標
您可以設定模型調整工作,收集及回報模型調整和模型評估指標,然後在 Vertex AI Studio 中以視覺化方式呈現。
如要在 Google Cloud 控制台中查看微調模型的詳細資料,請前往「Vertex AI Studio」頁面。
在「微調和蒸餾」表格中,按一下要查看指標的微調模型名稱。
調整指標會顯示在「監控」分頁下方。
模型調整指標
模型微調作業會自動收集 translation-llm-002 的下列微調指標。
/train_total_loss:訓練步驟中微調資料集的損失。/train_fraction_of_correct_next_step_preds:訓練步驟的權杖準確度。單一推論包含一系列預測的符記。這項指標會比較預測的詞元與調整資料集中的基準真相,藉此衡量預測詞元的準確率。/train_num_predictions:訓練步驟中預測的權杖數量。
模型驗證指標:
您可以設定模型微調工作,為 translation-llm-002 收集下列驗證指標。
/eval_total_loss:驗證步驟中驗證資料集的損失。/eval_fraction_of_correct_next_step_preds:驗證步驟中的詞元準確率。單一推論包含一系列預測的符記。這項指標會比較驗證資料集中的預測詞元與基準真相,藉此評估預測詞元的準確率。/eval_num_predictions:驗證步驟中預測的權杖數量。
調整工作開始執行後,即可查看指標的視覺化資料。 微調期間,系統會即時更新。如果您在建立調整工作時未指定驗證資料集,則只能使用調整指標的視覺化功能。
後續步驟
- 如要瞭解如何運用監督式微調技術,建構生成式 AI 知識庫解決方案,請參閱快速部署解決方案:生成式 AI 知識庫。