knowledge-distillation
하는 일
이 스킬은 큰 교사 모델이 작은 학생 모델을 학습시키는 지식 증류를 설명합니다. 작업에서 여전히 좋은 성능을 내면서 더 저렴한 모델이 필요한 팀을 위한 내용입니다.
사용하는 경우
- ✓큰 모델 품질의 대부분을 유지하는 작은 모델을 배포하고 싶을 때.
- ✓강력한 모델의 능력을 오픈소스 모델로 옮기고 싶을 때.
- ✓작은 학생 모델을 서빙해서 추론 비용을 낮추고 싶을 때.
스킬 링크
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/19-emerging-techniques/knowledge-distillation/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“고객 지원 질문에 대한 큰 모델의 답변을 따라 하도록 작은 모델을 학습시켜 주세요. 그래야 실행 비용이 더 저렴해집니다.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
학생 모델은 정답 라벨만이 아니라 교사 모델의 소프트 확률과 응답에서 배웁니다. 온도 스케일링, 역방향 KL 발산, MiniLLM 방식 학습 같은 기법이 포함됩니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Knowledge Distillation: Compressing LLMs
When to Use This Skill
Use Knowledge Distillation when you need to:
- Compress models from 70B → 7B while retaining 90%+ performance
- Transfer capabilities from proprietary models (GPT-4) to open-source (LLaMA, Mistral)
- Reduce inference costs by deploying smaller student models
- Create specialized models by distilling domain-specific knowledge
- Improve small models using synthetic data from large teachers
Key Techniques: Temperature scaling, soft targets, reverse KLD (MiniLLM), logit distillation, response distillation
Papers: Hinton et al. 2015 (arXiv 1503.02531), MiniLLM (arXiv 2306.08543), KD Survey (arXiv 2402.13116)
Installation
# Standard transformers
pip install transformers datasets accelerate
# For training
pip install torch deepspeed wandb
# Optional: MiniLLM implementation
git clone https://github.com/microsoft/LMOps
cd LMOps/minillm
pip install -e .
Quick Start
Basic Knowledge Distillation
import torch
import torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
# 1. Load teacher (large) and student (small) models
teacher = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-70b-hf", # Large teacher
torch_dtype=torch.float16,
device_map="auto"
)
student = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf", # Small student
torch_dtype=torch.float16,
device_map="cuda:0"
)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-70b-hf")
# 2. Define distillation loss
def distillation_loss(student_logits, teacher_logits, labels, temperature=2.0, alpha=0.5):
"""
Combine hard loss (cross-entropy) with soft loss (KL divergence).
Args:
temperature: Softens probability distributions (higher = softer)
alpha: Weight for distillation loss (1-alpha for hard loss)
"""
# Hard loss: Standard cross-entropy with true labels
hard_loss = F.cross_entropy(student_logits.view(-1, student_logits.size(-1)), labels.view(-1))
# Soft loss: KL divergence between student and teacher
soft_targets = F.softmax(teacher_logits / temperature, dim=-1)
soft_student = F.log_softmax(student_logits / temperature, dim=-1)
soft_loss = F.kl_div(soft_student, soft_targets, reduction='batchmean') * (temperature ** 2)
# Combined loss
return alpha * soft_loss + (1 - alpha) * hard_loss
# 3. Training loop
for batch in dataloader:
# Teacher forward (no grad)
with torch.no_grad():
teacher_outputs = teacher(**batch)
teacher_logits = teacher_outputs.logits
# Student forward
student_outputs = student(**batch)
student_logits = student_outputs.logits
# Compute distillation loss
loss = distillation_loss(
student_logits,
teacher_logits,
batch['labels'],
temperature=2.0,
alpha=0.7 # 70% soft, 30% hard
)
# Backward and optimize
loss.backward()
optimizer.step()
optimizer.zero_grad()
MiniLLM (Reverse KLD)
Source: arXiv 2306.08543 (2024)
Innovation: Use reverse KLD instead of forward KLD for better generative model distillation.
def reverse_kl_loss(student_logits, teacher_logits, temperature=1.0):
"""
Reverse KL divergence: KL(Teacher || Student)
Better for generative models than forward KL.
"""
# Teacher distribution (target)
p_teacher = F.softmax(teacher_logits / temperature, dim=-1)
# Student distribution (model)
log_p_student = F.log_softmax(student_logits / temperature, dim=-1)
# Reverse KL: Sum over teacher, student learns to cover teacher's modes
reverse_kl = -(p_teacher * log_p_student).sum(dim=-1).mean()
return reverse_kl * (temperature ** 2)
# Training with MiniLLM
for batch in dataloader:
with torch.no_grad():
teacher_logits = teacher(**batch).logits
student_logits = student(**batch).logits
# Reverse KLD (better for generation)
loss = reverse_kl_loss(student_logits, teacher_logits, temperature=1.0)
loss.backward()
optimizer.step()
Why reverse KL?
- Forward KL (standard): Student learns to match teacher's mean
- Reverse KL (MiniLLM): Student learns to cover all teacher's modes
- Better for diverse text generation
Response Distillation
# Generate synthetic data from teacher, train student to imitate
# 1. G
자주 묻는 질문
소프트 타깃이란 무엇인가요?
교사 모델이 가능한 답변 전체에 부여한 확률 분포입니다. 정답 하나만 있는 라벨보다 더 많은 정보를 담고 있습니다.
MiniLLM은 무엇인가요?
이 스킬은 MiniLLM을 언어 모델에 역방향 KL 발산을 쓰는 학습 전략으로 소개합니다.
무엇을 설치하나요?
transformers, datasets, accelerate를 설치하고, 학습에는 torch, deepspeed, wandb도 설치하세요.
상세 정보
작성자의 원본 설명
Compress large language models using knowledge distillation from teacher to student models. Use when deploying smaller models with retained performance, transferring GPT-4 capabilities to open-source models, or reducing inference costs. Covers temperature scaling, soft targets, reverse KLD, logit distillation, and MiniLLM training strategies.
인기도
- GitHub 스타
- 14k
- 순위
- #11239
- 라이선스
- MIT
- 업데이트
- 2026. 10. 10.
댓글
- …
이 저장소의 다른 스킬
autoresearch
14k에이전트가 문헌 검토부터 실험과 글쓰기까지 AI 연구 프로젝트 전체를 진행하도록 안내합니다. 테스트와 검토를 반복하는 주기를 따릅니다.
prompt-guard
14k에이전트가 Meta의 작은 분류기로, AI 앱에 도달하기 전에 텍스트에서 프롬프트 인젝션과 탈옥 시도를 검사하도록 돕습니다.
pytorch-fsdp2
14k에이전트가 PyTorch FSDP2를 학습 스크립트에 추가해, 큰 모델을 여러 GPU에 나누고 올바르게 저장하도록 보여 줍니다.
ml-training-recipes
14k에이전트에게 모델 선택, 옵티마이저, 학습률, 손실 급등 해결 등 신경망 학습의 검증된 방법을 알려 줍니다.