[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QEYKPGX7YMGK7FXHWADXY6":3,"skill-same:01M6QEYKPGX7YMGK7FXHWADXY6":84},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":44,"linkOnly":45,"markdownContent":46,"markdownBody":47,"frontMatter":48,"refName":55,"commitSha":56,"skillDirectory":57,"forksCount":14,"repositoryHtmlUrl":58,"repositoryHomepageUrl":59,"ownerHtmlUrl":60,"ownerBlogUrl":61,"ownerDescription":62,"updatedAt":63,"install":64,"resources":77},"01M6QEYKPGX7YMGK7FXHWADXY6","knowledge-distillation",null,"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.","Tashima-Tarsh\u002FDisha6.6","Tashima-Tarsh","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F269906498?v=4","01M6PBH98X03XERH0HFT4PFB1P","NITISH KUMAR","01M6PBH9DA0M6KM3Z12P848F0K",0,"MIT","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-knowledge-distillation\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000021","资料检索与研究","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43],"knowledge","distillation","Knowledge Distillation","teacher","performance","student","Model Transfer","Logit Distillation","Temperature Scaling","Soft Targets","Reverse KLD","MiniLLM","Teacher-Student","Emerging Techniques","scaling","strategies","model","open","capabilities","training","2026-11-10 10:12:30",false,"---\nname: knowledge-distillation\ndescription: 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.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: multimodal-and-emerging\n  maintainer: Kalaris Labs\n  tags: Emerging Techniques, Knowledge Distillation, Model Compression, Teacher-Student, MiniLLM, Reverse KLD, Soft Targets, Temperature Scaling, Logit Distillation, Model Transfer\n  dependencies: transformers, torch, datasets\n---\n\n# Knowledge Distillation: Compressing LLMs\n\n## When to Use This Skill\n\nUse Knowledge Distillation when you need to:\n- **Compress models** from 70B → 7B while retaining 90%+ performance\n- **Transfer capabilities** from proprietary models (GPT-4) to open-source (LLaMA, Mistral)\n- **Reduce inference costs** by deploying smaller student models\n- **Create specialized models** by distilling domain-specific knowledge\n- **Improve small models** using synthetic data from large teachers\n\n**Key Techniques**: Temperature scaling, soft targets, reverse KLD (MiniLLM), logit distillation, response distillation\n\n**Papers**: Hinton et al. 2015 (arXiv 1503.02531), MiniLLM (arXiv 2306.08543), KD Survey (arXiv 2402.13116)\n\n## Installation\n\n```bash\n# Standard transformers\npip install transformers datasets accelerate\n\n# For training\npip install torch deepspeed wandb\n\n# Optional: MiniLLM implementation\ngit clone https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FLMOps\ncd LMOps\u002Fminillm\npip install -e .\n```\n\n## Quick Start\n\n### Basic Knowledge Distillation\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments\n\n# 1. Load teacher (large) and student (small) models\nteacher = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-70b-hf\",  # Large teacher\n    torch_dtype=torch.float16,\n    device_map=\"auto\"\n)\n\nstudent = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",  # Small student\n    torch_dtype=torch.float16,\n    device_map=\"cuda:0\"\n)\n\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-70b-hf\")\n\n# 2. Define distillation loss\ndef distillation_loss(student_logits, teacher_logits, labels, temperature=2.0, alpha=0.5):\n    \"\"\"\n    Combine hard loss (cross-entropy) with soft loss (KL divergence).\n\n    Args:\n        temperature: Softens probability distributions (higher = softer)\n        alpha: Weight for distillation loss (1-alpha for hard loss)\n    \"\"\"\n    # Hard loss: Standard cross-entropy with true labels\n    hard_loss = F.cross_entropy(student_logits.view(-1, student_logits.size(-1)), labels.view(-1))\n\n    # Soft loss: KL divergence between student and teacher\n    soft_targets = F.softmax(teacher_logits \u002F temperature, dim=-1)\n    soft_student = F.log_softmax(student_logits \u002F temperature, dim=-1)\n    soft_loss = F.kl_div(soft_student, soft_targets, reduction='batchmean') * (temperature ** 2)\n\n    # Combined loss\n    return alpha * soft_loss + (1 - alpha) * hard_loss\n\n# 3. Training loop\nfor batch in dataloader:\n    # Teacher forward (no grad)\n    with torch.no_grad():\n        teacher_outputs = teacher(**batch)\n        teacher_logits = teacher_outputs.logits\n\n    # Student forward\n    student_outputs = student(**batch)\n    student_logits = student_outputs.logits\n\n    # Compute distillation loss\n    loss = distillation_loss(\n        student_logits,\n        teacher_logits,\n        batch['labels'],\n        temperature=2.0,\n        alpha=0.7  # 70% soft, 30% hard\n    )\n\n    # Backward and optimize\n    loss.backward()\n    optimizer.step()\n    optimizer.zero_grad()\n```\n\n### MiniLLM (Reverse KLD)\n\n**Source**: arXiv 2306.08543 (2024)\n\n**Innovation**: Use reverse KLD instead of forward KLD for better generative model distillation.\n\n```python\ndef reverse_kl_loss(student_logits, teacher_logits, temperature=1.0):\n    \"\"\"\n    Reverse KL divergence: KL(Teacher || Student)\n    Better for generative models than forward KL.\n    \"\"\"\n    # Teacher distribution (target)\n    p_teacher = F.softmax(teacher_logits \u002F temperature, dim=-1)\n\n    # Student distribution (model)\n    log_p_student = F.log_softmax(student_logits \u002F temperature, dim=-1)\n\n    # Reverse KL: Sum over teacher, student learns to cover teacher's modes\n    reverse_kl = -(p_teacher * log_p_student).sum(dim=-1).mean()\n\n    return reverse_kl * (temperature ** 2)\n\n# Training with MiniLLM\nfor batch in dataloader:\n    with torch.no_grad():\n        teacher_logits = teacher(**batch).logits\n\n    student_logits = student(**batch).logits\n\n    # Reverse KLD (better for generation)\n    loss = reverse_kl_loss(student_logits, teacher_logits, temperature=1.0)\n\n    loss.backward()\n    optimizer.step()\n```\n\n**Why reverse KL?**\n- **Forward KL** (standard): Student learns to match teacher's *mean*\n- **Reverse KL** (MiniLLM): Student learns to *cover* all teacher's modes\n- Better for diverse text generation\n\n### Response Distillation\n\n```python\n# Generate synthetic data from teacher, train student to imitate\n\n# 1. Generate synthetic responses from teacher\nprompts = [\"Explain AI:\", \"What is ML?\", \"Define NLP:\"]\n\nteacher_responses = []\nfor prompt in prompts:\n    inputs = tokenizer(prompt, return_tensors='pt').to(teacher.device)\n    outputs = teacher.generate(**inputs, max_new_tokens=256, do_sample=True, temperature=0.7)\n    response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n    teacher_responses.append(response)\n\n# 2. Train student on teacher's responses (standard fine-tuning)\ntrain_dataset = [\n    {\"text\": f\"{prompt}\\n{response}\"}\n    for prompt, response in zip(prompts, teacher_responses)\n]\n\n# 3. Fine-tune student\ntrainer = Trainer(\n    model=student,\n    args=TrainingArguments(output_dir=\".\u002Fstudent\", num_train_epochs=3, learning_rate=2e-5),\n    train_dataset=train_dataset,\n)\ntrainer.train()\n```\n\n## Core Concepts\n\n### 1. Temperature Scaling\n\n**Purpose**: Soften probability distributions to expose teacher's uncertainty.\n\n```python\n# Low temperature (T=1): Sharp distribution\nlogits = [3.0, 2.0, 1.0]\nprobs_T1 = softmax(logits \u002F 1.0)  # [0.67, 0.24, 0.09]\n\n# High temperature (T=4): Soft distribution\nprobs_T4 = softmax(logits \u002F 4.0)  # [0.42, 0.34, 0.24]\n\n# Higher T reveals more information about relative rankings\n```\n\n**Rule**: Use T=2-5 for distillation (2 is common default).\n\n### 2. Loss Function Components\n\n```python\n# Total loss = alpha * soft_loss + (1 - alpha) * hard_loss\n\n# Soft loss: Learn from teacher's knowledge\nsoft_loss = KL(student || teacher)\n\n# Hard loss: Learn from ground truth labels\nhard_loss = CrossEntropy(student_output, true_labels)\n\n# Typical values:\nalpha = 0.5  # Balanced\nalpha = 0.7  # More emphasis on teacher\nalpha = 0.3  # More emphasis on labels\n```\n\n### 3. Forward vs Reverse KLD\n\n```python\n# Forward KL: KL(Student || Teacher)\n# - Student matches teacher's average behavior\n# - Mode-seeking: Student focuses on teacher's highest probability modes\n# - Good for classification\n\n# Reverse KL: KL(Teacher || Student)\n# - Student covers all of teacher's behaviors\n# - Mode-covering: Student learns diverse behaviors\n# - Good for generation (MiniLLM)\n```\n\n## Training Strategies\n\n### Strategy 1: Logit Distillation\n\n```python\n# Train student to match teacher's logits directly\n\ndef logit_distillation_trainer(student, teacher, dataloader, temperature=2.0):\n    optimizer = torch.optim.AdamW(student.parameters(), lr=2e-5)\n\n    for epoch in range(3):\n        for batch in dataloader:\n            # Get logits\n            with torch.no_grad():\n                teacher_logits = teacher(**batch).logits\n\n            student_logits = student(**batch).logits\n\n            # MSE on logits (alternative to KLD)\n            loss = F.mse_loss(student_logits, teacher_logits)\n\n            # Or use KLD\n            # loss = F.kl_div(\n            #     F.log_softmax(student_logits\u002Ftemperature, dim=-1),\n            #     F.softmax(teacher_logits\u002Ftemperature, dim=-1),\n            #     reduction='batchmean'\n            # ) * (temperature ** 2)\n\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n\n    return student\n```\n\n### Strategy 2: Two-Stage Distillation\n\n```python\n# Stage 1: Distill from teacher\nstudent = distill(teacher, student, epochs=5)\n\n# Stage 2: Fine-tune on task-specific data\nstudent = fine_tune(student, task_data, epochs=3)\n\n# Results in better task performance than single-stage\n```\n\n### Strategy 3: Multi-Teacher Distillation\n\n```python\n# Learn from multiple expert teachers\n\ndef multi_teacher_distillation(student, teachers, batch):\n    \"\"\"Distill from ensemble of teachers.\"\"\"\n    teacher_logits_list = []\n\n    # Get logits from all teachers\n    with torch.no_grad():\n        for teacher in teachers:\n            logits = teacher(**batch).logits\n            teacher_logits_list.append(logits)\n\n    # Average teacher predictions\n    avg_teacher_logits = torch.stack(teacher_logits_list).mean(dim=0)\n\n    # Student learns from ensemble\n    student_logits = student(**batch).logits\n    loss = F.kl_div(\n        F.log_softmax(student_logits, dim=-1),\n        F.softmax(avg_teacher_logits, dim=-1),\n        reduction='batchmean'\n    )\n\n    return loss\n```\n\n## Production Deployment\n\n### Complete Training Script\n\n```python\nfrom transformers import Trainer, TrainingArguments, DataCollatorForLanguageModeling\n\ndef train_distilled_model(\n    teacher_name=\"meta-llama\u002FLlama-2-70b-hf\",\n    student_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    output_dir=\".\u002Fdistilled-llama-7b\",\n    temperature=2.0,\n    alpha=0.7,\n):\n    # Load models\n    teacher = AutoModelForCausalLM.from_pretrained(teacher_name, torch_dtype=torch.float16, device_map=\"auto\")\n    student = AutoModelForCausalLM.from_pretrained(student_name, torch_dtype=torch.float16)\n    tokenizer = AutoTokenizer.from_pretrained(teacher_name)\n\n    # Custom trainer with distillation\n    class DistillationTrainer(Trainer):\n        def compute_loss(self, model, inputs, return_outputs=False):\n            # Student forward\n            outputs_student = model(**inputs)\n            student_logits = outputs_student.logits\n\n            # Teacher forward (no grad)\n            with torch.no_grad():\n                outputs_teacher = teacher(**inputs)\n                teacher_logits = outputs_teacher.logits\n\n            # Distillation loss\n            soft_targets = F.softmax(teacher_logits \u002F temperature, dim=-1)\n            soft_student = F.log_softmax(student_logits \u002F temperature, dim=-1)\n            soft_loss = F.kl_div(soft_student, soft_targets, reduction='batchmean') * (temperature ** 2)\n\n            # Hard loss\n            hard_loss = outputs_student.loss\n\n            # Combined\n            loss = alpha * soft_loss + (1 - alpha) * hard_loss\n\n            return (loss, outputs_student) if return_outputs else loss\n\n    # Training arguments\n    training_args = TrainingArguments(\n        output_dir=output_dir,\n        num_train_epochs=3,\n        per_device_train_batch_size=4,\n        gradient_accumulation_steps=8,\n        learning_rate=2e-5,\n        warmup_steps=500,\n        logging_steps=100,\n        save_steps=1000,\n        bf16=True,\n        gradient_checkpointing=True,\n    )\n\n    # Train\n    trainer = DistillationTrainer(\n        model=student,\n        args=training_args,\n        train_dataset=train_dataset,\n        data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),\n    )\n\n    trainer.train()\n    student.save_pretrained(output_dir)\n    tokenizer.save_pretrained(output_dir)\n\n# Usage\ntrain_distilled_model(\n    teacher_name=\"meta-llama\u002FLlama-2-70b-hf\",\n    student_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    temperature=2.0,\n    alpha=0.7\n)\n```\n\n## Best Practices\n\n### 1. Hyperparameter Selection\n\n```python\n# Temperature\nT = 1.0  # Sharp (less knowledge transfer)\nT = 2.0  # Standard (good balance)\nT = 5.0  # Soft (more knowledge transfer)\n\n# Alpha (weight)\nalpha = 0.5  # Balanced\nalpha = 0.7  # Emphasize teacher knowledge\nalpha = 0.9  # Strong distillation\n\n# Rule: Higher T + higher alpha = stronger distillation\n```\n\n### 2. Model Size Ratio\n\n```python\n# Good ratios (teacher\u002Fstudent)\n70B \u002F 7B = 10×    # Excellent\n13B \u002F 1B = 13×    # Good\n7B \u002F 1B = 7×      # Acceptable\n\n# Avoid too large gap\n70B \u002F 1B = 70×    # Too large, ineffective\n```\n\n### 3. Data Quality\n\n```python\n# Best: Use teacher-generated data + real data\ntrain_data = {\n    \"teacher_generated\": 70%,  # Diverse, high-quality\n    \"real_data\": 30%            # Ground truth\n}\n\n# Avoid: Only real data (doesn't utilize teacher fully)\n```\n\n## Evaluation\n\n```python\nfrom transformers import pipeline\n\n# Compare student vs teacher\nteacher_pipe = pipeline(\"text-generation\", model=teacher)\nstudent_pipe = pipeline(\"text-generation\", model=student)\n\nprompts = [\"Explain quantum computing:\", \"What is AI?\"]\n\nfor prompt in prompts:\n    teacher_out = teacher_pipe(prompt, max_new_tokens=100)\n    student_out = student_pipe(prompt, max_new_tokens=100)\n\n    print(f\"Prompt: {prompt}\")\n    print(f\"Teacher: {teacher_out[0]['generated_text']}\")\n    print(f\"Student: {student_out[0]['generated_text']}\")\n    print(f\"Match quality: {calculate_similarity(teacher_out, student_out):.2f}\")\n```\n\n## Resources\n\n- **Hinton et al. 2015 (Foundational)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F1503.02531\n- **MiniLLM (Reverse KLD)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2306.08543\n- **KD Survey for LLMs (2024)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2402.13116\n- **MiniLLM GitHub**: https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FLMOps\u002Ftree\u002Fmain\u002Fminillm\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm GPU memory, model checkpoint and licence, framework versions and input formats.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Run inference on a single sample at low resolution or short length first.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Inspect outputs qualitatively and with task metrics; check licence restrictions for generated content.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Out-of-memory on large inputs | Reduce resolution or sequence length, use half precision, or tile the input. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Check model and dataset licences before commercial or published use.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `speculative-decoding`: Accelerate LLM inference using speculative decoding, Medusa multiple heads, and lookahead decoding techniques.\n- `model-merging`: Merge multiple fine-tuned models using mergekit to combine capabilities without retraining.\n","# Knowledge Distillation: Compressing LLMs\n\n## When to Use This Skill\n\nUse Knowledge Distillation when you need to:\n- **Compress models** from 70B → 7B while retaining 90%+ performance\n- **Transfer capabilities** from proprietary models (GPT-4) to open-source (LLaMA, Mistral)\n- **Reduce inference costs** by deploying smaller student models\n- **Create specialized models** by distilling domain-specific knowledge\n- **Improve small models** using synthetic data from large teachers\n\n**Key Techniques**: Temperature scaling, soft targets, reverse KLD (MiniLLM), logit distillation, response distillation\n\n**Papers**: Hinton et al. 2015 (arXiv 1503.02531), MiniLLM (arXiv 2306.08543), KD Survey (arXiv 2402.13116)\n\n## Installation\n\n```bash\n# Standard transformers\npip install transformers datasets accelerate\n\n# For training\npip install torch deepspeed wandb\n\n# Optional: MiniLLM implementation\ngit clone https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FLMOps\ncd LMOps\u002Fminillm\npip install -e .\n```\n\n## Quick Start\n\n### Basic Knowledge Distillation\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments\n\n# 1. Load teacher (large) and student (small) models\nteacher = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-70b-hf\",  # Large teacher\n    torch_dtype=torch.float16,\n    device_map=\"auto\"\n)\n\nstudent = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",  # Small student\n    torch_dtype=torch.float16,\n    device_map=\"cuda:0\"\n)\n\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-70b-hf\")\n\n# 2. Define distillation loss\ndef distillation_loss(student_logits, teacher_logits, labels, temperature=2.0, alpha=0.5):\n    \"\"\"\n    Combine hard loss (cross-entropy) with soft loss (KL divergence).\n\n    Args:\n        temperature: Softens probability distributions (higher = softer)\n        alpha: Weight for distillation loss (1-alpha for hard loss)\n    \"\"\"\n    # Hard loss: Standard cross-entropy with true labels\n    hard_loss = F.cross_entropy(student_logits.view(-1, student_logits.size(-1)), labels.view(-1))\n\n    # Soft loss: KL divergence between student and teacher\n    soft_targets = F.softmax(teacher_logits \u002F temperature, dim=-1)\n    soft_student = F.log_softmax(student_logits \u002F temperature, dim=-1)\n    soft_loss = F.kl_div(soft_student, soft_targets, reduction='batchmean') * (temperature ** 2)\n\n    # Combined loss\n    return alpha * soft_loss + (1 - alpha) * hard_loss\n\n# 3. Training loop\nfor batch in dataloader:\n    # Teacher forward (no grad)\n    with torch.no_grad():\n        teacher_outputs = teacher(**batch)\n        teacher_logits = teacher_outputs.logits\n\n    # Student forward\n    student_outputs = student(**batch)\n    student_logits = student_outputs.logits\n\n    # Compute distillation loss\n    loss = distillation_loss(\n        student_logits,\n        teacher_logits,\n        batch['labels'],\n        temperature=2.0,\n        alpha=0.7  # 70% soft, 30% hard\n    )\n\n    # Backward and optimize\n    loss.backward()\n    optimizer.step()\n    optimizer.zero_grad()\n```\n\n### MiniLLM (Reverse KLD)\n\n**Source**: arXiv 2306.08543 (2024)\n\n**Innovation**: Use reverse KLD instead of forward KLD for better generative model distillation.\n\n```python\ndef reverse_kl_loss(student_logits, teacher_logits, temperature=1.0):\n    \"\"\"\n    Reverse KL divergence: KL(Teacher || Student)\n    Better for generative models than forward KL.\n    \"\"\"\n    # Teacher distribution (target)\n    p_teacher = F.softmax(teacher_logits \u002F temperature, dim=-1)\n\n    # Student distribution (model)\n    log_p_student = F.log_softmax(student_logits \u002F temperature, dim=-1)\n\n    # Reverse KL: Sum over teacher, student learns to cover teacher's modes\n    reverse_kl = -(p_teacher * log_p_student).sum(dim=-1).mean()\n\n    return reverse_kl * (temperature ** 2)\n\n# Training with MiniLLM\nfor batch in dataloader:\n    with torch.no_grad():\n        teacher_logits = teacher(**batch).logits\n\n    student_logits = student(**batch).logits\n\n    # Reverse KLD (better for generation)\n    loss = reverse_kl_loss(student_logits, teacher_logits, temperature=1.0)\n\n    loss.backward()\n    optimizer.step()\n```\n\n**Why reverse KL?**\n- **Forward KL** (standard): Student learns to match teacher's *mean*\n- **Reverse KL** (MiniLLM): Student learns to *cover* all teacher's modes\n- Better for diverse text generation\n\n### Response Distillation\n\n```python\n# Generate synthetic data from teacher, train student to imitate\n\n# 1. Generate synthetic responses from teacher\nprompts = [\"Explain AI:\", \"What is ML?\", \"Define NLP:\"]\n\nteacher_responses = []\nfor prompt in prompts:\n    inputs = tokenizer(prompt, return_tensors='pt').to(teacher.device)\n    outputs = teacher.generate(**inputs, max_new_tokens=256, do_sample=True, temperature=0.7)\n    response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n    teacher_responses.append(response)\n\n# 2. Train student on teacher's responses (standard fine-tuning)\ntrain_dataset = [\n    {\"text\": f\"{prompt}\\n{response}\"}\n    for prompt, response in zip(prompts, teacher_responses)\n]\n\n# 3. Fine-tune student\ntrainer = Trainer(\n    model=student,\n    args=TrainingArguments(output_dir=\".\u002Fstudent\", num_train_epochs=3, learning_rate=2e-5),\n    train_dataset=train_dataset,\n)\ntrainer.train()\n```\n\n## Core Concepts\n\n### 1. Temperature Scaling\n\n**Purpose**: Soften probability distributions to expose teacher's uncertainty.\n\n```python\n# Low temperature (T=1): Sharp distribution\nlogits = [3.0, 2.0, 1.0]\nprobs_T1 = softmax(logits \u002F 1.0)  # [0.67, 0.24, 0.09]\n\n# High temperature (T=4): Soft distribution\nprobs_T4 = softmax(logits \u002F 4.0)  # [0.42, 0.34, 0.24]\n\n# Higher T reveals more information about relative rankings\n```\n\n**Rule**: Use T=2-5 for distillation (2 is common default).\n\n### 2. Loss Function Components\n\n```python\n# Total loss = alpha * soft_loss + (1 - alpha) * hard_loss\n\n# Soft loss: Learn from teacher's knowledge\nsoft_loss = KL(student || teacher)\n\n# Hard loss: Learn from ground truth labels\nhard_loss = CrossEntropy(student_output, true_labels)\n\n# Typical values:\nalpha = 0.5  # Balanced\nalpha = 0.7  # More emphasis on teacher\nalpha = 0.3  # More emphasis on labels\n```\n\n### 3. Forward vs Reverse KLD\n\n```python\n# Forward KL: KL(Student || Teacher)\n# - Student matches teacher's average behavior\n# - Mode-seeking: Student focuses on teacher's highest probability modes\n# - Good for classification\n\n# Reverse KL: KL(Teacher || Student)\n# - Student covers all of teacher's behaviors\n# - Mode-covering: Student learns diverse behaviors\n# - Good for generation (MiniLLM)\n```\n\n## Training Strategies\n\n### Strategy 1: Logit Distillation\n\n```python\n# Train student to match teacher's logits directly\n\ndef logit_distillation_trainer(student, teacher, dataloader, temperature=2.0):\n    optimizer = torch.optim.AdamW(student.parameters(), lr=2e-5)\n\n    for epoch in range(3):\n        for batch in dataloader:\n            # Get logits\n            with torch.no_grad():\n                teacher_logits = teacher(**batch).logits\n\n            student_logits = student(**batch).logits\n\n            # MSE on logits (alternative to KLD)\n            loss = F.mse_loss(student_logits, teacher_logits)\n\n            # Or use KLD\n            # loss = F.kl_div(\n            #     F.log_softmax(student_logits\u002Ftemperature, dim=-1),\n            #     F.softmax(teacher_logits\u002Ftemperature, dim=-1),\n            #     reduction='batchmean'\n            # ) * (temperature ** 2)\n\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n\n    return student\n```\n\n### Strategy 2: Two-Stage Distillation\n\n```python\n# Stage 1: Distill from teacher\nstudent = distill(teacher, student, epochs=5)\n\n# Stage 2: Fine-tune on task-specific data\nstudent = fine_tune(student, task_data, epochs=3)\n\n# Results in better task performance than single-stage\n```\n\n### Strategy 3: Multi-Teacher Distillation\n\n```python\n# Learn from multiple expert teachers\n\ndef multi_teacher_distillation(student, teachers, batch):\n    \"\"\"Distill from ensemble of teachers.\"\"\"\n    teacher_logits_list = []\n\n    # Get logits from all teachers\n    with torch.no_grad():\n        for teacher in teachers:\n            logits = teacher(**batch).logits\n            teacher_logits_list.append(logits)\n\n    # Average teacher predictions\n    avg_teacher_logits = torch.stack(teacher_logits_list).mean(dim=0)\n\n    # Student learns from ensemble\n    student_logits = student(**batch).logits\n    loss = F.kl_div(\n        F.log_softmax(student_logits, dim=-1),\n        F.softmax(avg_teacher_logits, dim=-1),\n        reduction='batchmean'\n    )\n\n    return loss\n```\n\n## Production Deployment\n\n### Complete Training Script\n\n```python\nfrom transformers import Trainer, TrainingArguments, DataCollatorForLanguageModeling\n\ndef train_distilled_model(\n    teacher_name=\"meta-llama\u002FLlama-2-70b-hf\",\n    student_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    output_dir=\".\u002Fdistilled-llama-7b\",\n    temperature=2.0,\n    alpha=0.7,\n):\n    # Load models\n    teacher = AutoModelForCausalLM.from_pretrained(teacher_name, torch_dtype=torch.float16, device_map=\"auto\")\n    student = AutoModelForCausalLM.from_pretrained(student_name, torch_dtype=torch.float16)\n    tokenizer = AutoTokenizer.from_pretrained(teacher_name)\n\n    # Custom trainer with distillation\n    class DistillationTrainer(Trainer):\n        def compute_loss(self, model, inputs, return_outputs=False):\n            # Student forward\n            outputs_student = model(**inputs)\n            student_logits = outputs_student.logits\n\n            # Teacher forward (no grad)\n            with torch.no_grad():\n                outputs_teacher = teacher(**inputs)\n                teacher_logits = outputs_teacher.logits\n\n            # Distillation loss\n            soft_targets = F.softmax(teacher_logits \u002F temperature, dim=-1)\n            soft_student = F.log_softmax(student_logits \u002F temperature, dim=-1)\n            soft_loss = F.kl_div(soft_student, soft_targets, reduction='batchmean') * (temperature ** 2)\n\n            # Hard loss\n            hard_loss = outputs_student.loss\n\n            # Combined\n            loss = alpha * soft_loss + (1 - alpha) * hard_loss\n\n            return (loss, outputs_student) if return_outputs else loss\n\n    # Training arguments\n    training_args = TrainingArguments(\n        output_dir=output_dir,\n        num_train_epochs=3,\n        per_device_train_batch_size=4,\n        gradient_accumulation_steps=8,\n        learning_rate=2e-5,\n        warmup_steps=500,\n        logging_steps=100,\n        save_steps=1000,\n        bf16=True,\n        gradient_checkpointing=True,\n    )\n\n    # Train\n    trainer = DistillationTrainer(\n        model=student,\n        args=training_args,\n        train_dataset=train_dataset,\n        data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),\n    )\n\n    trainer.train()\n    student.save_pretrained(output_dir)\n    tokenizer.save_pretrained(output_dir)\n\n# Usage\ntrain_distilled_model(\n    teacher_name=\"meta-llama\u002FLlama-2-70b-hf\",\n    student_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    temperature=2.0,\n    alpha=0.7\n)\n```\n\n## Best Practices\n\n### 1. Hyperparameter Selection\n\n```python\n# Temperature\nT = 1.0  # Sharp (less knowledge transfer)\nT = 2.0  # Standard (good balance)\nT = 5.0  # Soft (more knowledge transfer)\n\n# Alpha (weight)\nalpha = 0.5  # Balanced\nalpha = 0.7  # Emphasize teacher knowledge\nalpha = 0.9  # Strong distillation\n\n# Rule: Higher T + higher alpha = stronger distillation\n```\n\n### 2. Model Size Ratio\n\n```python\n# Good ratios (teacher\u002Fstudent)\n70B \u002F 7B = 10×    # Excellent\n13B \u002F 1B = 13×    # Good\n7B \u002F 1B = 7×      # Acceptable\n\n# Avoid too large gap\n70B \u002F 1B = 70×    # Too large, ineffective\n```\n\n### 3. Data Quality\n\n```python\n# Best: Use teacher-generated data + real data\ntrain_data = {\n    \"teacher_generated\": 70%,  # Diverse, high-quality\n    \"real_data\": 30%            # Ground truth\n}\n\n# Avoid: Only real data (doesn't utilize teacher fully)\n```\n\n## Evaluation\n\n```python\nfrom transformers import pipeline\n\n# Compare student vs teacher\nteacher_pipe = pipeline(\"text-generation\", model=teacher)\nstudent_pipe = pipeline(\"text-generation\", model=student)\n\nprompts = [\"Explain quantum computing:\", \"What is AI?\"]\n\nfor prompt in prompts:\n    teacher_out = teacher_pipe(prompt, max_new_tokens=100)\n    student_out = student_pipe(prompt, max_new_tokens=100)\n\n    print(f\"Prompt: {prompt}\")\n    print(f\"Teacher: {teacher_out[0]['generated_text']}\")\n    print(f\"Student: {student_out[0]['generated_text']}\")\n    print(f\"Match quality: {calculate_similarity(teacher_out, student_out):.2f}\")\n```\n\n## Resources\n\n- **Hinton et al. 2015 (Foundational)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F1503.02531\n- **MiniLLM (Reverse KLD)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2306.08543\n- **KD Survey for LLMs (2024)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2402.13116\n- **MiniLLM GitHub**: https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FLMOps\u002Ftree\u002Fmain\u002Fminillm\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm GPU memory, model checkpoint and licence, framework versions and input formats.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Run inference on a single sample at low resolution or short length first.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Inspect outputs qualitatively and with task metrics; check licence restrictions for generated content.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Out-of-memory on large inputs | Reduce resolution or sequence length, use half precision, or tile the input. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Check model and dataset licences before commercial or published use.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `speculative-decoding`: Accelerate LLM inference using speculative decoding, Medusa multiple heads, and lookahead decoding techniques.\n- `model-merging`: Merge multiple fine-tuned models using mergekit to combine capabilities without retraining.\n",{"name":5,"license":15,"metadata":49,"description":7},{"tags":50,"version":51,"category":52,"maintainer":53,"dependencies":54},"Emerging Techniques, Knowledge Distillation, Model Compression, Teacher-Student, MiniLLM, Reverse KLD, Soft Targets, Temperature Scaling, Logit Distillation, Model Transfer","1.0.0","multimodal-and-emerging","Kalaris Labs","transformers, torch, datasets","main","0da4485785ee599388900be50db1635489d53056",".agents\u002Fskills\u002Fkal-knowledge-distillation","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6","https:\u002F\u002Fdisha6.6.thenitishkr.in\u002F","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh","www.thenitishkr","thenitishkr | AI • Cyber-security • Research\r\n","2026-11-08 03:33:25",{"source":8,"skillName":5,"commands":65,"prompt":75,"zipAvailable":76},[66,69,72],{"tool":67,"command":68},"npx","npx skills add Tashima-Tarsh\u002FDisha6.6 --skill knowledge-distillation",{"tool":70,"command":71},"bunx","bunx skills add Tashima-Tarsh\u002FDisha6.6 --skill knowledge-distillation",{"tool":73,"command":74},"pnpm","pnpm dlx skills add Tashima-Tarsh\u002FDisha6.6 --skill knowledge-distillation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-knowledge-distillation\u002FSKILL.md",true,[78],{"path":79,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fminillm.md","REFERENCE","参考文档",9117,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-knowledge-distillation\u002Freferences\u002Fminillm.md",[85,115,140,167,192,216],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":94,"publishedAt":44},"01M6QRD07D4TGNDK6VJ4EHF8BV","youtube-full","Use when the user needs YouTube transcripts, video search, channel browsing, playlist extraction, or content monitoring. Trigger phrases: 'get the transcript for', 'search YouTube for', 'what are the latest videos on', 'list this playlist', 'monitor this channel', or any request involving a YouTube URL, video ID, or @handle. Do NOT use for downloading video or audio files, YouTube engagement data (likes, comments), or private\u002Fage-restricted videos.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fyoutube-full\u002FSKILL.md",[91],{"categoryNo":92,"categoryName":93,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",[95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114],"youtube full","youtube","full","transcript","search","monitoring","data","Video","Audio","list","files","do","get","age","trigger","URL","for","browsing","request","youtube transcripts",{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":44},"01M6QRCJ3112VYPA97YG7KGMC2","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[122,123,124,125,99,126,127,128,129,130,131,132,133,134,135,136,137,138,139,111],"twitter","x twitter growth","growth","research","content","engineering","plan","web search","competitors","analyze","engine","write","strategy","use","platform","grow","posting","competitive",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":149,"publishedAt":44},"01M6QRBN3EHQNJY42RERP7A149","write-a-skill","Create new agent skills with proper structure, progressive disclosure, and bundled resources. Use when user wants to create, write, build, or author a new skill.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrite-a-skill\u002FSKILL.md",[146],{"categoryNo":147,"categoryName":148,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[150,133,151,152,153,154,155,156,135,157,158,55,159,160,161,162,163,164,165,166],"write a skill","github","create","https","productivity","matt pocock","direct","example","build","new skill","structure","new agent","resources","with","tree","progressive disclosure","author",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":173,"publishedAt":44},"01M6QRB6G8P33PNGAF9Y69EJ9T","wrap-up","Close out a launched Claude Managed Agent — recap every primitive the founder now owns, regenerate the single-file overview page, and suggest the next 1-2 upgrades. Use when the user says \"wrap up\", \"close this out\", \"what do I own now\", \"give me the summary\", \"recap the agent\", or when the orchestrator routes phase=wrap-up. primitives_inventory.py tables everything owned (agent, environment, session, memory, outcome, deployment); overview_page.py regenerates a self-contained .\u002Fmy-agent\u002Fagent-overview.html; upgrade_suggester.py ranks the next moves from recorded deferrals plus standing hardening steps. Companion to run-without-you; the last stop before phase=done.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrap-up\u002FSKILL.md",[],[174,175,176,177,178,179,180,181,182,135,183,106,184,185,186,187,188,189,190,191],"wrap up","up","wrap","gemini","deployment","run","file","hardening","closeout","stop","upgrade","founder","close","companion","you","tables","directions","phase",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":199,"publishedAt":44},"01M6QRA5AYC1RBFZ39GTWGS3N8","workflow-builder","Design and write deterministic multi-agent workflow scripts (.js files in .claude\u002Fworkflows\u002F) for Claude Code's Workflow tool. Use when a user wants to build, create, author, scaffold, or run a custom Claude Code workflow, orchestrate sub-agents (fan-out, pipeline, loop, judge-panel), or automate a repeatable multi-step task across fresh-context agents.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkflow-builder\u002FSKILL.md",[198],{"categoryNo":147,"categoryName":148,"taxonomyType":21,"taxonomyTypeDesc":22},[200,201,202,203,204,152,179,205,206,207,208,209,133,210,105,211,212,213,214,215],"workflow","workflow builder","builder","design","workflows","code","orchestrate","pipeline","loop","multi-agent","context","across","fresh","scripts","judge","claude code workflow",{"skillNo":217,"name":218,"nameZh":6,"description":219,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":220,"categories":221,"keywords":222,"publishedAt":44},"01M6QR7QMCZESKQA0ERW1E657M","weekly-review","Use when someone wants to run a weekly review, close open loops, audit stalled projects and commitments, get their system back to trusted, restart a lapsed review habit, or says \"\u002Fcs:weekly-review\". Walks David Allen's three-phase loop — GET CLEAR, GET CURRENT, GET CREATIVE — with deterministic scripts that inventory open loops, gate the checklist with named gaps, and score commitment health 0-100.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fweekly-review\u002FSKILL.md",[],[223,224,225,226,227,228,229,41,230,208,231,232,233,234,235,236,107,237,238,191],"review","weekly review","weekly","deterministic scripts","reflect","feeds","inventory","team","projects","project-management","scanner","conversation","back","project","sprint","cadence"]