שיפור של Gemma באמצעות Hugging Face Transformers ו-QloRA

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

במדריך הזה נסביר איך לבצע כוונון עדין של Gemma במערך נתונים מותאם אישית של טקסט ל-SQL באמצעות Transformers ו-TRL של Hugging Face. תלמדו:

  • מה זה Quantized Low-Rank Adaptation‏ (QLoRA)
  • הגדרת סביבת פיתוח
  • יצירה והכנה של מערך הנתונים לכוונון עדין
  • ביצוע התאמה עדינה של Gemma באמצעות TRL ו-SFTTrainer
  • בדיקת הסקת המודל ויצירת שאילתות SQL

מה זה Quantized Low-Rank Adaptation‏ (QLoRA)

במדריך הזה נדגים את השימוש ב-Quantized Low-Rank Adaptation (QLoRA), שיטה פופולרית לביצוע כוונון עדין יעיל של מודלים של שפה גדולים (LLM), כי היא מצמצמת את הדרישות למשאבי מחשוב תוך שמירה על ביצועים גבוהים. ב-QloRA, המודל שעבר אימון מראש עובר קוונטיזציה ל-4 ביט והמשקלים קפואים. לאחר מכן מצורפות שכבות מתאם שניתנות לאימון (LoRA) ורק שכבות המתאם עוברות אימון. לאחר מכן, אפשר למזג את משקלי המתאם עם מודל הבסיס או לשמור אותם כמתאם נפרד.

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

השלב הראשון הוא להתקין את ספריות Hugging Face, כולל TRL וערכות נתונים, כדי לבצע כוונון עדין של מודל פתוח, כולל טכניקות שונות של RLHF ויישור.

# Install Pytorch & other libraries
%pip install torch tensorboard

# Install Transformers
%pip install transformers

# Install Hugging Face libraries
%pip install datasets accelerate evaluate bitsandbytes trl peft 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 עם ארכיטקטורת Ampere (כמו NVIDIA L4) או חדשה יותר, אתם יכולים להשתמש ב-Flash attention. Flash Attention היא שיטה שמאיצה משמעותית את החישובים ומפחיתה את השימוש בזיכרון מריבועי ללינארי באורך הרצף, וכך מאפשרת להאיץ את האימון עד פי 3. מידע נוסף זמין במאמר בנושא FlashAttention.

כדי לפרסם את המודל, צריך טוקן תקף של Hugging Face. אם אתם מריצים את הקוד ב-Google Colab, אתם יכולים להשתמש באסימון Hugging Face באופן מאובטח באמצעות הסודות של Colab. אחרת, אתם יכולים להגדיר את האסימון ישירות בשיטה login. חשוב לוודא שלטוקן יש גם הרשאת כתיבה, כי המודל נדחף אל Hub במהלך האימון.

# Login into Hugging Face Hub
from huggingface_hub import login
login()

יצירה והכנה של מערך הנתונים לכוונון עדין

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

לדוגמה, במדריך הזה אנחנו מתמקדים בתרחיש השימוש הבא:

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

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

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

  • שימוש במערכי נתונים קיימים של קוד פתוח, כמו Spider
  • שימוש במערכי נתונים סינתטיים שנוצרו על ידי מודלים של שפה גדולה (LLM), כמו Alpaca
  • שימוש במערכי נתונים שנוצרו על ידי בני אדם, כמו Dolly.
  • שימוש בשילוב של השיטות, כמו Orca

לכל אחת מהשיטות יש יתרונות וחסרונות משלה, והבחירה ביניהן תלויה בתקציב, בזמן ובדרישות האיכות. לדוגמה, השימוש במערך נתונים קיים הוא הכי קל, אבל יכול להיות שהוא לא יתאים לתרחיש השימוש הספציפי שלכם. לעומת זאת, שימוש במומחים בתחום יכול להיות הכי מדויק, אבל הוא עלול להיות יקר ולדרוש זמן רב. אפשר גם לשלב כמה שיטות כדי ליצור מערך נתונים של הוראות, כמו שמוצג במאמר Orca: Progressive Learning from Complex Explanation Traces of GPT-4.

במדריך הזה נעשה שימוש במערך נתונים שכבר קיים (philschmid/gretel-synthetic-text-to-sql), מערך נתונים סינתטי באיכות גבוהה של Text-to-SQL, כולל הוראות בשפה טבעית, הגדרות סכימה, נימוקים ושאילתת ה-SQL המתאימה.

Hugging Face TRL תומך ביצירת תבניות אוטומטית של פורמטים של מערכי נתונים של שיחות. כלומר, אתם צריכים רק להמיר את מערך הנתונים לאובייקטים הנכונים של JSON, ו-trl דואג ליצירת תבניות ולהצבת הנתונים בפורמט הנכון.

