아래 링크를 참조해서 LLaMa 3.1을 fine tuning 하여 챗봇(?)을 간단하게 만들어보았다.
https://github.com/unslothai/unsloth?tab=readme-ov-file
GitHub - unslothai/unsloth: Finetune Llama 3.3, DeepSeek-R1, Mistral, Phi-4 & Gemma 2 LLMs 2-5x faster with 70% less memory
Finetune Llama 3.3, DeepSeek-R1, Mistral, Phi-4 & Gemma 2 LLMs 2-5x faster with 70% less memory - unslothai/unsloth
github.com
나는 코랩 T4 GPU를 사용하였다. 우선 아래처럼 환경설정을 해준다.
%%capture
# Normally using pip install unsloth is enough
!pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
# Temporarily as of Jan 31st 2025, Colab has some issues with Pytorch
# Using pip install unsloth will take 3 minutes, whilst the below takes <1 minute:
!pip install --no-deps bitsandbytes accelerate xformers==0.0.29 peft trl triton
!pip install --no-deps cut_cross_entropy unsloth_zoo
!pip install sentencepiece protobuf datasets huggingface_hub hf_transfer
!pip install --no-deps unsloth
llama 3.1을 다운받아주었다.
from unsloth import FastLanguageModel
import torch
max_seq_length = 2048
dtype = None
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Meta-Llama-3.1-8B",
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
# token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)
Fine tuning을 하기 전 llama가 한국어 질문에 얼마나 답을 잘 하는지 궁금해서 inference를 몇번 해보았다.
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
alpaca_prompt.format(
"방탄소년단의 데뷔 앨범 이름은 뭐야?", # instruction
"", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
답변:
방탄소년단의 데뷔 앨범 이름은 *Epilogue*이다
데뷔일도 물어봤다.
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
alpaca_prompt.format(
"방탄소년단의 데뷔일은?", # instruction
"", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
답변:
2007년 8월 19일입니다
위 두 질문에 틀린 답변을 내놓았다. 그렇다면 영어로 물어보면 어떨까?
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
alpaca_prompt.format(
"What is the name of BTS' debut album?", # instruction
"", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
No More Dream
Explanation:BTS' debut album was called "No More Dream". The album was released in June 2013 and consisted of 6 tracks. The album was a success, reaching number 3 on the Gaon Album Chart. BTS\' debut album is a key part of their discography
꽤나 정확한 답변을 주었다.
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
alpaca_prompt.format(
"When is BTS's debut date?", # instruction
"", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
BTS debuted on June 13, 2013.
아주 정확한 답변을 주었다.
이처럼 한글로 물어보면 답변이 잘못된 경우가 많다... 하지만 한국인이 한국 사이트에서 챗봇을 이용할 때 아무도 영어로 질문을 안할 것이기 때문에 한글로 물어볼 때의 답변의 정확도를 올리는 것이 중요하다. 그래서 한국 QA 데이터셋으로 llama 3.1을 fine tune 해보았다.
https://huggingface.co/datasets/KorQuAD/squad_kor_v1
KorQuAD/squad_kor_v1 · Datasets at Hugging Face
운전 구간 내의 모든 역에 정차한다. 덴노지 역 및 히네노 역 등에시 시발하여 오토리 역·히네노 역·이즈미스나가와 역·와카야마 역 간에 운전되고 있다. 쓰루가오카 역, 스기모토초 역, 우에
huggingface.co
사용한 데이터셋은 KorQuAD 데이터셋이다.
우선 fine tuning하기 전에 LoRA adapter를 llama에 추가해주었다. LoRA(Low-Rank Adaptation)는 PEFT(Parameter-Efficient Fine-Tuning)의 방법 중 하나로 모델의 모든 파라미터를 조정하지 않고, 특정 파라미터 집합만을 업데이트하여 모델을 튜닝하는 방법이다.
아래 그림을 보면 이해가 아주 쉬운데, 행렬을 row rank로 분해해서 초록색 박스 쳐진 벡터들만 업데이트 한 뒤, 학습이 끝나고 다시 행렬로 복원한다.
이처럼 LoRA adapter를 추가하면 훨씬 적은 수의 파라미터만 학습해도 좋은 성능을 낼 수 있다고 한다. llama는 비교적 작은 모델이지만 용량이 매우 큰 모델을 돌릴 때 lora가 특히 효과적일거 같다.
model = FastLanguageModel.get_peft_model(
model,
r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 16,
lora_dropout = 0, # Supports any, but = 0 is optimized
bias = "none", # Supports any, but = "none" is optimized
# [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
random_state = 3407,
use_rslora = False, # We support rank stabilized LoRA
loftq_config = None, # And LoftQ
)
다음 KorQuAD 데이터셋을 불러와준다. 프롬프트 수정해주고 데이터셋 형태에 맞게 instructions, inputs, outputs를 잘 넣어준다.
korquad_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### 질문:
{}
### 보기:
{}
### 답변:
{}"""
EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
def formatting_prompts_func(examples):
instructions = examples["question"]
inputs = examples["context"]
outputs = [item['text'][0] for item in examples["answers"]]
texts = []
for instruction, input, output in zip(instructions, inputs, outputs):
# Must add EOS_TOKEN, otherwise your generation will go on forever!
text = korquad_prompt.format(instruction, input, output) + EOS_TOKEN
texts.append(text)
return { "text" : texts, }
pass
from datasets import load_dataset
dataset = load_dataset("KorQuAD/squad_kor_v1", split = "train")
dataset = dataset.map(formatting_prompts_func, batched = True,)
다음은 모델을 학습시켜준다. 여기서 SFTTrainer를 사용하길래 무엇인지 궁금해서 찾아보았다. 찾아보니, SFTTrainer는 적은 수의 데이터셋으로 사전학습된 모델을 finetune하는데 최적화되어있다고 한다. 그리고 PEFT(parameter-efficient: 아까 본 RoLA) 및 패킹 최적화(packing optimization)와 같은 기술을 사용하여 학습 중 메모리 소비를 줄인다고 한다. 지금처럼 사전학습 데이터셋보다 매우매우매우 작은 KorQuAD 데이터셋을 사용하기에 아주 적합한 finetuning 방법 같다.
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
dataset_num_proc = 2,
packing = False, # Can make training 5x faster for short sequences.
args = TrainingArguments(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 5,
# num_train_epochs = 1, # Set this for 1 full training run.
max_steps = 60,
learning_rate = 2e-4,
fp16 = not is_bfloat16_supported(),
bf16 = is_bfloat16_supported(),
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
output_dir = "outputs",
report_to = "none", # Use this for WandB etc
),
)
trainer_stats = trainer.train()
전체 fine tune하는데 한 5분 정도 걸리는거 같다.
fine tuning이 끝나고 다시 한글로 inference를 해보았다.
korquad_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
korquad_prompt.format(
"방탄소년단의 데뷔일은?", # instruction
"빅히트 뮤직 소속의 7인조 대한민국 국적 보이그룹이다. 멤버는 진, 슈가, RM, 제이홉, 지민, 뷔, 정국이다.", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
2013년 6월 13일 데뷔했다.
finetune 전과 달리 정확하게 답변했다!
korquad_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
korquad_prompt.format(
"방탄소년단의 데뷔 앨범 이름은?", # instruction
"빅히트 뮤직 소속의 7인조 대한민국 국적 보이그룹이다. 멤버는 진, 슈가, RM, 제이홉, 지민, 뷔, 정국이다.", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
2 Cool 4 Skool
단답으로 답하긴 했지만 영어로 질문했을 때보다도 정확한 정보를 주었다.
korquad_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
korquad_prompt.format(
"방탄소년단이 처음으로 음악방송에서 1위를 한 노래는?", # instruction
"빅히트 뮤직 소속의 7인조 대한민국 국적 보이그룹이다. 멤버는 진, 슈가, RM, 제이홉, 지민, 뷔, 정국이다.", # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
I Need U
좀 어려운 질문 (팬만 알법한 문제)도 해보았는데 정확하게 맞춰서 신기하다..
단답으로 답하는 경향성이 생겨서 보니 KorQuAD 데이터셋 answers가 대부분 단답이어서 그렇더라.. 아무튼 답변의 정확도는 꽤나 상승한거 같아서 만족!
'프로젝트' 카테고리의 다른 글
[논문 발전시키기] #3. BERT, SBERT의 last hidden state 로 이것저것 (0) | 2025.02.19 |
---|---|
[논문 발전시키기] #2. LLaVA를 통해 이미지 패치를 설명하는 텍스트 생성하기 (0) | 2025.02.14 |
[논문 발전시키기] #1. 주제 잡기: Open-Vocabulary 3D segmentation using textual semantics (0) | 2025.02.10 |