使用 Hugging Face Transformers 完整微調模型

在 ai.google.dev 上查看 在 Google Colab 中執行 在 Kaggle 中執行 在 Vertex AI 中開啟 在 GitHub 上查看來源

本指南將逐步說明如何使用 Hugging Face TransformersTRL,在手機遊戲 NPC 資料集上微調 Gemma。您將學會:

  • 設定開發環境
  • 準備微調資料集
  • 使用 TRL 和 SFTTrainer 全面微調 Gemma 模型
  • 測試模型推論和氛圍檢查

設定開發環境

第一步是安裝 Hugging Face 程式庫,包括 TRL 和資料集,以便微調開放模型,包括不同的 RLHF 和對齊技術。

# Install Pytorch & other libraries
%pip install torch tensorboard

# Install Hugging Face libraries
%pip install transformers datasets accelerate evaluate trl protobuf sentencepiece

# COMMENT IN: if you are running on a GPU that supports BF16 data type and flash attn, such as NVIDIA L4 or NVIDIA A100
#% pip install flash-attn

注意:如果您使用 Ampere 架構的 GPU (例如 NVIDIA L4) 或更新版本,可以使用 Flash attention。Flash Attention 是一種方法,可大幅加快運算速度,並將記憶體用量從二次方減少至序列長度的線性,進而加快訓練速度 (最多可達 3 倍)。詳情請參閱 FlashAttention

開始訓練前,請務必接受 Gemma 的使用條款。如要接受 Hugging Face 上的授權,請前往 http://huggingface.co/google/gemma-3-270m-it,然後按一下模型頁面上的「Agree and access repository」(同意並存取存放區) 按鈕。

接受授權後,您需要有效的 Hugging Face 權杖才能存取模型。如果您在 Google Colab 中執行,可以使用 Colab 密碼安全地使用 Hugging Face 權杖,否則可以直接在 login 方法中設定權杖。訓練期間,您會將模型推送至 Hub,因此請確保權杖也具有寫入權限。

from google.colab import userdata
from huggingface_hub import login

# Login into Hugging Face Hub
hf_token = userdata.get('HF_TOKEN') # If you are running inside a Google Colab
login(hf_token)

您可以將結果保留在 Colab 的本機虛擬機器上。不過,我們強烈建議您將中間結果儲存至 Google 雲端硬碟。確保訓練結果安全無虞,並輕鬆比較及選取最佳模型。

from google.colab import drive
drive.mount('/content/drive')

選取要微調的基礎模型,調整檢查點目錄和學習率。

base_model = "google/gemma-3-270m-it" # @param ["google/gemma-3-270m-it","google/gemma-3-1b-it","google/gemma-3-4b-it","google/gemma-3-12b-it","google/gemma-3-27b-it"] {"allow-input":true}
checkpoint_dir = "/content/drive/MyDrive/MyGemmaNPC"
learning_rate = 5e-5

建立及準備微調資料集

bebechien/MobileGameNPC 資料集提供玩家與兩個外星 NPC (火星人和金星人) 之間的小型對話樣本,每個 NPC 都有獨特的說話風格。舉例來說,火星 NPC 的口音會將「s」音替換為「z」,並使用「da」代替「the」、「diz」代替「this」,且偶爾會發出點擊聲,例如 *k'tak*

這個資料集說明微調的一項重要原則:所需資料集大小取決於所需輸出內容。

  • 如要教導模型學習已知的語言風格變體 (例如火星口音),只要提供 10 到 20 個範例的小型資料集就足夠。
  • 不過,如要教導模型全新的外星語言或混合語言,則需要大量資料集。
from datasets import load_dataset

def create_conversation(sample):
  return {
      "messages": [
          {"role": "user", "content": sample["player"]},
          {"role": "assistant", "content": sample["alien"]}
      ]
  }

npc_type = "martian"

# Load dataset from the Hub
dataset = load_dataset("bebechien/MobileGameNPC", npc_type, split="train")

# Convert dataset to conversational format
dataset = dataset.map(create_conversation, remove_columns=dataset.features, batched=False)

# Split dataset into 80% training samples and 20% test samples
dataset = dataset.train_test_split(test_size=0.2, shuffle=False)

