distill-anything 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. distill_anything-0.1.0/.gitignore +13 -0
  2. distill_anything-0.1.0/CONTRIBUTING.md +45 -0
  3. distill_anything-0.1.0/LICENSE +201 -0
  4. distill_anything-0.1.0/PKG-INFO +329 -0
  5. distill_anything-0.1.0/README.md +294 -0
  6. distill_anything-0.1.0/distillanything/__init__.py +27 -0
  7. distill_anything-0.1.0/distillanything/cli.py +175 -0
  8. distill_anything-0.1.0/distillanything/config.py +93 -0
  9. distill_anything-0.1.0/distillanything/data/__init__.py +4 -0
  10. distill_anything-0.1.0/distillanything/data/filters.py +48 -0
  11. distill_anything-0.1.0/distillanything/data/formats.py +85 -0
  12. distill_anything-0.1.0/distillanything/data/generate.py +70 -0
  13. distill_anything-0.1.0/distillanything/data/tokenize.py +59 -0
  14. distill_anything-0.1.0/distillanything/eval/__init__.py +12 -0
  15. distill_anything-0.1.0/distillanything/eval/benchmark.py +91 -0
  16. distill_anything-0.1.0/distillanything/eval/judge.py +164 -0
  17. distill_anything-0.1.0/distillanything/eval/report.py +237 -0
  18. distill_anything-0.1.0/distillanything/hardware.py +46 -0
  19. distill_anything-0.1.0/distillanything/losses/__init__.py +3 -0
  20. distill_anything-0.1.0/distillanything/losses/kd.py +137 -0
  21. distill_anything-0.1.0/distillanything/smoke.py +51 -0
  22. distill_anything-0.1.0/distillanything/student.py +151 -0
  23. distill_anything-0.1.0/distillanything/teachers/__init__.py +4 -0
  24. distill_anything-0.1.0/distillanything/teachers/api.py +103 -0
  25. distill_anything-0.1.0/distillanything/teachers/base.py +30 -0
  26. distill_anything-0.1.0/distillanything/teachers/local.py +77 -0
  27. distill_anything-0.1.0/distillanything/teachers/registry.py +54 -0
  28. distill_anything-0.1.0/distillanything/testing.py +65 -0
  29. distill_anything-0.1.0/distillanything/train/__init__.py +3 -0
  30. distill_anything-0.1.0/distillanything/train/trainer.py +251 -0
  31. distill_anything-0.1.0/examples/data/seed_prompts.txt +10 -0
  32. distill_anything-0.1.0/examples/quickstart_mac.py +38 -0
  33. distill_anything-0.1.0/examples/sample-report.md +69 -0
  34. distill_anything-0.1.0/pyproject.toml +56 -0
  35. distill_anything-0.1.0/recipes/claude-blackbox.yaml +24 -0
  36. distill_anything-0.1.0/recipes/mac-small.yaml +25 -0
  37. distill_anything-0.1.0/tests/test_config.py +26 -0
  38. distill_anything-0.1.0/tests/test_data.py +68 -0
  39. distill_anything-0.1.0/tests/test_judge.py +101 -0
  40. distill_anything-0.1.0/tests/test_losses.py +71 -0
  41. distill_anything-0.1.0/tests/test_report.py +99 -0
  42. distill_anything-0.1.0/tests/test_trainer.py +71 -0
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ dist/
6
+ build/
7
+ runs/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .DS_Store
11
+ *.log
12
+ headroom_readme.md
13
+ .env
@@ -0,0 +1,45 @@
1
+ # Contributing to Distill Anything
2
+
3
+ Thanks for helping build the open-source distillation lifecycle. PRs of all sizes welcome.
4
+
5
+ ## Dev setup
6
+
7
+ ```bash
8
+ git clone https://github.com/AIAnytime/distillanything && cd distillanything
9
+ uv venv && uv pip install -e ".[dev]"
10
+ ```
11
+
12
+ ## Before you open a PR
13
+
14
+ ```bash
15
+ ruff check distillanything tests # lint
16
+ pytest # full suite — offline, no GPU, no API keys, no downloads
17
+ distill smoke # end-to-end pipeline check on your hardware
18
+ ```
19
+
20
+ The test suite is deliberately hermetic: tiny random models from `distillanything/testing.py`
21
+ and fake judges stand in for real models and APIs. **Keep it that way** — a test that needs
22
+ a network connection, an API key, or a model download will not be merged. If your feature
23
+ touches an API teacher, test the logic around the call with a `Teacher` fake (see
24
+ `tests/test_judge.py` for examples).
25
+
26
+ ## What makes a good contribution
27
+
28
+ - **Roadmap items** (see README) are pre-approved directions — open an issue to claim one.
29
+ - **New teachers**: subclass `Teacher`, register a spec prefix in `teachers/registry.py`,
30
+ keep SDK imports lazy so the core install stays light.
31
+ - **New losses**: pure functions in `losses/`, operating on `[B, S, V]` logits with the
32
+ `-100` label-mask convention, plus property tests (non-negativity, zero-at-identity,
33
+ masking, backprop) like `tests/test_losses.py`.
34
+ - **Recipes**: sized so they run on a 16GB laptop, or clearly labeled otherwise.
35
+
36
+ ## Style
37
+
38
+ - `ruff` (line length 110) — CI enforces it.
39
+ - Comments explain constraints the code can't show, not what the next line does.
40
+ - User-facing strings and errors should say what to do next, not just what went wrong.
41
+
42
+ ## Releases
43
+
44
+ Maintainers cut releases from `main`. Version lives in `pyproject.toml` and
45
+ `distillanything/__init__.py`.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Distill Anything contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,329 @@
1
+ Metadata-Version: 2.4
2
+ Name: distill-anything
3
+ Version: 0.1.0
4
+ Summary: The open-source lifecycle framework for distilling any model: generate data from teachers, distill students, evaluate, and benchmark.
5
+ Project-URL: Homepage, https://github.com/AIAnytime/distillanything
6
+ Project-URL: Repository, https://github.com/AIAnytime/distillanything
7
+ Project-URL: Issues, https://github.com/AIAnytime/distillanything/issues
8
+ Author: Distill Anything contributors
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: distillation,knowledge-distillation,llm,synthetic-data,training
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: pydantic>=2.5
19
+ Requires-Dist: pyyaml>=6.0
20
+ Requires-Dist: rich>=13.0
21
+ Requires-Dist: torch>=2.2
22
+ Requires-Dist: transformers>=4.44
23
+ Requires-Dist: typer>=0.12
24
+ Provides-Extra: anthropic
25
+ Requires-Dist: anthropic>=0.40; extra == 'anthropic'
26
+ Provides-Extra: api
27
+ Requires-Dist: anthropic>=0.40; extra == 'api'
28
+ Requires-Dist: openai>=1.40; extra == 'api'
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == 'dev'
31
+ Requires-Dist: ruff>=0.6; extra == 'dev'
32
+ Provides-Extra: openai
33
+ Requires-Dist: openai>=1.40; extra == 'openai'
34
+ Description-Content-Type: text/markdown
35
+
36
+ <div align="center"><pre>
37
+ ██████╗ ██╗███████╗████████╗██╗██╗ ██╗
38
+ ██╔══██╗██║██╔════╝╚══██╔══╝██║██║ ██║
39
+ ██║ ██║██║███████╗ ██║ ██║██║ ██║
40
+ ██║ ██║██║╚════██║ ██║ ██║██║ ██║
41
+ ██████╔╝██║███████║ ██║ ██║███████╗███████╗
42
+ ╚═════╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
43
+ A N Y T H I N G
44
+ Distill any model into one you own
45
+ </pre></div>
46
+
47
+ <p align="center"><strong>generate → distill → judge → benchmark · white-box KD + black-box seqKD · any teacher (Claude / GPT / HF / Ollama) · LLM-as-judge report card · runs on a MacBook</strong></p>
48
+
49
+ <p align="center">
50
+ <a href="https://github.com/AIAnytime/distillanything/actions/workflows/ci.yml"><img src="https://github.com/AIAnytime/distillanything/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
51
+ <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.10%2B-blue" alt="Python 3.10+"></a>
52
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="License: Apache 2.0"></a>
53
+ <a href="#development"><img src="https://img.shields.io/badge/tests-31%20passing%20offline-brightgreen" alt="Tests"></a>
54
+ <a href="#whats-real-today-vs-the-vision"><img src="https://img.shields.io/badge/status-alpha-orange" alt="Status: alpha"></a>
55
+ <a href="https://github.com/astral-sh/ruff"><img src="https://img.shields.io/badge/code%20style-ruff-261230" alt="Code style: ruff"></a>
56
+ </p>
57
+
58
+ <p align="center">
59
+ <a href="#get-started-60-seconds">Install</a> ·
60
+ <a href="#proof">Proof</a> ·
61
+ <a href="#the-report-card">Report card</a> ·
62
+ <a href="#teachers">Teachers</a> ·
63
+ <a href="#compared-to">Compared to</a> ·
64
+ <a href="#roadmap">Roadmap</a>
65
+ </p>
66
+
67
+ ---
68
+
69
+ Big models know things. Small models ship. Distill Anything covers the **whole distillation lifecycle** — a teacher generates your dataset, a student trains on its logits or its words, a judge scores the result blind, and a benchmark prices it — with one YAML recipe schema that scales from a 16GB MacBook to a GPU cluster.
70
+
71
+ <p align="center">
72
+ <img src="https://raw.githubusercontent.com/AIAnytime/distillanything/main/media/demo.gif" alt="distill smoke running end-to-end on a MacBook" width="820">
73
+ <br/><sub>Live: <code>distill smoke</code> — full logit-KD pipeline, offline, &lt;60s on a MacBook. loss 2.24 → 2.08, PASS.</sub>
74
+ </p>
75
+
76
+ <p align="center">
77
+ <img src="https://raw.githubusercontent.com/AIAnytime/distillanything/main/media/architecture.png" alt="Distill Anything architecture: seed prompts through teachers, synthetic dataset pipeline, distillation engine, evaluation, benchmark" width="100%">
78
+ <br/><sub>The full picture. What's shipped vs planned: <a href="#whats-real-today-vs-the-vision">status table</a>.</sub>
79
+ </p>
80
+
81
+ ## What it does
82
+
83
+ - **Any teacher** — `claude`, `openai:gpt-4o-mini`, `ollama:llama3.2`, or any local `hf:` model, selected by one spec string
84
+ - **Synthetic data** — `distill generate` turns seed prompts into a deduped instruction dataset, with self-instruct-style prompt expansion (`--expand 5`)
85
+ - **Quality gating** — an LLM judge scores every record 1–10 before training (`--judge claude --min-score 7`)
86
+ - **White-box logit KD** — forward KL (Hinton), reverse KL (MiniLLM-style), generalized JSD, temperature scaling, and top-k truncation so 50k-vocab KD fits in laptop memory
87
+ - **Black-box seqKD** — no logits needed; fine-tune on what an API teacher wrote
88
+ - **LLM-as-judge eval** — blind A/B, position-swapped to kill judge bias → win/tie/lose and one headline number: *quality retention*
89
+ - **Report card** — `distill report` writes a shareable `REPORT.md`: quality vs the teacher, p50/p95 latency, tokens/s, memory, $ per 1K tokens
90
+ - **Hardware-aware** — CUDA (bf16) → Apple Silicon MPS → CPU, detected automatically
91
+
92
+ ## How it works (30 seconds)
93
+
94
+ ```
95
+ Seed prompts (.txt / .jsonl)
96
+
97
+
98
+ Teacher ──────────── claude · openai:<m> · ollama:<m> · hf:<repo>
99
+ │ generate + expand + dedup + judge-score
100
+
101
+ Curated dataset (JSONL)
102
+
103
+
104
+ Distillation engine
105
+ ├─ logit KD teacher logits → KL/JSD on every response token (hf: teachers)
106
+ └─ seqKD teacher text → cross-entropy fine-tune (any teacher)
107
+
108
+
109
+ Judge (blind A/B, position-swapped) → win / tie / lose
110
+
111
+
112
+ REPORT.md — "student keeps X% of teacher quality at 1/Nth the size and cost"
113
+ ```
114
+
115
+ One `DistillConfig` YAML describes the whole run; the same recipe format works for a 135M student on a MacBook and a 7B student on an A100.
116
+
117
+ ## Get started (60 seconds)
118
+
119
+ ```bash
120
+ # 1 — Install
121
+ git clone https://github.com/AIAnytime/distillanything && cd distillanything
122
+ pip install -e . # core (torch, transformers)
123
+ pip install -e ".[anthropic]" # optional: Claude as teacher/judge
124
+ pip install -e ".[openai]" # optional: OpenAI / vLLM / Ollama teachers
125
+
126
+ # 2 — Verify your machine (tiny random models, zero downloads, <1 min)
127
+ distill smoke
128
+
129
+ # 3 — First real distillation (SmolLM2-360M → 135M, ~1GB download, runs on MPS)
130
+ distill generate examples/data/seed_prompts.txt \
131
+ --teacher hf:HuggingFaceTB/SmolLM2-360M-Instruct --out data/train.jsonl --expand 5
132
+ distill train recipes/mac-small.yaml
133
+ distill report runs/mac-small --dataset data/train.jsonl \
134
+ --teacher hf:HuggingFaceTB/SmolLM2-360M-Instruct --judge hf:HuggingFaceTB/SmolLM2-360M-Instruct
135
+ ```
136
+
137
+ Prefer Claude as the teacher? `export ANTHROPIC_API_KEY=...` then swap `--teacher claude` and `distill train recipes/claude-blackbox.yaml`.
138
+
139
+ ## Proof
140
+
141
+ We publish only what we've measured. Every number below reproduces on a stock Apple-Silicon MacBook with the commands shown — no cluster required.
142
+
143
+ **End-to-end pipeline, offline, under a minute** (`distill smoke`):
144
+
145
+ ```
146
+ Training mode=logit device=mps steps=30 loss=forward_kl(T=2.0, alpha=0.5)
147
+ step 10/30 loss 2.2371 → step 30/30 loss 2.0767
148
+ PASS: loss 2.237 -> 2.077 over 30 steps
149
+ ```
150
+
151
+ **Benchmark output** (`distill benchmark sshleifer/tiny-gpt2 --n-runs 3 --cost-per-hour 1.20`, measured on an M-series MacBook):
152
+
153
+ | Metric | Value |
154
+ |---|---:|
155
+ | latency_p50_s | 0.054 |
156
+ | latency_p95_s | 0.079 |
157
+ | tokens_per_s | 262.4 |
158
+ | memory_mb | 0.4 |
159
+ | cost_per_1k_tokens_usd | 0.001271 |
160
+
161
+ **A real distillation, end to end on one MacBook** — the exact Quickstart above (SmolLM2-360M teaches 135M on 60 records it generated itself, ~15 min total, all local):
162
+
163
+ | | Student (135M, distilled) | Teacher (360M) |
164
+ |---|---:|---:|
165
+ | Parameters | 134.5M | 361.8M |
166
+ | Tokens / s (MPS) | **70.5** | 56.7 |
167
+ | Latency p50 | **0.40s** | 0.76s |
168
+ | Disk | **538MB** | 1447MB |
169
+ | $ / 1K tokens @ $1.20/hr | **$0.0047** | $0.0059 |
170
+
171
+ - **Quality retention 87.5%** on 24 held-out prompts (1 win / 20 ties / 3 losses), judged blind with position swap by the teacher itself. A 360M judge is coarse — most pairs tie; point `--judge claude` at it for sharper discrimination.
172
+ - Token-level teacher agreement **81%**, perplexity 2.17 (3-example eval split — demo scale).
173
+ - The full unedited artifact: [examples/sample-report.md](examples/sample-report.md), generated by `distill report`.
174
+
175
+ This is the quickstart, not a leaderboard claim — 60 records and 8 optimizer steps prove the loop runs on a laptop, not the ceiling of the method.
176
+
177
+ **Honest-by-construction evals:** the judge sees answers blind and judges each pair twice with positions swapped — a judge that always prefers "Answer A" nets out to a tie (that exact adversarial case is in the test suite). Disagreements and unparseable verdicts count as ties, never wins. 31 tests run fully offline against tiny random models.
178
+
179
+ ## The report card
180
+
181
+ The question that matters is *"did the student keep the teacher's quality at a fraction of the cost?"* — so every run can end with a one-page answer:
182
+
183
+ ```bash
184
+ distill report runs/mac-small \
185
+ --dataset data/train.jsonl \
186
+ --teacher hf:HuggingFaceTB/SmolLM2-360M-Instruct \
187
+ --judge claude --n 32 --cost-per-hour 1.20
188
+ ```
189
+
190
+ `REPORT.md` leads with **quality retention** (how often the student matches or beats the reference), then a side-by-side efficiency table (params, tokens/s, p50/p95, memory, $/1K tokens — "3.0x smaller and 3.0x faster"), sample outputs, and the training metrics. `report.json` sits next to it for machines.
191
+
192
+ ## Teachers
193
+
194
+ One string selects any knowledge source — as teacher *or* as judge:
195
+
196
+ | Spec | Backend | KD mode |
197
+ |---|---|---|
198
+ | `hf:HuggingFaceTB/SmolLM2-360M-Instruct` | local Hugging Face model | white-box (logits) |
199
+ | `claude` / `claude:claude-opus-4-8` | Anthropic API | black-box (seqKD) |
200
+ | `openai:gpt-4o-mini` | OpenAI API (or any compatible endpoint) | black-box |
201
+ | `ollama:llama3.2` | local Ollama server | black-box |
202
+
203
+ **One rule to know:** logit KD requires student and teacher to share a tokenizer (same model family). Across tokenizers, use `mode: seqkd` — cross-tokenizer logit alignment (ULD) is on the roadmap.
204
+
205
+ ## Recipes
206
+
207
+ Everything is a YAML recipe (`distill init` writes a starter):
208
+
209
+ ```yaml
210
+ mode: logit # or seqkd
211
+ teacher: { spec: hf:HuggingFaceTB/SmolLM2-360M-Instruct }
212
+ student: { model: HuggingFaceTB/SmolLM2-135M-Instruct }
213
+ data: { path: data/train.jsonl, max_seq_len: 512 }
214
+ loss: { kind: forward_kl, temperature: 2.0, alpha: 0.5, top_k: 256 }
215
+ train: { output_dir: runs/out, lr: 1.0e-4, epochs: 2, batch_size: 2, grad_accum: 8 }
216
+ ```
217
+
218
+ Or skip YAML entirely:
219
+
220
+ ```python
221
+ from distillanything import Student
222
+
223
+ student = Student("HuggingFaceTB/SmolLM2-135M-Instruct")
224
+ student.learn(teacher="claude", dataset="data/prompts_only.jsonl") # generates missing responses, then trains
225
+ print(student.generate("Explain what a database index is."))
226
+ print(student.benchmark())
227
+ ```
228
+
229
+ ## When to use · When to skip
230
+
231
+ **Great fit if you…**
232
+ - want a specialized model that's 10–100x smaller than the API model you're calling today
233
+ - have (or can seed) a few hundred domain prompts and an API key or a local teacher model
234
+ - work on a laptop — everything here is sized to run and iterate on 16GB of RAM
235
+
236
+ **Skip it if you…**
237
+ - need RAG or prompt engineering, not a trained model — distillation is for when the task is stable and volume is high
238
+ - need cross-tokenizer logit KD, multimodal, or distributed training *today* (roadmap, not shipped)
239
+ - expect a hosted platform — this is a framework; you bring the compute
240
+
241
+ <a id="whats-real-today-vs-the-vision"></a>
242
+ <details>
243
+ <summary><b>What's real today vs the vision</b></summary>
244
+
245
+ The architecture diagram is the north star, not the changelog. Every box, mapped honestly:
246
+
247
+ **Legend:** ✅ shipped &nbsp;·&nbsp; 🚧 partial &nbsp;·&nbsp; 🗺️ planned, not yet built
248
+
249
+ | Diagram section | Box | Status | Notes |
250
+ |---|---|:---:|---|
251
+ | Seed Prompts | Text / Docs, Custom | ✅ | `.txt` (one prompt/line) and `.jsonl` (`prompt`/`messages`/`text`) |
252
+ | Seed Prompts | Code | 🚧 | No special handling — treated as plain text, works but untuned |
253
+ | Teacher | Claude API, GPT API, Hugging Face (Local), Ollama (Local) | ✅ | `hf:` / `claude` / `openai:` / `ollama:` teacher specs |
254
+ | Synthetic Dataset Pipeline | Generate, Deduplication, Curated Dataset | ✅ | `distill generate`, normalized-content dedup |
255
+ | Synthetic Dataset Pipeline | Filtering | 🚧 | Empty/too-short response filter only — no content or toxicity filters yet |
256
+ | Synthetic Dataset Pipeline | Quality Scoring | ✅ | LLM-judge 1-10 scoring: `distill generate --judge claude --min-score 7` |
257
+ | Distillation Engine | Forward KL, Reverse KL, JSD, Top-k/Temp | ✅ | White-box logit KD, all three divergences + top-k truncation |
258
+ | Distillation Engine | Response Supervision, Instruction Tuning | ✅ | Black-box seqKD (fine-tune on teacher-generated text) |
259
+ | Distillation Engine | Preference (Optional) | 🗺️ | No DPO/preference-based distillation yet |
260
+ | Evaluation | Perplexity | ✅ | |
261
+ | Evaluation | Teacher Agreement | ✅ | Win/tie/lose via blind, position-swapped LLM judge (`distill report --judge`) + token-level agreement |
262
+ | Evaluation | Accuracy/EM, BLEU/ROUGE/BERTScore, Safety/Bias Checks | 🗺️ | No task-benchmark or safety-eval harness yet |
263
+ | Benchmark | Tokens/s, Memory, Model Size | ✅ | `distill benchmark` |
264
+ | Benchmark | Latency | ✅ | p50/p95 over repeated runs (`--n-runs`) |
265
+ | Benchmark | Cost / 1K Tokens | ✅ | From measured throughput × your `--cost-per-hour` |
266
+ | Outputs | Model Weights, Tokenizer & Config, Training Logs, Benchmarks | ✅ | Saved to `output_dir` on every run |
267
+ | Outputs | Evaluation Report | ✅ | `distill report` writes a shareable REPORT.md + report.json per run |
268
+ | Core Capabilities | Reproducible Pipelines | ✅ | Seeded runs + full config snapshot saved alongside the checkpoint |
269
+ | Core Capabilities | Multi-Teacher Support, Multi-Modal, Distributed Training, Quantization/Export, Experiment Tracking | 🗺️ | One teacher/one device per run today; text-only; no W&B/MLflow hooks |
270
+ | Integrations | Hugging Face | ✅ | Models, tokenizers, chat templates |
271
+ | Integrations | Weights & Biases, MLflow, S3/GCS/Azure Blob, Docker/Kubernetes | 🗺️ | Not integrated yet |
272
+ | How you interact | Python SDK, CLI | ✅ | `Student().learn(...)` and `distill ...` |
273
+ | How you interact | REST API, Web UI | 🗺️ | CLI/SDK only for now |
274
+
275
+ </details>
276
+
277
+ <details>
278
+ <summary><b>What's inside</b></summary>
279
+
280
+ - **`teachers/`** — one `Teacher` abstraction; local HF models expose logits (white-box), API teachers expose text (black-box). Registry resolves spec strings.
281
+ - **`losses/kd.py`** — masked, temperature-scaled (T² gradient correction) forward KL / reverse KL / generalized JSD, with top-k support truncation and automatic vocab-padding alignment.
282
+ - **`data/`** — JSONL/txt loading, chat-template rendering, prompt-masked tokenization, normalized dedup, teacher-driven generation with prompt expansion.
283
+ - **`train/trainer.py`** — hand-rolled loop (no HF Trainer): grad accumulation, cosine LR + warmup, grad clipping, KD+CE mixing, MPS-safe autocast policy.
284
+ - **`eval/judge.py`** — pairwise blind judging with position-swap debiasing; absolute 1–10 scoring for dataset gating.
285
+ - **`eval/benchmark.py`** — p50/p95 latency, throughput, peak memory, $/1K tokens.
286
+ - **`eval/report.py`** — REPORT.md + report.json builder.
287
+ - **`testing.py`** — tiny random Llama models + in-memory char tokenizer, so the whole suite runs offline.
288
+
289
+ </details>
290
+
291
+ ## Compared to
292
+
293
+ Excellent distillation *trainers* exist — the gap this project fills is the **lifecycle around the training loop**:
294
+
295
+ | | Primary focus | Data generation from API teachers | Blind LLM-judge → report card | Sized for laptops |
296
+ |---|---|:---:|:---:|:---:|
297
+ | **Distill Anything** | Full lifecycle: generate → distill → judge → benchmark | ✅ | ✅ | ✅ |
298
+ | [TRL](https://github.com/huggingface/trl) (GKD) | RL/KD training methods in the HF ecosystem | — | — | GPU-oriented |
299
+ | [DistillKit](https://github.com/arcee-ai/DistillKit) | KD training techniques | — | — | GPU-oriented |
300
+ | [EasyDistill](https://github.com/modelscope/easydistill) | KD training + data synthesis toolkit | ✅ | — | GPU-oriented |
301
+
302
+ If you already have a curated dataset and a GPU and just want a training loop, TRL's GKD trainer is great — and our loss implementations follow the same literature (Hinton KD, MiniLLM, DistiLLM).
303
+
304
+ ## Roadmap
305
+
306
+ Beyond closing the 🗺️ gaps in the status table:
307
+
308
+ - [ ] **LoRA/QLoRA students** — distill into 1–3B students on 16GB of RAM *(next up)*
309
+ - [ ] Hidden-state / feature KD with learned projectors
310
+ - [ ] Cross-tokenizer logit distillation (ULD)
311
+ - [ ] Multi-teacher voting and ensembling
312
+ - [ ] VLM, embedding, and reranker distillation
313
+ - [ ] Eval harness integration (lm-eval-harness) and regression tracking
314
+
315
+ Everything in this repo is and stays Apache-2.0. A hosted layer (GPU orchestration, dashboards, model registry) may come later — the framework is the product, not the funnel.
316
+
317
+ ## Development
318
+
319
+ ```bash
320
+ uv venv && uv pip install -e ".[dev]"
321
+ pytest # 31 tests, fully offline (tiny random models, fake judges)
322
+ distill smoke # end-to-end pipeline check on your hardware
323
+ ```
324
+
325
+ PRs welcome — the test suite needs no GPU, no API keys, and no downloads.
326
+
327
+ ## License
328
+
329
+ Apache 2.0 — see [LICENSE](LICENSE).