针对开放模型的监督式微调和提炼微调

本页面介绍了如何对 Llama 3.1 等开放模型执行监督式微调和蒸馏微调。除非另有说明,否则本页面上的说明同时适用于监督微调和蒸馏微调。通过蒸馏,您可以使用较大教师模型的输出内容来调整较小的学生模型。

支持的调优模式

  • 监督式微调
    • 全面微调
    • 低秩自适应 (LoRA):LoRA 是一种参数高效的调优模式,仅调整部分参数。与全面微调相比,它的成本效益更高,所需的训练数据更少。另一方面,通过调整所有参数,全面微调有可能达到更高的质量。
  • 蒸馏微调:蒸馏微调使用 GenAI SDK,您可以在其中指定教师模型来生成回答,然后使用这些回答来调优较小的学生模型。

推荐的知识蒸馏微调应用场景

当教师模型在目标任务上的能力远超学生模型时,蒸馏微调最为有效。建议用于将复杂的多步推理能力从较大的教师模型转移到较小的学生模型,包括:

  • 数学和定量推理
  • 需要逐步推理的科学、医学和其他领域特定的问答
  • 在其他任务中,具有“思考”或思维链行为的强大教师模型始终能生成比学生模型质量更高的回答。

如果学生模型的性能已接近教师模型,或者在教师模型的推理轨迹无法增加价值的短格式检索任务中,知识蒸馏带来的增益较小。

支持的模型

支持监督式微调的模型

  • Gemma 4 E2B IT (google/gemma4@gemma-4-e2b-it)
  • Gemma 4 E4B IT (google/gemma4@gemma-4-e4b-it)
  • Gemma 4 26B A4B IT (google/gemma4@gemma-4-26b-a4b-it)
  • Gemma 4 31B IT (google/gemma4@gemma-4-31b-it)
  • Gemma 3 1B IT (google/gemma3@gemma-3-1b-it)
  • Gemma 3 4B IT (google/gemma3@gemma-3-4b-it)
  • Gemma 3 12B IT (google/gemma3@gemma-3-12b-it)
  • Gemma 3 27B IT (google/gemma3@gemma-3-27b-it)
  • Medgemma 1.5 4B IT (google/medgemma@medgemma-4b-it)
  • Qwen 3.5 9B (qwen/qwen3-5@qwen3.5-9b)
  • Qwen 3 4B (qwen/qwen3@qwen3-4b)
  • Qwen 3 8B (qwen/qwen3@qwen3-8b)
  • Qwen 3 14B (qwen/qwen3@qwen3-14b)
  • Qwen 3 32B (qwen/qwen3@qwen3-32b)
  • Llama 3.1 8B (meta/llama3_1@llama-3.1-8b)
  • Llama 3.1 8B Instruct (meta/llama3_1@llama-3.1-8b-instruct)
  • Llama 3.2 1B Instruct (meta/llama3-2@llama-3.2-1b-instruct)
  • Llama 3.2 3B Instruct (meta/llama3-2@llama-3.2-3b-instruct)
  • Llama 3.3 70B Instruct (meta/llama3-3@llama-3.3-70b-instruct)
  • Llama 4 Scout 17B 16E Instruct (meta/llama4@llama-4-scout-17b-16e-instruct)

支持提炼调优的模型

支持的教师模型:

  • DeepSeek R1 0528 MaaS (deepseek-ai/deepseek-r1-0528-maas)
  • DeepSeek V3.2 MaaS (deepseek-ai/deepseek-v3.2-maas)
  • Qwen 3 Next 80B A3B Thinking MaaS (qwen/qwen3-next-80b-a3b-thinking-maas)

支持的学生模型:

  • Qwen 3 4B (qwen/qwen3@qwen3-4b)
  • Qwen 3 8B (qwen/qwen3@qwen3-8b)
  • Qwen 3 14B (qwen/qwen3@qwen3-14b)
  • Qwen 3 32B (qwen/qwen3@qwen3-32b)
  • Gemma 3 1B IT (google/gemma3@gemma-3-1b-it)
  • Gemma 3 4B IT (google/gemma3@gemma-3-4b-it)
  • Gemma 3 12B IT (google/gemma3@gemma-3-12b-it)
  • Gemma 3 27B IT (google/gemma3@gemma-3-27b-it)

支持的区域

强烈建议使用全局端点 (global) 启动调优作业;它会选择一个具有可用容量的受支持区域,然后启动调优作业。 从全局端点启动作业时,请注意以下事项:

  • 创建全局调优作业时,系统会创建相应的区域调优作业(位于所选区域中)。您只需支付配额费用,并且只需为单个调参作业支付费用。
  • 子资源(例如 TensorBoard 实验或模型)将在所选的目标区域中创建。位置信息可以从完整资源名称中提取,并使用 Vertex AI SDK 进行查询。