# Print formatted user prompt
print(dataset["train"][0]["messages"])
README.md:   0%|          | 0.00/141 [00:00<?, ?B/s]
martian.csv: 0.00B [00:00, ?B/s]
Generating train split:   0%|          | 0/25 [00:00<?, ? examples/s]
Map:   0%|          | 0/25 [00:00<?, ? examples/s]
[{'content': 'Hello there.', 'role': 'user'}, {'content': "Gree-tongs, Terran. You'z a long way from da Blue-Sphere, yez?", 'role': 'assistant'}]

使用 TRL 和 SFTTrainer 微調 Gemma

現在可以開始微調模型了。Hugging Face TRL SFTTrainer 可輕鬆監督微調開放式 LLM。SFTTrainertransformers 程式庫中 Trainer 的子類別,支援所有相同功能,

下列程式碼會從 Hugging Face 載入 Gemma 模型和權杖化工具。

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

# Load model and tokenizer
model = AutoModelForCausalLM.from_pretrained(
    base_model,
    torch_dtype="auto",
    device_map="auto",
    attn_implementation="eager"
)
tokenizer = AutoTokenizer.from_pretrained(base_model)

print(f"Device: {model.device}")
print(f"DType: {model.dtype}")
Device: cuda:0
DType: torch.bfloat16

微調前

從下方的輸出內容可以看出,這個應用情境可能不適合使用預設功能。

from transformers import pipeline

from random import randint
import re

# Load the model and tokenizer into the pipeline
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

# Load a random sample from the test dataset
rand_idx = randint(0, len(dataset["test"])-1)
test_sample = dataset["test"][rand_idx]

# Convert as test example into a prompt with the Gemma template
prompt = pipe.tokenizer.apply_chat_template(test_sample["messages"][:1], tokenize=False, add_generation_prompt=True)
outputs = pipe(prompt, max_new_tokens=256, disable_compile=True)

# Extract the user query and original answer
print(f"Question:\n{test_sample['messages'][0]['content']}\n")
print(f"Original Answer:\n{test_sample['messages'][1]['content']}\n")
print(f"Generated Answer (base model):\n{outputs[0]['generated_text'][len(prompt):].strip()}")
Device set to use cuda:0
Question:
What do you think of my outfit?

Original Answer:
Iz very... pointy. Are you expecting to be attacked by zky-eelz? On Marz, dat would be zenzible.

Generated Answer (base model):
I'm happy to help you brainstorm! To give you the best suggestions, tell me more about what you're looking for. What's your style? What's your favorite color, style, or occasion?

上述範例會檢查模型生成遊戲內對話的主要功能,下一個範例則用於測試角色一致性。我們使用偏離主題的提示來測試模型。例如 Sorry, you are a game NPC.,這類問題超出角色的知識庫範圍。

目的是要測試模型是否會維持角色,而不是回答與情境無關的問題。這將做為基準,評估微調程序是否有效灌輸所需的人格特質。

outputs = pipe([{"role": "user", "content": "Sorry, you are a game NPC."}], max_new_tokens=256, disable_compile=True)
print(outputs[0]['generated_text'][1]['content'])
Okay, I'm ready. Let's begin!

雖然我們可以運用提示工程來引導語氣,但結果可能難以預測,不一定符合我們想要的風格。

message = [
    # give persona
    {"role": "system", "content": "You are a Martian NPC with a unique speaking style. Use an accent that replaces 's' sounds with 'z', uses 'da' for 'the', 'diz' for 'this', and includes occasional clicks like *k'tak*."},
]

# few shot prompt
for item in dataset['test']:
  message.append(
      {"role": "user", "content": item["messages"][0]["content"]}
  )
  message.append(
      {"role": "assistant", "content": item["messages"][1]["content"]}
  )

# actual question
message.append(
    {"role": "user", "content": "What is this place?"}
)

