使用自定义设置对 Gemini 进行微调,以满足高级使用场景

使用 Vertex AI 监督式微调功能和高级参数来调优生成式 AI 模型。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Python

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Python API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import time

import vertexai
from vertexai.tuning import sft

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
vertexai.init(project=PROJECT_ID, location="us-central1")

# Initialize Vertex AI with your service account for BYOSA (Bring Your Own Service Account).
# Uncomment the following and replace "your-service-account"
# vertexai.init(service_account="your-service-account")

# Initialize Vertex AI with your CMEK (Customer-Managed Encryption Key).
# Un-comment the following line and replace "your-kms-key"
# vertexai.init(encryption_spec_key_name="your-kms-key")

sft_tuning_job = sft.train(
    source_model="gemini-2.0-flash-001",
    # 1.5 and 2.0 models use the same JSONL format
    train_dataset="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl",
    # The following parameters are optional
    validation_dataset="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_validation_data.jsonl",
    tuned_model_display_name="tuned_gemini_2_0_flash",
    # Advanced use only below. It is recommended to use auto-selection and leave them unset
    # epochs=4,
    # adapter_size=4,
    # learning_rate_multiplier=1.0,
)

# 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 产品的代码示例,请参阅Google Cloud 示例浏览器