SFT
Supervised Fine-Tuning
Fine-tuning a model with labeled data in a supervised way. The stage before RLHF. A core training method for chatbots like ChatGPT.
Supervised Fine-Tuning
Fine-tuning a model with labeled data in a supervised way. The stage before RLHF. A core training method for chatbots like ChatGPT.
SFT (Supervised Fine-Tuning) is the process of training a pretrained LLM through supervised learning on high-quality (input, output) pair data. By directly showing "when a user asks this, you should answer like this," it is also called Instruction Tuning.
All conversational LLMs, including GPT-3.5/4, Claude, and Llama 2 Chat, go through SFT. A base model (GPT-3) simply predicts the next token, whereas a model that has gone through SFT (ChatGPT) responds appropriately to user questions. OpenAI mobilized thousands of human labelers for this process.
The typical LLM alignment pipeline proceeds in the order Pretraining -> SFT -> RLHF. SFT teaches basic conversational ability and instruction following, and RLHF reflects more nuanced preferences. Recently, there has been a trend of replacing RLHF with DPO (Direct Preference Optimization).
As open-source models such as Alpaca and Vicuna succeeded by using GPT-3.5 outputs as SFT data, synthetic-data-based SFT has been attracting attention. Even 1,000 to 10,000 high-quality data samples alone can bring substantial performance gains.
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments
from trl import SFTTrainer
from datasets import load_dataset
# λͺ¨λΈκ³Ό ν ν¬λμ΄μ λ‘λ
model_name = "meta-llama/Llama-2-7b-hf"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
# SFT λ°μ΄ν°μ
λ‘λ (Instruction-Output νμ)
dataset = load_dataset("tatsu-lab/alpaca", split="train")
# λ°μ΄ν° ν¬λ§·ν
ν¨μ
def format_instruction(example):
"""Alpaca νμμ ν둬ννΈ μμ±"""
if example.get("input"):
return f"""### Instruction:
{example['instruction']}
### Input:
{example['input']}
### Response:
{example['output']}"""
else:
return f"""### Instruction:
{example['instruction']}
### Response:
{example['output']}"""
# νμ΅ μ€μ
training_args = TrainingArguments(
output_dir="./llama-2-7b-sft",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-5,
warmup_ratio=0.03,
logging_steps=10,
save_strategy="epoch",
bf16=True,
)
# SFT Trainer μ¬μ©
trainer = SFTTrainer(
model=model,
args=training_args,
train_dataset=dataset,
formatting_func=format_instruction,
max_seq_length=2048,
tokenizer=tokenizer,
)
# νμ΅ μ€ν
trainer.train()
trainer.save_model("./llama-2-7b-sft-final")
# A100 80GB κΈ°μ€: 7B λͺ¨λΈ SFT ~4μκ°, 52K μν
# === LoRA + SFT (λ©λͺ¨λ¦¬ ν¨μ¨μ ) ===
from peft import LoraConfig, get_peft_model
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"
)
model_lora = get_peft_model(model, lora_config)
model_lora.print_trainable_parameters()
# trainable params: 4,194,304 || all params: 6,742,609,920 || trainable%: 0.0622
# LoRA SFTλ RTX 4090 24GBλ‘λ 7B λͺ¨λΈ νμ΅ κ°λ₯!
# === ChatML νμ λ°μ΄ν° ===
def format_chatml(example):
"""ChatML νμ (OpenAI, Mistral νΈν)"""
return f"""<|im_start|>system
You are a helpful AI assistant.<|im_end|>
<|im_start|>user
{example['instruction']}<|im_end|>
<|im_start|>assistant
{example['output']}<|im_end|>"""
# === κ³ νμ§ λ°μ΄ν° μμ± (GPT-4 νμ©) ===
from openai import OpenAI
import json
client = OpenAI()
def generate_sft_data(topic: str, num_samples: int = 10):
"""GPT-4λ‘ SFT λ°μ΄ν° ν©μ±"""
samples = []
for _ in range(num_samples):
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{
"role": "user",
"content": f"""λ€μ μ£Όμ μ λν Q&A λ°μ΄ν°λ₯Ό μμ±νμΈμ.
μ£Όμ : {topic}
JSON νμ:
{{"instruction": "μ¬μ©μ μ§λ¬Έ", "output": "μμΈνκ³ μ νν λ΅λ³"}}"""
}],
response_format={"type": "json_object"}
)
samples.append(json.loads(response.choices[0].message.content))
return samples
# === νκ° λ©νΈλ¦ ===
def evaluate_sft_model(model, tokenizer, test_prompts):
"""SFT λͺ¨λΈ νμ§ νκ°"""
results = []
for prompt in test_prompts:
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=200)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
results.append({"prompt": prompt, "response": response})
return results
# GPT-4λ‘ μλ΅ νμ§ νκ° (LLM-as-Judge)
def evaluate_with_gpt4(responses):
"""GPT-4λ‘ μλ΅ νμ§ μ μ λ§€κΈ°κΈ°"""
scores = []
for r in responses:
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{
"role": "user",
"content": f"""λ€μ μλ΅μ νμ§μ 1-10μ μΌλ‘ νκ°νμΈμ.
μ§λ¬Έ: {r['prompt']}
μλ΅: {r['response']}
μ μ (μ«μλ§):"""
}]
)
scores.append(int(response.choices[0].message.content.strip()))
return sum(scores) / len(scores)
"The base Llama model can't hold a conversation. If we create about 10,000 Q&A data samples that fit our domain and run SFT, that should do it. With LoRA, one A100 for a day is enough. There's no need to go as far as RLHF; SFT alone is good enough to use."
"SFT is the process of training an LLM to follow instructions. A pretrained model only completes text, but after SFT it understands commands such as 'summarize this' and 'translate this.' ChatGPT was built with SFT + RLHF, and recently DPO has been emerging as a more efficient alternative."
"80% of SFT success is data quality. According to the LIMA paper, 1,000 high-quality data samples perform better than the 52,000 Alpaca data samples. Quality over quantity. Creating synthetic data with GPT-4 and having people review it is the best value for cost."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
SFT on noisy data actually degrades model performance. 10,000 high-quality samples > 1 million low-quality samples.
SFT on a specific domain only causes general capabilities to be lost. Mix diverse tasks or use LoRA to preserve the original knowledge.
Keep the prompt format consistent, and mix domain data and general data at 8:2. Start with a learning rate 10 times lower than the base.