|
|
[Run in Google Colab]
|
|
|
[GitHub 上のソースを見る]
|
このガイドでは、Hugging Face Transformers と TRL を使用して、カスタムのテキストから SQL へのデータセットで Gemma をファインチューニングする方法について説明します。学習内容:
- Quantized Low-Rank Adaptation(QLoRA)とは
- 開発環境を設定する
- ファインチューニング データセットを作成して準備する
- TRL と SFTTrainer を使用して Gemma をファインチューニングする
- モデル推論をテストして SQL クエリを生成する
Quantized Low-Rank Adaptation(QLoRA)とは
このガイドでは、Quantized Low-Rank Adaptation(QLoRA)の使用方法について説明します。QLoRA は、高いパフォーマンスを維持しながらコンピューティングリソースの要件を削減するため、LLM を効率的にファインチューニングする一般的な方法として登場しました。QloRA では、事前トレーニング済みモデルが 4 ビットに量子化され、重みが固定されます。次に、トレーニング可能なアダプター レイヤ(LoRA)が接続され、アダプター レイヤのみがトレーニングされます。その後、アダプターの重みをベースモデルと統合するか、別のアダプターとして保持できます。
開発環境を設定する
まず、TRL やデータセットなどの Hugging Face ライブラリをインストールして、さまざまな 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
注: Ampere アーキテクチャ(NVIDIA L4 など)以降の GPU を使用している場合は、Flash Attention を使用できます。Flash Attention は、計算を大幅に高速化し、シーケンス長でメモリ使用量を 2 乗から線形に削減する手法です。これにより、トレーニングが最大 3 倍高速化されます。詳細については、FlashAttention をご覧ください。
モデルを公開するには、有効な Hugging Face トークンが必要です。Google Colab
内で実行している場合は、Colab シークレットを使用して Hugging Face トークンを安全に使用できます。それ以外の場合は、login
メソッドでトークンを直接設定できます。トレーニング中にモデルを Hub に push するため、トークンに書き込み権限があることを確認してください。
# Login into Hugging Face Hub
from huggingface_hub import login
login()
ファインチューニング データセットを作成して準備する
LLM をファインチューニングする場合は、ユースケースと解決するタスクを把握することが重要です。これにより、モデルをファインチューニングするためのデータセットを作成できます。ユースケースをまだ定義していない場合は、もう一度検討することをおすすめします。
たとえば、このガイドでは次のユースケースに焦点を当てています。
- データ分析ツールにシームレスに統合するために、自然言語から SQL へのモデルをファインチューニングします。目的は、SQL クエリの生成に必要な時間と専門知識を大幅に削減し、技術系のユーザー以外でもデータから有意義な分析情報を抽出できるようにすることです。
テキストから SQL への変換は、データと SQL 言語に関する多くの(内部)知識を必要とする複雑なタスクであるため、LLM のファインチューニングに適したユースケースです。
ファインチューニングが適切なソリューションであると判断したら、ファインチューニング用のデータセットが必要です。データセットは、解決するタスクの多様なデモンストレーションである必要があります。このようなデータセットを作成する方法はいくつかあります。
- Spider などの既存のオープンソース データセットを使用する
- Alpaca などの LLM によって作成された合成データセットを使用する
- Dolly などの人間が作成したデータセットを使用する。
- Orca などの方法を組み合わせる
各方法には長所と短所があり、予算、時間、品質要件によって異なります。たとえば、既存のデータセットを使用するのが最も簡単ですが、特定のユースケースに合わせて調整されていない可能性があります。一方、ドメイン エキスパートを使用するのが最も正確ですが、時間と費用がかかる可能性があります。Orca: Progressive Learning from Complex Explanation Traces of GPT-4 に示すように、複数の方法を組み合わせて命令データセットを作成することもできます。
このガイドでは、既存のデータセット(philschmid/gretel-synthetic-text-to-sql)を使用します。これは、自然言語の指示、スキーマ定義、推論、対応する 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 には 10 万件を超えるサンプルが含まれています。ガイドを簡潔にするため、1 万件のサンプルのみを使用するようにダウンサンプリングされています。
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'}
TRL と SFTTrainer を使用して Gemma をファインチューニングする
これで、モデルをファインチューニングする準備が整いました。Hugging Face TRL SFTTrainer を使用すると、オープン LLM を簡単に監督してファインチューニングできます。SFTTrainer は transformers ライブラリの Trainer のサブクラスであり、ロギング、評価、チェックポイントなど、同じ機能をすべてサポートしていますが、次のような追加の利便性機能が追加されています。
- 会話形式や指示形式などのデータセットのフォーマット
- プロンプトを無視して、完了のみをトレーニングする
- トレーニングを効率化するためのデータセットのパッキング
- QloRA を含むパラメータ エフィシエント ファインチューニング(PEFT)のサポート
- 会話のファインチューニング用のモデルとトークナイザーの準備(特殊トークンの追加など)
次のコードは、Hugging Face から Gemma モデルとトークナイザーを読み込み、量子化構成を初期化します。
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 との組み込み統合をサポートしているため、QLoRA を使用して LLM
を効率的にチューニングできます。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';
まとめと次のステップ
このチュートリアルでは、TRL と QLoRA を使用して Gemma モデルをファインチューニングする方法について説明しました。次のドキュメントもご覧ください。
- Gemma モデルでテキストを生成する方法を学習する。
- Hugging Face Transformers を使用して、ビジョン タスク用に Gemma をファインチューニングする方法を学習する。
- Gemma モデルで分散ファインチューニングと推論を行う方法を学習する。
- Vertex AI で Gemma オープンモデルを使用する方法を学習する。
- KerasNLP を使用して Gemma を ファインチューニングし、Vertex AI にデプロイする方法を学習する。
[Run in Google Colab]
[GitHub 上のソースを見る]