对于有更高级需求(例如所有资源都限定在单个区域)的用户,仍可使用特定于区域的调优作业:

  • 爱荷华 (us-central1)
  • 荷兰 (europe-west4)
  • 俄勒冈 (us-west1)
  • 哥伦布 (us-east5)
  • 新加坡 (asia-southeast1)

限制

型号 规范
Gemma 4 E2B IT 调优模式 参数高效微调
序列长度上限 8192
模态 文本
Gemma 4 E4B IT 调优模式 参数高效微调
序列长度上限 8192
模态 文本
Gemma 4 26B A4B IT 调优模式 参数高效微调
序列长度上限 8192
模态 文本
Gemma 4 31B IT 调优模式 参数高效微调
序列长度上限 8192
模态 文本
Gemma 3 1B IT 调优模式 全面微调
序列长度上限 8192
模态 文本
Gemma 3 4B IT 调优模式 全面微调
序列长度上限 8192
模态 文本
Gemma 3 12B IT 调优模式 全面微调
序列长度上限 8192
模态 文本
Gemma 3 27B IT 调优模式 参数高效微调
完全微调
序列长度上限 8192
模态 文本
Medgemma 1.5 4B IT 调优模式 全面微调
序列长度上限 8192
模态 文本
Qwen 3.5 9B 调优模式 参数高效微调
完全微调
序列长度上限 8192
模态 文本
Qwen 3 4B 调优模式 全面微调
序列长度上限 8192
模态 文本
Qwen 3 8B 调优模式 全面微调
序列长度上限 8192
模态 文本
Qwen 3 14B 调优模式 全面微调
序列长度上限 8192
模态 文本
Qwen 3 32B 调优模式 参数高效微调
完全微调
序列长度上限 8192
模态 文本
Llama 3.1 8B 调优模式 参数高效微调
完全微调
序列长度上限 8192
模态 文本
Llama 3.1 8B Instruct 调优模式 参数高效微调
完全微调
序列长度上限 8192
模态 文本
Llama 3.2 1B Instruct 调优模式 全面微调
序列长度上限 8192
模态 文本
Llama 3.2 3B Instruct 调优模式 全面微调
序列长度上限 8192
模态 文本
Llama 3.3 70B Instruct 调优模式 参数高效微调
完全微调
序列长度上限 8192
模态 文本
Llama 4 Scout 17B 16E Instruct 调优模式 参数高效微调
序列长度上限 2048
模态 文本
图片*

*不支持同时包含纯文本样本和图片样本的混合数据集。如果数据集中存在至少一个图片样本,则所有纯文本样本都将被滤除。

准备工作

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the Gemini Enterprise Agent Platform and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

安装 SDK 并导入用于微调方法的库。

监督式微调

安装并初始化 Vertex AI SDK for Python,然后导入以下库:

import os
import time
import uuid
import vertexai

vertexai.init(project=PROJECT_ID, location=REGION)

from google.cloud import aiplatform
from vertexai.tuning import sft, SourceModel

蒸馏调优

安装以下 SDK:

pip install google-genai

然后,导入以下库:

import os
import time
import uuid

from google import genai
from google.genai import types
client = genai.Client(vertexai=True, project=PROJECT_ID, location=REGION)

准备用于调优的数据集

调优需要训练数据集。如果您想评估调优模型的性能,建议准备一个可选的验证数据集。

您的数据集必须采用以下受支持的 JSON 行 (JSONL) 格式之一,其中每行包含一个调优示例。

将 JSONL 文件上传到 Cloud Storage。

纯文本数据集

提示完成

{"prompt": "<prompt text>", "completion": "<ideal generated text>"}

基于回合的聊天格式

{"messages": [
  {"content": "You are a chatbot that helps with scientific literature and generates state-of-the-art abstracts from articles.",
    "role": "system"},
  {"content": "Summarize the paper in one paragraph.",
    "role": "user"},
  {"content": " Here is a one paragraph summary of the paper:\n\nThe paper describes PaLM, ...",
    "role": "assistant"}
]}

GenerateContent

{
"systemInstruction": {
  "parts": [{ "text": "You are a chatbot that helps with scientific literature and generates state-of-the-art abstracts from articles." }]},
"contents": [
  {"role": "user",
    "parts": [{ "text": "Summarize the paper in one paragraph." }]},
  {"role": "assistant",
    "parts": [{ "text": "Here is a one paragraph summary of the paper:\n\nThe paper describes PaLM, ..." }]}
]}

