|
|
Google Colab에서 실행
|
|
|
GitHub에서 소스 보기
|
이 가이드에서는 Hugging Face Transformers 및 TRL을 사용하여 커스텀 텍스트-SQL 데이터 세트에서 Gemma를 미세 조정하는 방법을 안내합니다. 학습할 내용은 다음과 같습니다.
- 양자화된 Low-Rank Adaptation (QLoRA)이란 무엇인가요?
- 개발 환경 설정
- 미세 조정 데이터 세트 만들기 및 준비
- TRL 및 SFTTrainer를 사용하여 Gemma 미세 조정
- 모델 추론 테스트 및 SQL 쿼리 생성
양자화된 Low-Rank Adaptation (QLoRA)이란 무엇인가요?
이 가이드에서는 양자화된 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 메서드에서 토큰을 직접 설정할 수 있습니다. 학습 중에 모델을 허브로 푸시하므로 토큰에 쓰기 액세스 권한도 있는지 확인하세요.
# Login into Hugging Face Hub
from huggingface_hub import login
login()
미세 조정 데이터 세트 만들기 및 준비
LLM을 미세 조정할 때는 사용 사례와 해결하려는 작업을 파악하는 것이 중요합니다. 이를 통해 모델을 미세 조정할 데이터 세트를 만들 수 있습니다. 아직 사용 사례를 정의하지 않은 경우 다시 계획을 세우는 것이 좋습니다.
예를 들어 이 가이드에서는 다음 사용 사례에 중점을 둡니다.
- 데이터 분석 도구에 원활하게 통합할 수 있도록 자연어-SQL 모델을 미세 조정합니다. 목표는 SQL 쿼리 생성에 필요한 시간과 전문 지식을 크게 줄여 기술자가 아닌 사용자도 데이터에서 의미 있는 통계를 추출할 수 있도록 하는 것입니다.
텍스트-SQL은 데이터 및 SQL 언어에 관한 많은 (내부) 지식이 필요한 복잡한 작업이므로 LLM을 미세 조정하는 데 적합한 사용 사례가 될 수 있습니다.
미세 조정이 적합한 솔루션이라고 판단한 후에는 미세 조정할 데이터 세트가 필요합니다. 데이터 세트는 해결하려는 작업의 다양한 데모 세트여야 합니다. 이러한 데이터 세트를 만드는 방법에는 다음과 같은 여러 가지가 있습니다.
각 방법에는 고유한 장단점이 있으며 예산, 시간, 품질 요구사항에 따라 다릅니다. 예를 들어 기존 데이터 세트를 사용하는 것이 가장 쉽지만 특정 사용 사례에 맞게 조정되지 않을 수 있으며, 도메인 전문가를 사용하는 것이 가장 정확할 수 있지만 시간이 오래 걸리고 비용이 많이 들 수 있습니다. Orca: 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만 개 이상의 샘플이 포함되어 있습니다. 가이드를 작게 유지하기 위해 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'}
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, 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 오픈 모델을 사용하는 방법을 알아봅1}.
- KerasNLP를 사용하여 Gemma를 미세 조정하고 Vertex AI에 배포하는 방법을 알아봅니다.
Google Colab에서 실행
GitHub에서 소스 보기