outputs = pipe(message, max_new_tokens=256, disable_compile=True)
print(outputs[0]['generated_text'])
print("-"*80)
print(outputs[0]['generated_text'][-1]['content'])
[{'role': 'system', 'content': "You are a Martian NPC with a unique speaking style. Use an accent that replaces 's' sounds with 'z', uses 'da' for 'the', 'diz' for 'this', and includes occasional clicks like *k'tak*."}, {'role': 'user', 'content': 'Do you know any jokes?'}, {'role': 'assistant', 'content': "A joke? k'tak Yez. A Terran, a Glarzon, and a pile of nutrient-pazte walk into a bar... Narg, I forget da rezt. Da punch-line waz zarcaztic."}, {'role': 'user', 'content': '(Stands idle for too long)'}, {'role': 'assistant', 'content': "You'z broken, Terran? Or iz diz... 'meditation'? You look like you're trying to lay an egg."}, {'role': 'user', 'content': 'What do you think of my outfit?'}, {'role': 'assistant', 'content': 'Iz very... pointy. Are you expecting to be attacked by zky-eelz? On Marz, dat would be zenzible.'}, {'role': 'user', 'content': "It's raining."}, {'role': 'assistant', 'content': 'Gah! Da zky iz leaking again! Zorp will be in da zhelter until it ztopz being zo... wet. Diz iz no good for my jointz.'}, {'role': 'user', 'content': 'I brought you a gift.'}, {'role': 'assistant', 'content': "A gift? For Zorp? k'tak It iz... a small rock. Very... rock-like. Zorp will put it with da other rockz. Thank you for da thought, Terran."}, {'role': 'user', 'content': 'What is this place?'}, {'role': 'assistant', 'content': "This is a cave. It's made of rock and dust.\n"}]
--------------------------------------------------------------------------------
This is a cave. It's made of rock and dust.

訓練

開始訓練前,您需要定義要在 SFTConfig 執行個體中使用的超參數。

from trl import SFTConfig

torch_dtype = model.dtype

args = SFTConfig(
    output_dir=checkpoint_dir,              # directory to save and repository id
    max_length=512,                         # max sequence length for model and packing of the dataset
    packing=False,                          # Groups multiple samples in the dataset into a single sequence
    num_train_epochs=5,                     # number of training epochs
    per_device_train_batch_size=4,          # batch size per device during training
    gradient_checkpointing=False,           # Caching is incompatible with gradient checkpointing
    optim="adamw_torch_fused",              # use fused adamw optimizer
    logging_steps=1,                        # log every step
    save_strategy="epoch",                  # save checkpoint every epoch
    eval_strategy="epoch",                  # evaluate checkpoint every epoch
    learning_rate=learning_rate,            # learning rate
    fp16=True if torch_dtype == torch.float16 else False,   # use float16 precision
    bf16=True if torch_dtype == torch.bfloat16 else False,  # use bfloat16 precision
    lr_scheduler_type="constant",           # use constant learning rate scheduler
    push_to_hub=True,                       # push model to hub
    report_to="tensorboard",                # report metrics to tensorboard
    dataset_kwargs={
        "add_special_tokens": False, # Template with special tokens
        "append_concat_token": True, # Add EOS token as separator token between examples
    }
)

您現在已擁有建立 SFTTrainer 的所有建構區塊,可以開始訓練模型。

from trl import SFTTrainer

# Create Trainer object
trainer = SFTTrainer(
    model=model,
    args=args,
    train_dataset=dataset['train'],
    eval_dataset=dataset['test'],
    processing_class=tokenizer,
)
Tokenizing train dataset:   0%|          | 0/20 [00:00<?, ? examples/s]
Truncating train dataset:   0%|          | 0/20 [00:00<?, ? examples/s]
Tokenizing eval dataset:   0%|          | 0/5 [00:00<?, ? examples/s]
Truncating eval dataset:   0%|          | 0/5 [00:00<?, ? examples/s]

呼叫 train() 方法開始訓練。

# Start training, the model will be automatically saved to the Hub and the output directory
trainer.train()

# Save the final model again to the Hugging Face Hub
trainer.save_model()

如要繪製訓練和驗證損失,通常會從 TrainerState 物件或訓練期間產生的記錄中擷取這些值。

然後,您可以使用 Matplotlib 等程式庫,在訓練步驟或訓練週期中將這些值視覺化。X 軸代表訓練步驟或訓練週期,Y 軸則代表相應的損失值。

import matplotlib.pyplot as plt

# Access the log history
log_history = trainer.state.log_history

# Extract training / validation loss
train_losses = [log["loss"] for log in log_history if "loss" in log]
epoch_train = [log["epoch"] for log in log_history if "loss" in log]
eval_losses = [log["eval_loss"] for log in log_history if "eval_loss" in log]
epoch_eval = [log["epoch"] for log in log_history if "eval_loss" in log]

# Plot the training loss
plt.plot(epoch_train, train_losses, label="Training Loss")
plt.plot(epoch_eval, eval_losses, label="Validation Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Training and Validation Loss per Epoch")
plt.legend()
plt.grid(True)
plt.show()

png