多模态数据集

基于回合的聊天格式

{"messages": [
  {"role": "user", "content": [
    {"type": "text", "text": "You are a chatbot that helps with scientific literature and generates state-of-the-art abstracts from articles."},
    {"type": "image_url", "image_url": {
      "url": "gs://your-gcs-bucket/your-image.jpeg",
      "detail": "low"}}]
  },
  {"role": "assistant", "content": [
    {"type": "text", "text": "Here is a one paragraph summary of the paper:\n\nThe paper describes PaLM, ..."}]
  },
  {"role": "user", "content": [
    {"type": "text", "text": "You are a chatbot that helps with scientific literature and generates state-of-the-art abstracts from articles."},
    {"type": "image_url", "image_url": {
      "url": "data:image/jpeg;base64,<base64 image>",
      "detail": "low"}}]
  },
  {"role": "assistant", "content": [
    {"type": "text", "text": "Here is a one paragraph summary of the paper:\n\nThe paper describes PaLM, ..."}]
  },
]}

GenerateContent

{
"systemInstruction": {
  "parts": [{ "text": "You are a chatbot that helps with scientific literature and generates state-of-the-art abstracts from articles." }]},
"contents": [
  {"role": "user",
    "parts": [
      {"text": "You are a chatbot that helps with scientific literature and generates state-of-the-art abstracts from articles." },
      {"file_data": {
        "mime_type": "image/jpeg", "file_uri": "gs://your-gcs-bucket/your-image.jpeg"}}]
  },
  {"role": "assistant",
    "parts": [{ "text": "Here is a one paragraph summary of the paper:\n\nThe paper describes PaLM, ..." }]}
]}

支持的格式包括 JPEG、PNG、WEBP 和 Base64 编码的图片。

请注意,如果您的图片存储在与 JSONL 文件不同的 Cloud Storage 存储桶中,请确保您已向以下两个服务账号授予这两个存储分区的 Storage Object User (roles/storage.objectUser) IAM 角色:

  • service-PROJECT_NUMBER@gcp-sa-vertex-moss-ft.
  • service-PROJECT_NUMBER@gcp-sa-aiplatform.

创建调优作业

您可以通过以下来源调优:

  • 受支持的基础模型,例如 Llama 3.1
  • 与支持的基础模型之一具有相同架构的模型。 这可以是来自 Hugging Face 等代码库的自定义模型检查点,也可以是来自 Gemini Enterprise Agent Platform 调优作业的之前调优的模型。这样,您就可以继续对已调优的模型进行调优。

Cloud 控制台(受监督)

  1. 您可以通过以下方式启动微调:

    • 前往模型卡片,点击微调,然后选择托管式调优

    前往 Llama 3.1 模型卡片

    • 前往调优页面,然后点击创建调优的模型

    前往“调优”

  2. 填写参数,然后点击开始调优

这会启动一个调优作业,您可以在“调优”页面中的托管式调优标签页下看到该作业。

调优作业完成后,您可以在详细信息标签页中查看有关调优的模型的信息。

Agent Platform SDK(监督型)

将参数值替换为您自己的值,然后运行以下代码以创建调优作业:

sft_tuning_job = sft.train(
    source_model=SourceModel(
      base_model="meta/llama3_1@llama-3.1-8b",
      # Optional, folder that is either a custom model checkpoint or previously tuned model
      custom_base_model="gs://{STORAGE-URI}",
    ),
    tuning_mode="FULL", # FULL or PEFT_ADAPTER
    epochs=3,
    train_dataset="gs://{STORAGE-URI}", # JSONL file
    validation_dataset="gs://{STORAGE-URI}", # JSONL file
    output_uri="gs://{STORAGE-URI}",
)

GenAI SDK(精简版)

将参数值替换为您自己的值,然后运行以下代码以创建蒸馏调优作业:

tuning_job = client.tunings.tune(
    base_model="qwen/qwen3@qwen3-4b",
    training_dataset=types.TuningDataset(
        gcs_uri="gs://{STORAGE-URI}"
    ),
    config=types.CreateTuningJobConfig(
        method="DISTILLATION",
        base_teacher_model="qwen/qwen3-next-80b-a3b-thinking-maas",
        epoch_count=3,
        validation_dataset=types.TuningValidationDataset(
            gcs_uri="gs://{STORAGE-URI}"
        ),
        output_uri="gs://{STORAGE-URI}",
    ),
)

已调优的模型制品

调优作业完成后,调优的模型的模型制品会存储在您的 Cloud Storage 输出目录中。

gs://<output_dir>/
    # (Distillation tuning only) The labeled dataset from teacher model's inference
    -> distillation_labelled_dataset.jsonl

