[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109339":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":8,"htmlUrl":8,"language":9,"languages":8,"totalLinesOfCode":8,"stars":10,"forks":11,"watchers":12,"openIssues":13,"contributorsCount":13,"subscribersCount":13,"size":13,"stars1d":14,"stars7d":11,"stars30d":15,"stars90d":13,"forks30d":13,"starsTrendScore":16,"compositeScore":17,"rankGlobal":8,"rankLanguage":8,"license":18,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":21,"hasPages":19,"topics":22,"createdAt":8,"pushedAt":23,"updatedAt":24,"readmeContent":25,"aiSummary":26,"trendingCount":13,"starSnapshotCount":13,"syncStatus":11,"lastSyncTime":27,"discoverSource":28},109339,"LM-KD","phongdq25\u002FLM-KD","phongdq25",null,"Python",90,2,72,0,1,18,4,43.23,"Apache License 2.0",false,"main",true,[],"2026-11-14 14:34:41","2026-11-23 15:44:38","\u003Cdiv align=\"center\">\n\n# LM-KD\n\n**A unified, modular toolkit for Language Model Knowledge Distillation**\n\nReproducible benchmarking and rapid prototyping of distillation and alignment methods for LLMs, from a single hardware-efficient runtime.\n\n![Python](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython-3.11-blue)\n![PyTorch](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPyTorch-2.9%2B-ee4c2c?logo=pytorch&logoColor=white)\n![Backends](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fbackends-DeepSpeed%20%7C%20FSDP2%20%7C%20vLLM-orange)\n![Lint](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fcode%20style-ruff-261230)\n[![License](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-Apache--2.0-green.svg)](LICENSE)\n[![Paper](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FarXiv-Survey%20Paper-b31b1b.svg)](#citation)\n\n[Documentation](official_docs\u002Findex.md) · [Quickstart](official_docs\u002Fgetting-started\u002Fquickstart.md) · [Methods](official_docs\u002Fmethods\u002Findex.md) · [Scenarios & Baselines](official_docs\u002Fscenarios\u002Findex.md) · [Results](official_docs\u002Fresults\u002Fleaderboards.md) · [Contributing](official_docs\u002Fcontributing\u002Findex.md)\n\n\u003C\u002Fdiv>\n\n---\n\n## Table of Contents\n\n\u003Ctable width=\"100%\">\n\u003Ctr>\n\u003Ctd valign=\"top\" width=\"33%\">\n\n- [Overview](#overview)\n- [Key Features](#key-features)\n- [Taxonomy & Supported Methods](#taxonomy--supported-methods)\n- [Experimental Scenarios](#experimental-scenarios)\n- [Installation](#installation)\n\n\u003C\u002Ftd>\n\u003Ctd valign=\"top\" width=\"33%\">\n\n- [Quickstart](#quickstart)\n- [Recipes & Configuration](#recipes--configuration)\n- [Extending LM-KD](#extending-lm-kd)\n- [Architecture](#architecture)\n- [Repository Structure](#repository-structure)\n\n\u003C\u002Ftd>\n\u003Ctd valign=\"top\" width=\"33%\">\n\n- [Evaluation](#evaluation)\n- [Documentation](#documentation)\n- [Contributing](#contributing)\n- [Citation](#citation)\n- [License](#license)\n- [Acknowledgements](#acknowledgements)\n\n\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftable>\n\n---\n\n## Overview\n\n> **Companion toolkit of a survey.** LM-KD is the open-source implementation and benchmarking toolkit that accompanies the survey ***Knowledge Distillation for Large Language Models: A Survey of Training Contexts and Supervision***. The survey introduces the taxonomy used in this README, and LM-KD provides the implementations of the surveyed methods together with the seven benchmark scenarios discussed in the paper (see [Experimental Scenarios](#experimental-scenarios)).\n\nKnowledge distillation (KD) for LLMs has moved far beyond classical logit matching: it now covers cross-tokenizer transfer, long chain-of-thought compression, on-policy self-distillation, preference distillation and iterative self-play. Research in this space is often fragmented:\n\n- **Disparate codebases.** Methods live in bespoke forks of TRL, LLaMA-Factory, verl, Megatron, etc., so it is unclear whether gains come from the algorithm or from hidden engineering details (padding masks, warmups, accumulation denominators).\n- **GPU memory explosions.** Large vocabularies (V ≥ 128k) trigger OOM when logits are materialized over long contexts.\n- **Incompatible interfaces.** Comparing token-level, sequence-level and representation-level losses usually means rewriting the training loop.\n\n**LM-KD** addresses this with a single runtime built around one universal batch contract, a plugin registry, declarative YAML recipes and centralized, distributed-safe loss normalization. Every distillation run is decomposed along **six orthogonal axes**, so changing one component (e.g. the loss, the teacher, or the context source) does not require touching the others.\n\n## Key Features\n\n- **Unified plugin registry.** Implement a loss, teacher provider, dataset, aligner, optimizer or evaluator in a standalone Python file and register it with a single decorator, with no core changes.\n- **Declarative recipes.** Experiments are YAML files with `_base_` inheritance, Pydantic schema validation and CLI dot-key overrides.\n- **Target-aligned lazy chunking (`LogitsView`).** Divergences are computed over streamed sequence chunks, so the full `[Batch, Length, Vocab]` tensor is never materialized (documented peak-memory reduction of over 60%).\n- **Centralized global token normalization.** Loss numerators are divided by the exact global count of supervised tokens (`num_items_in_batch`) across micro-batches and ranks, so gradients are numerically identical regardless of batch size, accumulation steps or GPU count.\n- **Flexible teachers.** Local Hugging Face teachers (incl. 4\u002F8-bit quantized), precomputed top-K logit caches, remote API teachers, and EMA \u002F lagged self-teachers.\n- **On-policy rollouts.** Colocated or server-mode **vLLM**, plus a Hugging Face generation fallback and Ray-based decoupled rollouts.\n- **Distributed first.** DeepSpeed ZeRO-1\u002F2\u002F3, PyTorch FSDP2, FlashAttention-2 and attention-isolated sequence packing.\n- **Cross-tokenizer tooling.** Built-in aligners (`dtw_edit`, `parent_groups`, `exact_token`), learnable projectors and optimal-transport losses.\n- **PEFT support.** LoRA \u002F QLoRA through Hugging Face PEFT.\n- **Offline teacher caching.** Precompute teacher logits once; the docs report 3.5x to 8x faster training with zero teacher memory.\n- **Developer experience.** `lmkd try`, `lmkd check`, `lmkd config`, `lmkd explain`, `lmkd list` and `lmkd new` for fast iteration and scaffolding.\n\n## Taxonomy & Supported Methods\n\nLM-KD organizes distillation methods by one question: **where does the training context come from?** In an autoregressive model every token is predicted from a prefix, and the teacher's signal can be applied to prefixes taken from a reference corpus, from an external model's answers, or from sequences generated by the student itself. Knowing the teacher or the loss does not tell you which contexts the student actually learns on, so the taxonomy classifies each training configuration by the **origin and version of its training context**.\n\n```text\nTaxonomy by Training Context Source\n├── 1. External Supervision\n│   ├── 1.1. Reference text only\n│   │   ├── 1.1.1. Autoregressive generation on reference prefixes\n│   │   └── 1.1.2. Text embedding and dense retrieval\n│   └── 1.2. Text generated by external models\n├── 2. Current-policy Supervision\n│   ├── 2.1. Non-interactive rollouts\n│   └── 2.2. Environment-interactive rollouts\n├── 3. Lagged-policy Supervision\n│   ├── 3.1. Data from a single student checkpoint\n│   └── 3.2. Data from multiple student checkpoints\n└── 4. Mixed-policy Supervision\n    ├── 4.1. Mixing samples across sources\n    ├── 4.2. Combining sources within the generation history\n    └── 4.3. Staged source transitions\n```\n\n| Branch | Training context comes from | Methods in LM-KD |\n| :--- | :--- | :--- |\n| **1. External Supervision** | A reference corpus or text written by external models; no student rollouts | **Same-tokenizer logit KD:** FKL, RKL, JSD, TVD, SFKL, SRKL\u003Cbr>**Cross-tokenizer KD:** DSKD, DSKDv2, DSKD-CMA, DSKDv2-ETA, ULD, MinED, MultiLevelOT, E-SCOT, ALM, SRA, MCW-KD, ResidualKD, DWA-KD\u003Cbr>**Long-CoT reasoning:** SSFT, P-ALIGN, SGL-Spectral\u003Cbr>**Preference distillation:** VPD (PAD), PPD, DCKD, TVKD, ADPA, CTPD, DP3O, PBSD\u003Cbr>**Embedding distillation:** TALAS, DistillCSE, EMO, Jasper, MoL |\n| **2. Current-policy Supervision** | Rollouts generated by the exact student version that is about to be updated | **On-policy self-distillation:** OPSD, SDPO, RLSD |\n| **3. Lagged-policy Supervision** | Student-generated data that is used after the student's parameters have changed | **Self-play fine-tuning:** SPIN, T-SPIN, SPACE, SPPO, S-SPPO, RSPO |\n| **4. Mixed-policy Supervision** | External text combined with student rollouts | CSD, DistiLLM, GKD, FDD, AMiD, MTA |\n\n> **Classification unit.** The taxonomy classifies a concrete *training configuration*, not an algorithm name. The same method can fall into different branches depending on how it is run (for example, GKD can be external, current-policy or mixed depending on its mixing ratio). The table lists each method under the branch of the configuration evaluated in LM-KD.\n>\n> The taxonomy answers *\"which contexts does the student learn on?\"*, not *\"which loss is optimized?\"*. Methods with very different losses can share a branch, and one family can span several branches (for example, the same-tokenizer methods are split between External and Mixed). MTA is classified under Mixed, including when it is combined with a cross-tokenizer base method. Method families remain the unit of documentation: formulations, pseudocode and recipes are grouped by family in the [Methods Catalog](official_docs\u002Fmethods\u002Findex.md), and the concepts are explained in [Taxonomy of LLM Knowledge Distillation](official_docs\u002Fconcepts\u002Ftaxonomy.md). For primary source publications, authors, and conference links across all 49+ baselines, see the [Scenarios & Baseline Registry](official_docs\u002Fscenarios\u002Findex.md#baseline-methods--paper-registry).\n\n**Method families and their docs**\n\n| Family | Methods and recipes |\n| :--- | :--- |\n| Same-Tokenizer KD | [Methods](official_docs\u002Fmethods\u002Fsame-tokenizer.md) · `recipes\u002Fsame_tokenizer\u002F` |\n| Cross-Tokenizer KD | [Methods](official_docs\u002Fmethods\u002Fcross-tokenizer.md) · `recipes\u002Fcross_tokenizer\u002F` |\n| Long-CoT Reasoning | [Methods](official_docs\u002Fmethods\u002Flong-cot.md) · `recipes\u002Flong_cot\u002F` |\n| On-Policy Self-Distillation | [Methods](official_docs\u002Fmethods\u002Fon-policy-self-distill.md) · `recipes\u002Fself_distill\u002F` |\n| Preference Distillation | [Methods](official_docs\u002Fmethods\u002Fpreference-distill.md) · `recipes\u002Fpreference\u002F` |\n| Embedding Distillation | [Methods](official_docs\u002Fmethods\u002Fembedding-distill.md) · `recipes\u002Fembedding\u002F` |\n| Self-Play Fine-Tuning | [Methods](official_docs\u002Fmethods\u002Fself-play.md) · `recipes\u002Fself_play\u002F` |\n\n## Experimental Scenarios\n\nScenarios are a separate axis from the taxonomy. A **scenario** is a standardized benchmark setting: a fixed set of teacher\u002Fstudent pairs, training data, evaluation benchmarks and metrics shared by every method that competes in it. The taxonomy describes *how a method obtains its training context*; a scenario describes *what the method is evaluated on*. Each scenario page contains the full protocol and its results table; all tables are compiled in the [Master Leaderboards](official_docs\u002Fresults\u002Fleaderboards.md).\n\n| # | Scenario | Teacher → Student pairs | Training data → evaluation | Details |\n| :-: | :--- | :--- | :--- | :--- |\n| 1 | **Sentence embedding distillation** | Qwen3-Embedding-0.6B → MiniLMv2-L6, BGE-M3 → MiniLMv2-L12, Qwen3-Embedding-4B → BERT-base | AllNLI, Wikipedia → 9 MTEB tasks (classification, pair classification, STS) | [Scenario 1](official_docs\u002Fscenarios\u002F1-sentence-embedding.md) |\n| 2 | **Same-tokenizer instruction distillation** | GPT-2 (1.5B → 120M), Qwen1.5 (1.8B → 0.5B), OPT (6.7B → 1.3B) | Dolly-15k → Dolly, Self-Instruct, Vicuna, Super-NaturalInstructions (ROUGE-L) | [Scenario 2](official_docs\u002Fscenarios\u002F2-same-tokenizer.md) |\n| 3 | **Cross-tokenizer distillation** | Qwen1.5-1.8B → GPT-2 120M and 0.4B; Qwen2.5-7B → GPT-2 1.5B and OPT-2.7B; Mistral-7B → TinyLLaMA-1.1B | Dolly-15k → Dolly, Self-Instruct, Vicuna, Super-NaturalInstructions (ROUGE-L) | [Scenario 3](official_docs\u002Fscenarios\u002F3-cross-tokenizer.md) |\n| 4 | **Long-CoT reasoning distillation** | DeepSeek-R1 → R1-Distill-Qwen-1.5B, Qwen2.5-7B-Instruct, Qwen3-8B | s1K-1.1 → AIME 2024\u002F2025, AMC 12, MATH-500 (pass@1, pass@3) | [Scenario 4](official_docs\u002Fscenarios\u002F4-long-cot.md) |\n| 5 | **On-policy self-distillation for reasoning** | Qwen3-8B, Olmo3-7B-Think, Qwen3-4B (no external teacher) | GSM8K, MATH, NuminaMath-CoT → AIME 2025, AIME 2026, HMMT 2025 (accuracy) | [Scenario 5](official_docs\u002Fscenarios\u002F5-opsd.md) |\n| 6 | **Reward-model-free preference distillation** | Llama-3.1-8B → Llama-3.2-1B, Qwen3-8B → Qwen3-1.7B, Qwen3-1.7B → Qwen3-0.6B | UltraFeedback Binarized → HellaSwag, ARC, TruthfulQA, Winogrande, GSM8K | [Scenario 6](official_docs\u002Fscenarios\u002F6-preference-distillation.md) |\n| 7 | **Self-play fine-tuning** | Qwen2.5-1.5B, Gemma-2-2B, Qwen3-4B | UltraChat-200k, SPIN_iter0 → GSM8K, MATH, MMLU, MMLU-Pro, HellaSwag, Winogrande, IFEval | [Scenario 7](official_docs\u002Fscenarios\u002F7-self-play-fine-tuning.md) |\n\nBecause the two axes are independent, a scenario can compare methods that sit in different taxonomy branches (for instance, Scenario 5 compares SFT, GRPO and OPSD\u002FRLSD\u002FSDPO), and a taxonomy branch can be evaluated across several scenarios.\n\n## Installation\n\n### Option A: `uv` (recommended)\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fphongdq25\u002FLM-KD.git\ncd LM-KD\n\ncurl -LsSf https:\u002F\u002Fastral.sh\u002Fuv\u002Finstall.sh | sh\nuv venv --python 3.11\nsource .venv\u002Fbin\u002Factivate\nuv pip install -e \".[dev]\"\n```\n\n### Option B: Conda + pip\n\n```bash\nconda create -n lmkd python=3.11 -y\nconda activate lmkd\n\npip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https:\u002F\u002Fdownload.pytorch.org\u002Fwhl\u002Fcu128\n\ncd LM-KD\npip install -e \".[dev]\"\n```\n\n### Optional acceleration backends\n\n```bash\npip install flash-attn --no-build-isolation   # FlashAttention-2 (recommended for context length >= 2048)\n```\n\n### Verify\n\n```bash\nbash scripts\u002Frun_smoke_tests.sh\nbash scripts\u002Frun_baseline.sh --all --check\n```\n\n## Quickstart\n\nA first end-to-end run (Qwen3-0.6B student from Qwen3-4B-Instruct-2507 on Dolly-15k with Forward KL) takes roughly 10 minutes on a single GPU. Full walkthrough: [Quickstart](official_docs\u002Fgetting-started\u002Fquickstart.md).\n\n**1. Sanity-check a loss in seconds (no model or dataset download):**\n\n```bash\nlmkd try fkl\nlmkd try rkl\n```\n\n**2. Inspect and validate a recipe without allocating GPUs:**\n\n```bash\nlmkd config -c recipes\u002Fsame_tokenizer\u002Ffkl.yaml     # print the fully merged config\nlmkd check  -c recipes\u002Fsame_tokenizer\u002Ffkl.yaml     # schema, imports and vocab validation\n```\n\n**3. Train:**\n\n```bash\nlmkd train -c recipes\u002Fsame_tokenizer\u002Ffkl.yaml \\\n    --set train.max_steps=50 \\\n          train.log_every=10 \\\n          train.output_dir=.\u002Foutputs\u002Fquickstart_fkl\n```\n\n**4. Evaluate:**\n\n```bash\nlmkd eval -c recipes\u002Fsame_tokenizer\u002Ffkl.yaml \\\n    --ckpt .\u002Foutputs\u002Fquickstart_fkl\u002Fcheckpoint-50\n```\n\n### Python API\n\n```python\nimport lmkd\n\nrt = lmkd.quick(\n    student=\"Qwen\u002FQwen2.5-0.5B\",\n    teacher=\"Qwen\u002FQwen2.5-1.5B\",\n    data=\"datasets\u002Fsame_cross_tokenizer_data\u002Fdolly\u002Ftrain.jsonl\",\n    loss=\"fkl\",\n    max_steps=100,\n    lr=2e-5,\n    output_dir=\".\u002Foutputs\u002Fquick_fkl\",\n)\nrt.fit()\n```\n\nFor full control, build a `Runtime` and drive the loop yourself:\n\n```python\nrt = lmkd.build(\"recipes\u002Fsame_tokenizer\u002Ffkl.yaml\", overrides=[\"train.max_steps=500\"])\n\nrt.begin()\nwhile not rt.done:\n    out = rt.train_step()                 # micro-batches, all-reduce, optimizer step\n    if rt.state.step % 50 == 0:\n        print(rt.state.step, out.metrics.get(\"loss\u002Ftotal\", 0.0), rt.evaluate())\nrt.end()\nrt.save(\"final_checkpoint\")\n```\n\n### CLI reference\n\n| Command | Purpose |\n| :--- | :--- |\n| `lmkd train -c \u003Crecipe>` | Run distillation |\n| `lmkd eval -c \u003Crecipe> [--ckpt \u003Cpath>]` | Evaluate a checkpoint on benchmark suites |\n| `lmkd config -c \u003Crecipe>` | Print the resolved configuration |\n| `lmkd check -c \u003Crecipe>` | Static validation of a recipe |\n| `lmkd explain -c \u003Crecipe>` | Architectural summary of a recipe |\n| `lmkd try \u003Ccriterion>` | Dry-run a loss on synthetic tensors |\n| `lmkd list [registry]` | List registered plugins and components |\n| `lmkd pipeline -c \u003Crecipe>` | Offline pipelines (e.g. teacher logit caching) |\n| `lmkd init \u003Cname>` | Initialize a complete baseline\u002Fmethod template directory (`dev\u002F` or `src\u002Fbaselines\u002F`) |\n| `lmkd new \u003Ckind> \u003Cname>` | Scaffold a single plugin, test, and recipe |\n\n## Recipes & Configuration\n\nA recipe is a single YAML file describing a whole experiment. Recipes can inherit from base templates via `_base_` and any value can be overridden from the CLI via `--set a.b.c=value`.\n\n```yaml\n# recipes\u002Fsame_tokenizer\u002Ffkl.yaml\nname: fkl_qwen3_0.6b_from_4b\n\nmodels:\n  student:\n    path: Qwen\u002FQwen3-0.6B\n    dtype: bf16\n    task: causal_lm\n  teacher:\n    path: Qwen\u002FQwen3-4B-Instruct-2507\n    dtype: bf16\n    task: causal_lm\n    placement: same_device\n\ndata:\n  train:\n    type: jsonl\n    path: datasets\u002Fsame_cross_tokenizer_data\u002Fdolly\u002Ftrain.jsonl\n  eval:\n    type: jsonl\n    path: datasets\u002Fsame_cross_tokenizer_data\u002Fdolly\u002Fdev.jsonl\n  transforms:\n    - type: tokenize_sft\n      use_chat_template: true\n  max_length: 1024\n\nloss:\n  aggregator:\n    type: kd_mix\n    kd_ratio: 1.0\n    ce_alias: nll\n  terms:\n    - criterion: nll\n    - criterion: token_kd\n      alias: kd\n      params:\n        divergence: fkl\n        chunk_size: 1024\n\ntrain:\n  batch_size: 16\n  micro_batch_size: 4\n  max_steps: 2000\n  output_dir: .\u002Foutputs\u002Fqwen_fkl\n  seed: 42\n\noptim:\n  lr: 2.0e-5\n  optimizers:\n    default:\n      type: adamw\n```\n\nCLI overrides with `--set`:\n\n```bash\nlmkd train -c recipes\u002Fsame_tokenizer\u002Ffkl.yaml \\\n    --set optim.lr=5e-5 \\\n          train.batch_size=8 \\\n          train.micro_batch_size=2\n```\n\nRecipes are organized by research domain under [`recipes\u002F`](recipes\u002F): `same_tokenizer\u002F`, `cross_tokenizer\u002F`, `embedding\u002F`, `long_cot\u002F`, `self_distill\u002F`, `preference\u002F`, `self_play\u002F`, plus shared building blocks in `_base_\u002F` (DeepSpeed engines, optimizers, evaluation suites). More in the [Configuration System](official_docs\u002Farchitecture\u002Fconfiguration-system.md) guide.\n\n## Extending LM-KD\n\nAdd a new loss in a standalone file and register it, with no changes to core code:\n\n```python\nfrom __future__ import annotations\n\nimport torch\nfrom lmkd.core.plugin import BaseConfig\nfrom lmkd.core.registry import CRITERIONS\nfrom lmkd.losses.base import Criterion, LossContext, LossOutput, LossTerm\nfrom lmkd.models.forward import FeatureRequest, SideRequest\n\n\n@CRITERIONS.register(\"temperature_mse\", paper=\"arXiv:xxxx.xxxxx\", status=\"stable\")\nclass TemperatureMSELoss(Criterion):\n    class Config(BaseConfig):\n        temperature: float = 1.0\n\n    def __init__(self, config: Config):\n        super().__init__(config)\n        self.temp = config.temperature\n\n    def features(self) -> FeatureRequest:\n        return FeatureRequest(\n            student=SideRequest(logits=\"view\"),\n            teacher=SideRequest(logits=\"view\"),\n        )\n\n    def forward(self, ctx: LossContext) -> LossOutput:\n        s_logits = ctx.student_logits().full() \u002F self.temp\n        t_logits = (ctx.teacher.logits.full() if ctx.teacher else s_logits) \u002F self.temp\n        diff = (s_logits - t_logits).pow(2).sum()\n        # Return an unnormalized numerator; the framework normalizes globally.\n        return LossOutput(terms={\"mse\": LossTerm(value=diff, reduction=\"token_sum\")})\n```\n\nUse it from a recipe:\n\n```yaml\nimports:\n  - .\u002Fplugins\u002Ftemperature_mse.py\n\nloss:\n  terms:\n    - criterion: temperature_mse\n      params:\n        temperature: 2.0\n```\n\nOr generate boilerplate (implementation, unit test, minimal recipe) with `lmkd new criterion my_custom_kd`. See [Developing a Custom Loss](official_docs\u002Fguides\u002Fdeveloping-custom-loss.md) and [Adding a New Baseline](official_docs\u002Fguides\u002Fadding-a-baseline.md).\n\n> **Three rules for criterions:** (1) never shift logits manually; only `LogitsView` does, and every per-token tensor is target-aligned; (2) never call a model inside a criterion; (3) never divide by batch size or sequence length; return raw numerators and let the aggregator normalize.\n\n\n## Architecture\n\nEvery distillation algorithm is decomposed into six independent axes:\n\n| Axis | Responsibility |\n| :--- | :--- |\n| **A. Context** | Where prefixes come from: external corpus, current policy, lagged policy, or a mixed schedule (see the [taxonomy](#taxonomy--supported-methods)) |\n| **B. Producer** | Batch collation, packing, multi-turn, preference pairs, cross-tokenizer aligners |\n| **C. Teacher** | Local HF, vLLM, remote API, EMA checkpoint, or offline cache |\n| **D. Criterion** | The divergence or objective (FKL, RKL, JSD, TVD, CSD, Sinkhorn, DPO-style, ...) |\n| **E. Step** | Execution strategy: standard backprop, PPO\u002FGRPO-style, dual-model sync, gradient hooks |\n| **F. Optimizer** | AdamW, Muon, TALAS, SAM, schedules, clipping |\n\n```\nRecipe (YAML) ─▶ Pydantic RecipeConfig ─▶ Plugin Registries\n                                              │\nRaw data ─▶ Batch Producer ─▶ Unified Batch ──┤\n                                  ┌───────────┴───────────┐\n                         Student forward           Teacher Provider\n                                  └───────────┬───────────┘\n                                       Criterion ─▶ Loss Aggregator ─▶ Engine\n                                                      (global Z_tok)   (ZeRO \u002F FSDP2)\n```\n\nLearn more: [Core Abstractions](official_docs\u002Farchitecture\u002Fcore-abstractions.md), [Registry & Plugins](official_docs\u002Farchitecture\u002Fregistry-plugin-system.md), [Data Flow & Caching](official_docs\u002Farchitecture\u002Fdata-flow-and-caching.md), [Distributed Backends](official_docs\u002Farchitecture\u002Fdistributed-backends.md), and the [Taxonomy of LLM KD](official_docs\u002Fconcepts\u002Ftaxonomy.md).\n\n## Repository Structure\n\n```text\nLM-KD\u002F\n├── src\u002F\n│   ├── lmkd\u002F               # Core framework\n│   │   ├── core\u002F           # Batch, Registry, Config, State\n│   │   ├── data\u002F           # Collators, aligners, packing, producers\n│   │   ├── losses\u002F         # Criterions, divergences, aggregator\n│   │   ├── teachers\u002F       # Teacher providers, caches, weight policies\n│   │   ├── rollout\u002F        # HF \u002F vLLM rollout engines, weight sync\n│   │   ├── models\u002F         # Adapters, LogitsView, ChunkedHead\n│   │   ├── rl\u002F             # Advantage estimators, verifiers, sandboxes\n│   │   ├── train\u002F          # Engine, trainer, optimizers, schedulers\n│   │   ├── eval\u002F           # Benchmarks, evaluators, graders, LLM-as-judge\n│   │   ├── compat\u002F         # DeepSpeed \u002F FSDP \u002F vLLM \u002F TRL compatibility\n│   │   ├── scaffold\u002F       # `lmkd new` code generators\n│   │   ├── cli.py          # Command-line entrypoint\n│   │   └── api.py          # Public Python API\n│   └── baselines\u002F          # Self-contained baseline implementations\n├── recipes\u002F                # YAML experiment specifications (grouped by method family)\n├── datasets\u002F               # Instruction, reasoning and embedding datasets\n├── examples\u002F               # Standalone scripts, custom loops, and tutorials\n├── packages\u002F               # Internal packages (tokenkit)\n├── scripts\u002F                # Generation, conversion and evaluation scripts\n├── official_docs\u002F          # Documentation\n├── tests\u002F                  # Unit, regression and integration tests\n├── LICENSE                 # Apache 2.0 License\n└── pyproject.toml\n```\n\n## Evaluation\n\nLM-KD includes a unified evaluation harness (`lmkd eval`) with registered evaluators, graders and a standardized protocol.\n\n- **Math and reasoning:** `math500`, `aime24`, `aime25`, `amc23`, `amc12`, `minerva`, `olympiadbench`, `gpqa` (unbiased pass@k with `math_verify` grading).\n- **Instruction following:** Dolly, Self-Instruct, Vicuna, Super-NaturalInstructions (ROUGE-L, exact match).\n- **Sentence embeddings:** 9 MTEB-style tasks covering STS, pair classification and linear-probe classification.\n- **LLM-as-a-judge:** pairwise win-rate with bidirectional position swap and length-bias reporting.\n- **Protocol:** greedy decoding for deterministic benchmarks, 3-seed replication (42, 123, 456), and paired bootstrap significance testing.\n\nSee [Metrics Catalog](official_docs\u002Fevaluation\u002Fmetrics-catalog.md), [Benchmark Suites](official_docs\u002Fevaluation\u002Fbenchmarks.md), [Evaluation Protocol](official_docs\u002Fevaluation\u002Feval-protocol.md) and the [Master Leaderboards](official_docs\u002Fresults\u002Fleaderboards.md) for the full results of all 7 experimental scenarios.\n\n## Documentation\n\n| If you want to... | Start here |\n| :--- | :--- |\n| Run your first experiment | [Quickstart](official_docs\u002Fgetting-started\u002Fquickstart.md) |\n| Understand the concepts | [Concepts & Taxonomy](official_docs\u002Fconcepts\u002Findex.md) |\n| Reproduce a published method | [Methods](official_docs\u002Fmethods\u002Findex.md), [Scenarios](official_docs\u002Fscenarios\u002Findex.md) |\n| Look up baseline papers & links | [Scenarios & Baseline Registry](official_docs\u002Fscenarios\u002Findex.md#baseline-methods--paper-registry) |\n| Implement a new method | [Architecture](official_docs\u002Farchitecture\u002Findex.md), [Guides](official_docs\u002Fguides\u002Findex.md), [API Reference](official_docs\u002Fapi\u002Findex.md) |\n| Prepare data | [Data Schemas & Datasets](official_docs\u002Fdata\u002Findex.md) |\n| Debug OOM \u002F NaN issues | [Troubleshooting](official_docs\u002Fgetting-started\u002Ftroubleshooting.md), [Debugging & Profiling](official_docs\u002Fguides\u002Fdebugging-and-profiling.md) |\n| Contribute | [Contributing Guide](official_docs\u002Fcontributing\u002Findex.md) |\n\n## Contributing\n\nContributions are welcome: new baselines, distributed backends (Megatron-LM, MLX, TPU, ROCm), fused Triton\u002FCUDA kernels, and benchmark loaders.\n\n```bash\ngit checkout -b feature\u002Fmy-new-feature\nruff check --fix . && ruff format .\npytest tests\u002F -v\nlmkd check -c recipes\u002F\u003Cyour_recipe>.yaml\n```\n\nBefore opening a pull request, please read the [Code Style & Standards](official_docs\u002Fcontributing\u002Fcode-style.md) (Ruff, 120-char lines, Python 3.11 type hints) and the [PR Checklist](official_docs\u002Fcontributing\u002Fpr-checklist.md).\n\n## Citation\n\nIf you use LM-KD or the taxonomy in your research, please cite the survey:\n\n```bibtex\n@article{lmkd_survey,\n  title  = {Knowledge Distillation for Large Language Models: A Survey of Training Contexts and Supervision},\n  author = {},\n  year   = {},\n  url    = {}\n}\n```\n\nand the software:\n\n```bibtex\n@software{lmkd,\n  title  = {LM-KD: A Unified Toolkit for Language Model Knowledge Distillation},\n  author = {},\n  year   = {},\n  url    = {https:\u002F\u002Fgithub.com\u002Fphongdq25\u002FLM-KD}\n}\n```\n\nPlease also cite the original papers of the baselines you use; complete bibliographies, authors, and links are cataloged in the [Baseline Methods & Paper Registry](official_docs\u002Fscenarios\u002Findex.md#baseline-methods--paper-registry) and on each method page.\n\n## License\n\nReleased under the Apache License 2.0. See [LICENSE](LICENSE).\n\n## Acknowledgements\n\nLM-KD builds on the open-source ecosystem, including PyTorch, Hugging Face Transformers \u002F Datasets \u002F PEFT, DeepSpeed, vLLM, FlashAttention, and Ray. Thanks to the authors of all the baseline methods implemented in this toolkit.\n","LM-KD 是一个面向大语言模型（LLM）知识蒸馏的统一、模块化开源工具包，旨在支持可复现的基准测试与快速方法原型开发。它整合了跨分词器迁移、链式思维压缩、偏好蒸馏、自蒸馏等七类主流蒸馏范式，提供基于 DeepSpeed\u002FFSDP2\u002FvLLM 的硬件高效运行时，并通过标准化接口消除工程差异对评估结果的干扰。项目强调内存优化（如避免长上下文 logits 全量计算），适用于算法研究人员开展蒸馏方法对比、工业界工程师部署轻量化 LLM 服务，以及教学场景中系统理解 LLM 对齐与压缩技术体系。","2026-11-24 04:36:33","CREATED_QUERY"]