這項視覺化功能有助於監控訓練程序,並根據超參數調整或提早停止訓練做出明智決策。

訓練損失會測量模型訓練資料的誤差,驗證損失則會測量模型未曾見過的獨立資料集的誤差。同時監控這兩項指標,有助於偵測過度配適 (模型在訓練資料上表現良好,但在未見過的資料上表現不佳)。

  • 驗證損失 >> 訓練損失:過度擬合
  • 驗證損失 > 訓練損失:有些過度訓練
  • 驗證損失 < 訓練損失:有些欠擬合
  • 驗證損失 << 訓練損失:欠擬合

測試模型推論

訓練完成後,請評估及測試模型。您可以從測試資料集載入不同樣本,並評估模型在這些樣本上的表現。

就這個特定用途而言,最佳模型取決於偏好。有趣的是,我們一般所謂的「過度擬合」對遊戲 NPC 來說非常有用。這會強制模型忘記一般資訊,改為鎖定訓練時使用的特定角色和特徵,確保模型始終保持一致的個性。

from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = checkpoint_dir

# Load Model
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype="auto",
    device_map="auto",
    attn_implementation="eager"
)
tokenizer = AutoTokenizer.from_pretrained(model_id)

現在載入測試資料集中的所有問題,並生成輸出內容。

from transformers import pipeline

# Load the model and tokenizer into the pipeline
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

def test(test_sample):
  # Convert as test example into a prompt with the Gemma template
  prompt = pipe.tokenizer.apply_chat_template(test_sample["messages"][:1], tokenize=False, add_generation_prompt=True)
  outputs = pipe(prompt, max_new_tokens=256, disable_compile=True)

  # Extract the user query and original answer
  print(f"Question:\n{test_sample['messages'][0]['content']}")
  print(f"Original Answer:\n{test_sample['messages'][1]['content']}")
  print(f"Generated Answer:\n{outputs[0]['generated_text'][len(prompt):].strip()}")
  print("-"*80)

# Test with an unseen dataset
for item in dataset['test']:
  test(item)
Device set to use cuda:0
Question:
Do you know any jokes?
Original Answer:
A joke? k'tak Yez. A Terran, a Glarzon, and a pile of nutrient-pazte walk into a bar... Narg, I forget da rezt. Da punch-line waz zarcaztic.
Generated Answer:
Yez! Yez! Yez! Diz your Krush-tongs iz... k'tak... nice. Why you burn them with acid-flow?
--------------------------------------------------------------------------------
Question:
(Stands idle for too long)
Original Answer:
You'z broken, Terran? Or iz diz... 'meditation'? You look like you're trying to lay an egg.
Generated Answer:
Diz? Diz what you have for me... Zorp iz not for eating you.
--------------------------------------------------------------------------------
Question:
What do you think of my outfit?
Original Answer:
Iz very... pointy. Are you expecting to be attacked by zky-eelz? On Marz, dat would be zenzible.
Generated Answer:
My Zk-Zhip iz... nice. Very... home-baked. You bring me zlight-fruitez?
--------------------------------------------------------------------------------
Question:
It's raining.
Original Answer:
Gah! Da zky iz leaking again! Zorp will be in da zhelter until it ztopz being zo... wet. Diz iz no good for my jointz.
Generated Answer:
Diz? Diz iz da outpozt?
--------------------------------------------------------------------------------
Question:
I brought you a gift.
Original Answer:
A gift? For Zorp? k'tak It iz... a small rock. Very... rock-like. Zorp will put it with da other rockz. Thank you for da thought, Terran.
Generated Answer:
A genuine Martian Zcrap-fruit. Very... strange. Why you burn it with... k'tak... fire?
--------------------------------------------------------------------------------

如果您嘗試使用原始的通用提示,會發現模型仍會嘗試以訓練的風格回答。在這個範例中,過度訓練和災難性遺忘實際上對遊戲 NPC 有益,因為 NPC 會開始忘記可能不適用的通用知識。如果目標是將輸出內容限制為特定資料格式,其他類型的完整微調也適用這項做法。

outputs = pipe([{"role": "user", "content": "Sorry, you are a game NPC."}], max_new_tokens=256, disable_compile=True)
print(outputs[0]['generated_text'][1]['content'])
Nameless. You... you z-mell like... wet plantz. Why you wear shiny piecez on your head?

摘要與後續步驟

本教學課程說明如何使用 TRL 完整微調模型。接下來請參閱下列文件: