🤖 AI/ML

Instruction Tuning

Instruction Tuning

A technique for training a model with instruction-response pairs. Improves instruction-following ability.

📖 Detailed Explanation

Instruction Tuning is a technique for fine-tuning a language model with pairs of natural-language instructions and their responses. It teaches the model the ability to understand and carry out commands such as "summarize this," "translate this," and "write code."

It was systematized in Google's FLAN (Finetuned Language Net) project, and FLAN-T5 was trained on more than 1,800 diverse task templates. This gives it the ability to generalize to instructions it has never seen before (zero-shot generalization).

Conventional language models are optimized for next-token prediction, so they lack the ability to follow commands. Instruction Tuning teaches the pattern "understand the user's intent -> generate an appropriate response," and it is a core technique for building conversational AI like ChatGPT.

In practice, FLAN-T5 achieved 94.8% SQL generation accuracy in 2 hours (versus 54 hours for SQLCoder, a 15B model), and it outperformed GPT-4 in medical report summarization. Even small models can be trained effectively on a single GPU.

💻 Code Example

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, Trainer, TrainingArguments
from datasets import Dataset
import torch

# FLAN-T5 모델 로드
model_name = "google/flan-t5-base"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)

# Instruction Tuning 데이터셋 예시
instruction_data = [
    {"instruction": "다음 문장을 요약해줘:", "input": "인공지능은 컴퓨터 과학의 한 분야로, 기계가 인간처럼 학습하고 추론하는 능력을 갖추게 하는 기술입니다.", "output": "AI는 기계에 학습과 추론 능력을 부여하는 기술입니다."},
    {"instruction": "영어로 번역해줘:", "input": "안녕하세요, 만나서 반갑습니다.", "output": "Hello, nice to meet you."},
    {"instruction": "감정을 분류해줘:", "input": "이 영화 정말 최고였어요!", "output": "긍정"},
]

# 데이터 전처리
def preprocess(examples):
    inputs = [f"{ex['instruction']} {ex['input']}" for ex in examples]
    targets = [ex['output'] for ex in examples]

    model_inputs = tokenizer(inputs, max_length=256, truncation=True, padding="max_length")
    labels = tokenizer(targets, max_length=128, truncation=True, padding="max_length")

    model_inputs["labels"] = labels["input_ids"]
    return model_inputs

dataset = Dataset.from_list(instruction_data)
tokenized_dataset = dataset.map(lambda x: preprocess([x]), batched=False)

# 학습 설정
training_args = TrainingArguments(
    output_dir="./flan-t5-instruction-tuned",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    learning_rate=5e-5,
    save_strategy="epoch"
)

trainer = Trainer(model=model, args=training_args, train_dataset=tokenized_dataset)
trainer.train()
print("Instruction Tuning 완료!")

🗣️ Say It Like This in Practice

💬 In a Meeting
"A base LLM is optimized only for text completion, so it has difficulty following commands. When you apply Instruction Tuning, it becomes able to understand and carry out instructions such as 'summarize this' and 'translate this.'"
💬 In an Interview
"Instruction Tuning is a technique that trains a model with instruction-response pairs. FLAN-T5 is a representative example; it was trained on more than 1,800 tasks, so it responds well even to instructions it has never seen. It is one of the core technologies of ChatGPT."
💬 In a Technical Discussion
"Even FLAN-T5-base alone can be instruction-tuned on a single GPU. If you just build an instruction dataset suited to a specific domain, you can run your own service more cheaply than with the GPT API."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring consistency of instruction format

When "요약해줘", "요약해주세요", and "Summarize" are mixed, it is hard for the model to learn the pattern. Use a consistent template.

❌
Training on a single task only

If you train only on summarization, the model's ability to generalize to other instructions declines. Include a variety of tasks.

✅
Include diverse task templates

Including diverse tasks such as classification, summarization, translation, QA, and code generation improves zero-shot generalization.

🔗 Related Terms

📚 Learn More