gs://<output_dir>/postprocess/node-0/checkpoints/
    # Final checkpoint
    -> final/
        -> model-00001-of-000xx.safetensors
        -> model-000yy-of-000xx.safetensors

    # Intermediate checkpoints
    -> checkpoint-M/
        -> model-00001-of-000xx.safetensors
        -> model-000yy-of-000xx.safetensors
        -> checkpoint-N/
        -> model-00001-of-000xx.safetensors
        -> model-000yy-of-000xx.safetensors
  • 最多可存储 10 个检查点。
  • 如果周期数 (E) 小于 10,则系统会存储 E 个检查点(每个周期一个)。
  • 范围从 M 到 N 的中间检查点是有序的。请注意,中间检查点并不总是按顺序编号。例如,检查点可能编号为 1、3、5、10,而不是 1、2、3、4。

部署调优的模型

您可以将调整后的模型部署到 Gemini Enterprise Agent Platform 端点。您还可以从 Cloud Storage 导出调优的模型,并将其部署到其他位置。

如需将调优的模型部署到 Gemini Enterprise Agent Platform 端点,请执行以下操作:

Cloud Console

  1. 前往 Model Garden 页面,然后点击部署具有自定义权重的模型

    转到 Model Garden

  2. 填写参数,然后点击部署

Agent Platform SDK for Python

使用预构建容器部署 G2 machine

from vertexai.preview import model_garden

MODEL_ARTIFACTS_STORAGE_URI = "gs://{STORAGE-URI}/postprocess/node-0/checkpoints/final"

model = model_garden.CustomModel(
    gcs_uri=MODEL_ARTIFACTS_STORAGE_URI,
)

# deploy the model to an endpoint using GPUs. Cost will incur for the deployment
endpoint = model.deploy(
  machine_type="g2-standard-12",
  accelerator_type="NVIDIA_L4",
  accelerator_count=1,
)

获取推理

成功部署后,您就可以向端点发送包含文本提示的请求。请注意,前几个提示需要更长时间才能执行完毕。

# Loads the deployed endpoint
endpoint = aiplatform.Endpoint("projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint_name}")

prompt = "Summarize the following article. Article: Preparing a perfect risotto requires patience and attention to detail. Begin by heating butter in a large, heavy-bottomed pot over medium heat. Add finely chopped onions and minced garlic to the pot, and cook until they're soft and translucent, about 5 minutes. Next, add Arborio rice to the pot and cook, stirring constantly, until the grains are coated with the butter and begin to toast slightly. Pour in a splash of white wine and cook until it's absorbed. From there, gradually add hot chicken or vegetable broth to the rice, stirring frequently, until the risotto is creamy and the rice is tender with a slight bite.. Summary:"

# Define input to the prediction call
instances = [
    {
        "prompt": "What is a car?",
        "max_tokens": 200,
        "temperature": 1.0,
        "top_p": 1.0,
        "top_k": 1,
        "raw_response": True,
    },
]

# Request the prediction
response = endpoint.predict(
    instances=instances
)

for prediction in response.predictions:
    print(prediction)

如需详细了解如何从已部署的模型获取推理结果,请参阅获取在线推理结果

请注意,托管式开放模型使用 chat.completions 方法,而不是已部署模型使用的 predict 方法。如需详细了解如何从托管式模型获取推理,请参阅调用 Llama 模型

限制和配额

系统对并发调优作业的数量实施配额。每个项目都配有运行至少一个调优作业的默认配额。这是一个全球配额,所有可用区域和支持的模型共用这一配额。如果要同时运行更多作业,则需要为 Global concurrent managed OSS model fine-tuning jobs per project 申请更多配额

除了调优作业配额外,知识蒸馏微调还会使用教师模型,因此您的项目必须具有足够的配额来支持指定的教师模型。以服务 (MaaS) 形式提供的开放模型使用动态共享配额。当调优作业调用教师模型时,它会使用该模型的项目共享配额。如需详细了解托管式开放模型的配额,请参阅 Gemini Enterprise Agent Platform 托管式 MaaS 模型

价格

您需要根据模型调优价格支付调优费用。训练 token 数的计算方式如下:训练数据集中的 token 数乘以周期数。对于蒸馏调优,您还需要根据受管模型的价格支付向教师模型发出的用于生成回答的 API 调用费用。

您还需要为相关服务(例如 Cloud Storage 和 Gemini Enterprise Agent Platform Prediction)付费。

了解 Gemini Enterprise Agent Platform 价格Cloud Storage 价格,并使用价格计算器根据预计使用量来生成估算的费用。

后续步骤