כוונון עדין מלא של מודל באמצעות Hugging Face Transformers

לצפייה באתר ai.google.dev הרצה ב-Google Colab הפעלה ב-Kaggle פתיחה ב-Vertex AI צפייה במקור ב-GitHub

במדריך הזה מוסבר איך לשפר ולחדד את Gemma במערך נתונים של דמויות NPC במשחק לנייד באמצעות Transformers ו-TRL של Hugging Face. תלמדו:

  • הגדרת סביבת פיתוח
  • הכנת מערך הנתונים לכוונון עדין
  • כוונון עדין של מודל Gemma מלא באמצעות TRL ו-SFTTrainer
  • בדיקת הסקת מסקנות ממודל ובדיקות אווירה

הגדרת סביבת פיתוח

השלב הראשון הוא להתקין את ספריות 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

הערה: אם אתם משתמשים ב-GPU עם ארכיטקטורת אמפר (כמו NVIDIA L4) או חדשה יותר, אתם יכולים להשתמש ב-Flash attention. Flash Attention היא שיטה שמאיצה משמעותית את החישובים ומפחיתה את השימוש בזיכרון מריבועי ללינארי באורך הרצף, וכך מאפשרת להאיץ את האימון עד פי 3. מידע נוסף זמין במאמר בנושא FlashAttention.

לפני שמתחילים באימון, צריך לוודא שאישרתם את תנאי השימוש ב-Gemma. כדי לאשר את הרישיון ב-Hugging Face, לוחצים על הלחצן Agree and access repository (אישור וגישה למאגר) בדף המודל בכתובת: http://huggingface.co/google/gemma-3-270m-it

אחרי שתאשרו את הרישיון, תצטרכו טוקן תקף של Hugging Face כדי לגשת למודל. אם אתם מריצים את הקוד ב-Google Colab, אתם יכולים להשתמש באסימון של Hugging Face בצורה מאובטחת באמצעות הסודות של Colab. אחרת, אתם יכולים להגדיר את האסימון ישירות בשיטה 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 Drive. כך תוכלו להשוות בקלות בין המודלים ולבחור את המודל הכי טוב.

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 המאדים מדברת במבטא שבו הצליל 'ס' מוחלף ב-'ז', היא משתמשת במילה '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'}]

ביצוע התאמה עדינה של Gemma באמצעות TRL ו-SFTTrainer

עכשיו אפשר לבצע כוונון עדין של המודל. ‫Hugging Face TRL SFTTrainer מאפשר לפקח בקלות על כוונון עדין של מודלים גדולים של שפה (LLM) בקוד פתוח. ‫SFTTrainer הוא מחלקת משנה של Trainer מהספרייה transformers, והוא תומך בכל אותן התכונות.

הקוד הבא טוען את מודל Gemma ואת ה-tokenizer מ-Hugging Face.

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

הוויזואליזציה הזו עוזרת לעקוב אחרי תהליך האימון ולקבל החלטות מושכלות לגבי כוונון של היפרפרמטרים או עצירה מוקדמת.

הפסד האימון מודד את השגיאה בנתונים שהמודל אומן עליהם, בעוד שהפסד האימות מודד את השגיאה במערך נתונים נפרד שהמודל לא ראה לפני כן. המעקב אחרי שניהם עוזר לזהות התאמת יתר (overfitting) (מצב שבו המודל פועל היטב על נתוני האימון אבל לא טוב על נתונים שלא נראו לו).

  • הפסד האימות >> הפסד האימון: התאמת יתר
  • ההפסד של האימות > ההפסד של האימון: התאמת יתר מסוימת
  • ההפסד של האימות < ההפסד של האימון: התאמה חלקית
  • ההפסד של האימות נמוך בהרבה מההפסד של האימון: התאמה חסרה

Test Model Inference

אחרי שהאימון יסתיים, כדאי להעריך ולבדוק את המודל. אפשר לטעון דוגמאות שונות ממערך הנתונים של הבדיקה ולהעריך את המודל על סמך הדוגמאות האלה.

במקרה השימוש הספציפי הזה, המודל הכי טוב הוא עניין של העדפה. מעניין לציין שמה שאנחנו בדרך כלל מכנים 'התאמת יתר' יכול להיות שימושי מאוד עבור דמות 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 במשחק, כי היא תתחיל לשכוח ידע כללי שאולי לא רלוונטי. זה נכון גם לגבי סוגים אחרים של כוונון עדין מלא, שבהם המטרה היא להגביל את הפלט לפורמטים ספציפיים של נתונים.

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. כדאי לעיין במסמכים הבאים: