Fine-tuning
Fine-tuning
Additional training of a pretrained model for a specific task. High performance with little data. Made efficient with LoRA.
Fine-tuning
Additional training of a pretrained model for a specific task. High performance with little data. Made efficient with LoRA.
Fine-tuning is a technique that further trains a model pre-trained on large-scale data (Pre-trained Model) to suit a specific domain or task. It can achieve high performance with far less data and time than training from scratch. It adds expertise in a specific field while retaining the foundation model's general language/vision understanding capabilities.
The concept of fine-tuning became popular with the emergence of BERT in 2018. Transfer Learning existed before that, but with the emergence of Transformer-based large language models, the effectiveness of fine-tuning improved dramatically. In the LLM era since 2023, efficient fine-tuning techniques such as Instruction Tuning, RLHF (Reinforcement Learning from Human Feedback), and LoRA have developed, making it possible to fine-tune models with billions of parameters even on small-scale GPUs.
Fine-tuning methods fall broadly into three categories. Full Fine-tuning is the traditional approach that updates all parameters. PEFT (Parameter-Efficient Fine-Tuning) uses LoRA, QLoRA, Adapters, and similar methods to train only a small number of parameters, saving memory and time. Instruction Tuning trains the model on instruction-response pairs so that it follows instructions better. In 2024-2025, tools such as QLoRA and Unsloth made it possible to fine-tune 7B-70B models even on consumer GPUs.
In practice, fine-tuning is applied to domain-specific tasks that are difficult to solve with RAG. It is effective in fields where technical terminology and context are important, such as medicine, law, and finance, when a specific output format or style is required, and when response speed is important and external retrieval needs to be reduced. However, RAG is suitable when up-to-date information needs to be reflected, and fine-tuning is suitable when domain knowledge needs to be internalized. In many cases, a hybrid approach that uses both techniques together is the best.
This is an example of LoRA fine-tuning using Hugging Face and PEFT.
# LoRA 파인튜닝 예제
# pip install transformers peft datasets accelerate bitsandbytes
from transformers import (
AutoModelForCausalLM, AutoTokenizer,
TrainingArguments, Trainer, DataCollatorForLanguageModeling
)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from datasets import load_dataset
import torch
# 4비트 양자화로 모델 로드 (메모리 절약)
model_name = "meta-llama/Llama-2-7b-hf"
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
model_name,
load_in_4bit=True,
device_map="auto",
torch_dtype=torch.float16,
)
# LoRA 설정
lora_config = LoraConfig(
r=16, # LoRA rank
lora_alpha=32, # 스케일링 파라미터
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], # 적용 레이어
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
# PEFT 모델 생성
model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)
# 학습 가능한 파라미터 수 확인
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
total_params = sum(p.numel() for p in model.parameters())
print(f"학습 가능 파라미터: {trainable_params:,} / {total_params:,} ({100 * trainable_params / total_params:.2f}%)")
# 데이터셋 준비 (예: 한국어 지시 데이터)
def preprocess(example):
prompt = f"### 질문: {example['instruction']}\n\n### 답변: {example['output']}"
return tokenizer(prompt, truncation=True, max_length=512)
dataset = load_dataset("your_dataset", split="train")
tokenized_dataset = dataset.map(preprocess, remove_columns=dataset.column_names)
# 학습 설정
training_args = TrainingArguments(
output_dir="./lora-output",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
fp16=True,
logging_steps=10,
save_steps=100,
)
# 학습 실행
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
trainer.train()
# 어댑터 저장
model.save_pretrained("./lora-adapter")
This is an example of GPT fine-tuning through the OpenAI API.
# OpenAI 파인튜닝 API
# pip install openai
from openai import OpenAI
import json
client = OpenAI()
# 1. 학습 데이터 준비 (JSONL 형식)
training_data = [
{
"messages": [
{"role": "system", "content": "당신은 친절한 고객 상담원입니다."},
{"role": "user", "content": "배송이 언제 오나요?"},
{"role": "assistant", "content": "주문 번호를 알려주시면 배송 현황을 확인해드리겠습니다."}
]
},
# ... 더 많은 예시
]
# JSONL 파일로 저장
with open("training_data.jsonl", "w", encoding="utf-8") as f:
for item in training_data:
f.write(json.dumps(item, ensure_ascii=False) + "\n")
# 2. 파일 업로드
file = client.files.create(
file=open("training_data.jsonl", "rb"),
purpose="fine-tune"
)
print(f"파일 ID: {file.id}")
# 3. 파인튜닝 작업 생성
fine_tune_job = client.fine_tuning.jobs.create(
training_file=file.id,
model="gpt-4o-mini-2024-07-18", # 또는 gpt-3.5-turbo
hyperparameters={
"n_epochs": 3,
"learning_rate_multiplier": 1.0,
}
)
print(f"작업 ID: {fine_tune_job.id}")
# 4. 작업 상태 확인
job = client.fine_tuning.jobs.retrieve(fine_tune_job.id)
print(f"상태: {job.status}")
# 5. 완료 후 파인튜닝 모델 사용
# fine_tuned_model = "ft:gpt-4o-mini:your-org::xxxx"
# response = client.chat.completions.create(
# model=fine_tuned_model,
# messages=[{"role": "user", "content": "배송 문의드립니다"}]
# )
This is a comparison of fine-tuning methods as of January 2025.
| Method | Memory Requirements | Training Speed | Performance | Applicable Models |
|---|---|---|---|---|
| Full Fine-tuning | Very high (80GB+) | Slow | Highest | 7B or smaller |
| LoRA | Medium (24GB) | Fast | High | 70B or smaller |
| QLoRA (4bit) | Low (8-16GB) | Fast | High | 70B or smaller |
| Adapters | Low | Fast | Medium | All sizes |
Cloud fine-tuning service pricing (January 2025):
| Services | Training Cost | Inference Cost | Features |
|---|---|---|---|
| OpenAI GPT-4o-mini | $3.00/1M tokens | $0.15/1M input | Easiest to get started |
| Together AI | $3.00/hour | $0.20/1M tokens | Open-source model support |
| AWS Bedrock | Varies by model | Varies by model | Enterprise integration |
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Training for a long time on a small amount of data causes overfitting. The model works well only on the training data, and its performance degrades on new inputs. Monitor with a validation set and apply early stopping.
Fine-tuning too heavily on a specific domain makes the model forget the general knowledge it learned previously. Keep the learning rate low, and mix in general data when training.
Start with at least 1,000 high-quality examples. Lower the learning rate to 0.1-0.5 times the default, and limit epochs to 1-3. Start with a LoRA rank of 8-32 and adjust according to performance.