πŸ€–AI/ML

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.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

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)

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In an LLM customization meeting
"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."
πŸ’¬ In an Interview
"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."
πŸ’¬ In a data quality discussion
"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

⚠️ Common Mistakes & Cautions

❌
Large-scale SFT on low-quality data

SFT on noisy data actually degrades model performance. 10,000 high-quality samples > 1 million low-quality samples.

❌
Catastrophic Forgetting

SFT on a specific domain only causes general capabilities to be lost. Mix diverse tasks or use LoRA to preserve the original knowledge.

βœ…
The right way

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.

πŸ”— Related Terms

πŸ“š Learn More