{"messages": [{"role": "system", "content": "You are..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
{"messages": [{"role": "system", "content": "You are..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
{"messages": [{"role": "system", "content": "You are..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}

המאגר philschmid/gretel-synthetic-text-to-sql מכיל יותר מ-100,000 דוגמאות. כדי שהמדריך יהיה קטן, הוא עובר דגימת חסר כדי להשתמש רק ב-10,000 דוגמאות.

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

from datasets import load_dataset

# System message for the assistant
system_message = """You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA."""

# User prompt that combines the user query and the schema
user_prompt = """Given the <USER_QUERY> and the <SCHEMA>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints.

<SCHEMA>
{context}
</SCHEMA>

<USER_QUERY>
{question}
</USER_QUERY>
"""
def create_conversation(sample):
  return {
    "messages": [
      {"role": "system", "content": system_message},
      {"role": "user", "content": user_prompt.format(question=sample["sql_prompt"], context=sample["sql_context"])},
      {"role": "assistant", "content": sample["sql"]}
    ]
  }

# Load dataset from the hub
dataset = load_dataset("philschmid/gretel-synthetic-text-to-sql", split="train")
dataset = dataset.shuffle().select(range(12500))

# Convert dataset to OAI messages
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)

# Print formatted user prompt
for item in dataset["train"][0]["messages"]:
  print(item)
README.md:   0%|          | 0.00/737 [00:00<?, ?B/s]
synthetic_text_to_sql_train.snappy.parqu(…):   0%|          | 0.00/32.4M [00:00<?, ?B/s]
synthetic_text_to_sql_test.snappy.parque(…):   0%|          | 0.00/1.90M [00:00<?, ?B/s]
Generating train split:   0%|          | 0/100000 [00:00<?, ? examples/s]
Generating test split:   0%|          | 0/5851 [00:00<?, ? examples/s]
Map:   0%|          | 0/12500 [00:00<?, ? examples/s]
{'content': 'You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA.', 'role': 'system'}
{'content': "Given the <USER_QUERY> and the <SCHEMA>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints.\n\n<SCHEMA>\nCREATE TABLE Menu (id INT PRIMARY KEY, name VARCHAR(255), category VARCHAR(255), price DECIMAL(5,2));\n</SCHEMA>\n\n<USER_QUERY>\nCalculate the average price of all menu items in the Vegan category\n</USER_QUERY>\n", 'role': 'user'}
{'content': "SELECT AVG(price) FROM Menu WHERE category = 'Vegan';", 'role': 'assistant'}

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

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

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

הקוד הבא טוען את מודל Gemma ואת ה-tokenizer מ-Hugging Face ומפעיל את הגדרת הכימות.

import torch
from transformers import AutoTokenizer, AutoModelForImageTextToText, BitsAndBytesConfig

# Hugging Face model id
model_id = "google/gemma-4-E2B" # @param ["google/gemma-4-E2B","google/gemma-4-E4B"] {"allow-input":true}

# Check if GPU benefits from bfloat16
if torch.cuda.get_device_capability()[0] >= 8:
    torch_dtype = torch.bfloat16
else:
    torch_dtype = torch.float16

# Define model init arguments
model_kwargs = dict(
    dtype=torch_dtype,
    device_map="auto", # Let torch decide how to load the model
)

# BitsAndBytesConfig: Enables 4-bit quantization to reduce model size/memory usage
model_kwargs["quantization_config"] = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type='nf4',
    bnb_4bit_compute_dtype=model_kwargs['dtype'],
    bnb_4bit_quant_storage=model_kwargs['dtype'],
)

# Load model and tokenizer
model = AutoModelForImageTextToText.from_pretrained(model_id, **model_kwargs)
tokenizer = AutoTokenizer.from_pretrained("google/gemma-4-E2B-it") # Load the Instruction Tokenizer to use the official Gemma template
config.json: 0.00B [00:00, ?B/s]
model.safetensors:   0%|          | 0.00/10.2G [00:00<?, ?B/s]
Loading weights:   0%|          | 0/2011 [00:00<?, ?it/s]
generation_config.json:   0%|          | 0.00/181 [00:00<?, ?B/s]
config.json: 0.00B [00:00, ?B/s]
tokenizer_config.json: 0.00B [00:00, ?B/s]
tokenizer.json:   0%|          | 0.00/32.2M [00:00<?, ?B/s]
chat_template.jinja: 0.00B [00:00, ?B/s]

SFTTrainer תומך בשילוב מובנה עם peft, כך שקל לכוונן ביעילות מודלים גדולים של שפה (LLM) באמצעות QLoRA. צריך ליצור LoraConfig ולספק אותו למדריך.

from peft import LoraConfig

peft_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.05,
    r=16,
    bias="none",
    target_modules="all-linear",
    task_type="CAUSAL_LM",
    modules_to_save=["lm_head", "embed_tokens"], # make sure to save the lm_head and embed_tokens as you train the special tokens
    ensure_weight_tying=True,
)

לפני שמתחילים את האימון, צריך להגדיר את ההיפר-פרמטר שרוצים להשתמש בו במכונה SFTConfig.

import torch
from trl import SFTConfig

args = SFTConfig(
    output_dir="gemma-text-to-sql",         # directory to save and repository id
    max_length=512,                         # max length for model and packing of the dataset
    num_train_epochs=3,                     # number of training epochs
    per_device_train_batch_size=1,          # batch size per device during training
    optim="adamw_torch_fused",              # use fused adamw optimizer
    logging_steps=10,                       # log every 10 steps
    save_strategy="epoch",                  # save checkpoint every epoch
    eval_strategy="epoch",                  # evaluate checkpoint every epoch
    learning_rate=5e-5,                     # learning rate
    fp16=True if model.dtype == torch.float16 else False,   # use float16 precision
    bf16=True if model.dtype == torch.bfloat16 else False,   # use bfloat16 precision
    max_grad_norm=0.3,                      # max gradient norm based on QLoRA paper
    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"],
    peft_config=peft_config,
    processing_class=tokenizer,
)
Tokenizing train dataset:   0%|          | 0/10000 [00:00<?, ? examples/s]
Tokenizing eval dataset:   0%|          | 0/2500 [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()
The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'eos_token_id': 1, 'bos_token_id': 2, 'pad_token_id': 0}.

לפני שבודקים את המודל, חשוב לפנות את הזיכרון.

# free the memory again
del model
del trainer
torch.cuda.empty_cache()

כשמשתמשים ב-QLoRA, מאמנים רק מתאמים ולא את המודל המלא. כלומר, כששומרים את המודל במהלך האימון, שומרים רק את משקלי המתאם ולא את המודל המלא. אם רוצים לשמור את המודל המלא, כדי שיהיה קל יותר להשתמש בו עם מחסניות להצגת מודלים כמו vLLM או TGI, אפשר למזג את משקלי המתאם עם משקלי המודל באמצעות השיטה merge_and_unload ואז לשמור את המודל באמצעות השיטה save_pretrained. הפעולה הזו שומרת מודל ברירת מחדל, שאפשר להשתמש בו להסקת מסקנות.

from peft import PeftModel

# Load Model base model
model = AutoModelForImageTextToText.from_pretrained(model_id, low_cpu_mem_usage=True)

# Merge LoRA and base model and save
peft_model = PeftModel.from_pretrained(model, args.output_dir)
merged_model = peft_model.merge_and_unload()
merged_model.save_pretrained("merged_model", safe_serialization=True, max_shard_size="2GB")

processor = AutoTokenizer.from_pretrained(args.output_dir)
processor.save_pretrained("merged_model")
Loading weights:   0%|          | 0/2011 [00:00<?, ?it/s]
Writing model shards:   0%|          | 0/5 [00:00<?, ?it/s]
('merged_model/tokenizer_config.json',
 'merged_model/chat_template.jinja',
 'merged_model/tokenizer.json')

בדיקת הסקת המודל ויצירת שאילתות SQL

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

import torch
from transformers import pipeline

model_id = "merged_model"

# Load Model with PEFT adapter
model = AutoModelForImageTextToText.from_pretrained(
  model_id,
  device_map="auto",
  dtype="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
Loading weights:   0%|          | 0/2012 [00:00<?, ?it/s]
The tied weights mapping and config for this model specifies to tie model.language_model.embed_tokens.weight to lm_head.weight, but both are present in the checkpoints with different values, so we will NOT tie them. You should update the config with `tie_word_embeddings=False` to silence this warning.

בואו נטען דגימה אקראית ממערך נתוני הבדיקה וניצור פקודת SQL.

from random import randint
import re
from transformers import pipeline, GenerationConfig

config = GenerationConfig.from_pretrained(model_id)
config.max_new_tokens = 256

# 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"]))
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"][:2], tokenize=False, add_generation_prompt=True)
print(prompt)

# Generate our SQL query.
outputs = pipe(prompt, generation_config=config)

# Extract the user query and original answer
print(f"Context:\n", re.search(r'<SCHEMA>\n(.*?)\n</SCHEMA>', test_sample['messages'][1]['content'], re.DOTALL).group(1).strip())
print(f"Query:\n", re.search(r'<USER_QUERY>\n(.*?)\n</USER_QUERY>', test_sample['messages'][1]['content'], re.DOTALL).group(1).strip())
print(f"Original Answer:\n{test_sample['messages'][2]['content']}")
print(f"Generated Answer:\n{outputs[0]['generated_text'][len(prompt):].strip()}")
<bos><|turn>system
You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA.<turn|>
<|turn>user
Given the <USER_QUERY> and the <SCHEMA>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints.

<SCHEMA>
CREATE TABLE broadband_plans (plan_id INT, plan_name VARCHAR(255), download_speed INT, upload_speed INT, price DECIMAL(5,2));
</SCHEMA>

<USER_QUERY>
Delete a broadband plan from the 'broadband_plans' table
</USER_QUERY><turn|>
<|turn>model

Context:
 CREATE TABLE broadband_plans (plan_id INT, plan_name VARCHAR(255), download_speed INT, upload_speed INT, price DECIMAL(5,2));
Query:
 Delete a broadband plan from the 'broadband_plans' table
Original Answer:
DELETE FROM broadband_plans WHERE plan_id = 3001;
Generated Answer:
DELETE FROM broadband_plans
WHERE plan_name = 'Basic';

סיכום והשלבים הבאים

במדריך הזה למדנו איך לשפר ולחדד מודל Gemma באמצעות TRL ו-QLoRA. כדאי לעיין במסמכים הבאים: