이 가이드에서는 Hugging Face Transformers 및 TRL을 사용하여 맞춤 텍스트-SQL 데이터 세트에서 Gemma를 파인 튜닝하는 방법을 안내합니다. 학습 내용
- 양자화된 LoRA (QLoRA)란 무엇인가요?
- 개발 환경 설정
- 미세 조정 데이터 세트 만들기 및 준비
- TRL 및 SFTTrainer를 사용하여 Gemma 미세 조정
- 모델 추론 테스트 및 SQL 쿼리 생성
양자화된 LoRA (QLoRA)란 무엇인가요?
이 가이드에서는 높은 성능을 유지하면서 컴퓨팅 리소스 요구사항을 줄여 LLM을 효율적으로 파인 튜닝하는 인기 있는 방법으로 부상한 양자화된 로우 랭크 적응 (QLoRA)의 사용을 보여줍니다. QloRA에서는 사전 학습된 모델이 4비트로 양자화되고 가중치가 고정됩니다. 그런 다음 학습 가능한 어댑터 레이어 (LoRA)가 연결되고 어댑터 레이어만 학습됩니다. 그런 다음 어댑터 가중치를 기본 모델과 병합하거나 별도의 어댑터로 유지할 수 있습니다.
개발 환경 설정
첫 번째 단계는 다양한 RLHF 및 정렬 기법을 비롯한 공개 모델을 미세 조정하기 위해 TRL 및 데이터 세트를 비롯한 Hugging Face 라이브러리를 설치하는 것입니다.
# Install Pytorch & other libraries
%pip install "torch>=2.4.0" tensorboard
# Install Gemma release branch from Hugging Face
%pip install "transformers>=4.51.3"
# Install Hugging Face libraries
%pip install --upgrade \
"datasets==3.3.2" \
"accelerate==1.4.0" \
"evaluate==0.4.3" \
"bitsandbytes==0.45.3" \
"trl==0.21.0" \
"peft==0.14.0" \
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은 계산 속도를 크게 높이고 메모리 사용량을 시퀀스 길이의 2차에서 선형으로 줄여 학습 속도를 최대 3배까지 높이는 방법입니다. FlashAttention에서 자세히 알아보세요.
학습을 시작하기 전에 Gemma 이용약관에 동의했는지 확인해야 합니다. Hugging Face에서 라이선스를 수락하려면 http://huggingface.co/google/gemma-3-1b-pt의 모델 페이지에서 동의 및 저장소 액세스 버튼을 클릭하세요.
라이선스에 동의한 후 모델에 액세스하려면 유효한 Hugging Face 토큰이 필요합니다. Google Colab 내에서 실행하는 경우 Colab 보안 비밀을 사용하여 Hugging Face 토큰을 안전하게 사용할 수 있습니다. 그렇지 않으면 login 메서드에서 직접 토큰을 설정할 수 있습니다. 학습 중에 모델을 허브에 푸시하므로 토큰에 쓰기 액세스 권한도 있어야 합니다.
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)
미세 조정 데이터 세트 만들기 및 준비
LLM을 미세 조정할 때는 사용 사례와 해결하려는 작업을 아는 것이 중요합니다. 이를 통해 모델을 미세 조정할 데이터 세트를 만들 수 있습니다. 아직 사용 사례를 정의하지 않았다면 다시 설계 단계로 돌아가는 것이 좋습니다.
예를 들어 이 가이드에서는 다음 사용 사례에 중점을 둡니다.
- 데이터 분석 도구에 원활하게 통합할 수 있도록 자연어-SQL 모델을 미세 조정합니다. 목표는 SQL 쿼리 생성에 필요한 시간과 전문성을 크게 줄여 기술자가 아닌 사용자도 데이터에서 의미 있는 통계를 추출할 수 있도록 하는 것입니다.
텍스트-SQL은 데이터와 SQL 언어에 관한 많은 (내부) 지식이 필요한 복잡한 작업이므로 LLM 미세 조정에 적합한 사용 사례가 될 수 있습니다.
미세 조정이 적합한 솔루션이라고 판단되면 미세 조정할 데이터 세트가 필요합니다. 데이터 세트는 해결하려는 작업의 다양한 데모여야 합니다. 이러한 데이터 세트를 만드는 방법에는 여러 가지가 있습니다.
- Spider와 같은 기존 오픈소스 데이터 세트 사용
- Alpaca와 같은 LLM으로 생성된 합성 데이터 세트 사용
- Dolly와 같이 사람이 만든 데이터 세트를 사용합니다.
- Orca와 같은 메서드 조합 사용
각 방법에는 장단점이 있으며 예산, 시간, 품질 요구사항에 따라 달라집니다. 예를 들어 기존 데이터 세트를 사용하는 것이 가장 쉽지만 특정 사용 사례에 맞지 않을 수 있으며, 도메인 전문가를 사용하는 것이 가장 정확할 수 있지만 시간이 오래 걸리고 비용이 많이 들 수 있습니다. Orca: Progressive Learning from Complex Explanation Traces of GPT-4에 표시된 것처럼 여러 메서드를 결합하여 명령어 데이터 세트를 만들 수도 있습니다.
이 가이드에서는 자연어 안내, 스키마 정의, 추론, 해당 SQL 쿼리를 포함하는 고품질 합성 Text-to-SQL 데이터 세트인 기존 데이터 세트 (philschmid/gretel-synthetic-text-to-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만 개가 넘는 샘플이 포함되어 있습니다. 가이드를 작게 유지하기 위해 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 10,000 training samples and 2,500 test samples
dataset = dataset.train_test_split(test_size=2500/12500)
# Print formatted user prompt
print(dataset["train"][345]["messages"][1]["content"])
TRL 및 SFTTrainer를 사용하여 Gemma 미세 조정
이제 모델을 미세 조정할 준비가 되었습니다. Hugging Face TRL SFTTrainer를 사용하면 오픈 LLM을 감독 기반으로 미세 조정할 수 있습니다. SFTTrainer는 transformers 라이브러리의 Trainer의 서브클래스이며 로깅, 평가, 체크포인트를 비롯한 모든 동일한 기능을 지원하지만 다음과 같은 삶의 질 기능이 추가됩니다.
- 대화형 및 명령 형식 등 데이터 세트 형식 지정
- 완성만 학습하고 프롬프트는 무시
- 더 효율적인 학습을 위한 데이터 세트 패킹
- QloRA를 비롯한 Parameter-Efficient Fine-Tuning (PEFT) 지원
- 대화형 미세 조정을 위해 모델과 토큰화 도구 준비 (예: 특수 토큰 추가)
다음 코드는 Hugging Face에서 Gemma 모델과 토큰화 도구를 로드하고 양자화 구성을 초기화합니다.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForImageTextToText, BitsAndBytesConfig
# Hugging Face model id
model_id = "google/gemma-3-1b-pt" # or `google/gemma-3-4b-pt`, `google/gemma-3-12b-pt`, `google/gemma-3-27b-pt`
# Select model class based on id
if model_id == "google/gemma-3-1b-pt":
model_class = AutoModelForCausalLM
else:
model_class = AutoModelForImageTextToText
# 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(
attn_implementation="eager", # Use "flash_attention_2" when running on Ampere or newer GPU
torch_dtype=torch_dtype, # What torch dtype to use, defaults to auto
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['torch_dtype'],
bnb_4bit_quant_storage=model_kwargs['torch_dtype'],
)
# Load model and tokenizer
model = model_class.from_pretrained(model_id, **model_kwargs)
tokenizer = AutoTokenizer.from_pretrained("google/gemma-3-1b-it") # Load the Instruction Tokenizer to use the official Gemma template
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
)
학습을 시작하기 전에 SFTConfig 인스턴스에서 사용할 초매개변수를 정의해야 합니다.
from trl import SFTConfig
args = SFTConfig(
output_dir="gemma-text-to-sql", # directory to save and repository id
max_length=512, # max sequence length for model and packing of the dataset
packing=True, # Groups multiple samples in the dataset into a single sequence
num_train_epochs=3, # number of training epochs
per_device_train_batch_size=1, # batch size per device during training
gradient_accumulation_steps=4, # number of steps before performing a backward/update pass
gradient_checkpointing=True, # use gradient checkpointing to save memory
optim="adamw_torch_fused", # use fused adamw optimizer
logging_steps=10, # log every 10 steps
save_strategy="epoch", # save checkpoint every epoch
learning_rate=2e-4, # learning rate, based on QLoRA paper
fp16=True if torch_dtype == torch.float16 else False, # use float16 precision
bf16=True if torch_dtype == torch.bfloat16 else False, # use bfloat16 precision
max_grad_norm=0.3, # max gradient norm based on QLoRA paper
warmup_ratio=0.03, # warmup ratio 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, # We 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"],
peft_config=peft_config,
processing_class=tokenizer
)
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()
모델을 테스트하기 전에 메모리를 확보해야 합니다.
# 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 = model_class.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")
모델 추론 테스트 및 SQL 쿼리 생성
학습이 완료되면 모델을 평가하고 테스트해야 합니다. 테스트 데이터 세트에서 다양한 샘플을 로드하고 해당 샘플에서 모델을 평가할 수 있습니다.
import torch
from transformers import pipeline
model_id = "gemma-text-to-sql"
# Load Model with PEFT adapter
model = model_class.from_pretrained(
model_id,
device_map="auto",
torch_dtype=torch_dtype,
attn_implementation="eager",
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
테스트 데이터 세트에서 무작위 샘플을 로드하고 SQL 명령어를 생성해 보겠습니다.
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
stop_token_ids = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<end_of_turn>")]
prompt = pipe.tokenizer.apply_chat_template(test_sample["messages"][:2], tokenize=False, add_generation_prompt=True)
# Generate our SQL query.
outputs = pipe(prompt, max_new_tokens=256, do_sample=False, temperature=0.1, top_k=50, top_p=0.1, eos_token_id=stop_token_ids, disable_compile=True)
# Extract the user query and original answer
print(f"Context:\n", re.search(r'<SCHEMA>\n(.*?)\n</SCHEMA>', test_sample['messages'][0]['content'], re.DOTALL).group(1).strip())
print(f"Query:\n", re.search(r'<USER_QUERY>\n(.*?)\n</USER_QUERY>', test_sample['messages'][0]['content'], re.DOTALL).group(1).strip())
print(f"Original Answer:\n{test_sample['messages'][1]['content']}")
print(f"Generated Answer:\n{outputs[0]['generated_text'][len(prompt):].strip()}")
요약 및 다음 단계
이 튜토리얼에서는 TRL 및 QLoRA를 사용하여 Gemma 모델을 미세 조정하는 방법을 다뤘습니다. 다음 문서를 확인하세요.
- Gemma 모델로 텍스트를 생성하는 방법을 알아보세요.
- Hugging Face Transformers를 사용하여 시각 작업에 맞게 Gemma를 미세 조정하는 방법을 알아봅니다.
- Hugging Face 트랜스포머를 사용하여 전체 모델을 미세 조정하는 방법을 알아봅니다.
- Gemma 모델에서 분산 파인 튜닝 및 추론을 실행하는 방법을 알아봅니다.
- Vertex AI에서 Gemma 개방형 모델을 사용하는 방법을 알아보세요.
- KerasNLP를 사용하여 Gemma를 미세 조정하고 Vertex AI에 배포하는 방법을 알아봅니다.