distill-slm 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 (60) hide show
  1. distill_slm-0.1.0/.gitignore +20 -0
  2. distill_slm-0.1.0/LICENSE +201 -0
  3. distill_slm-0.1.0/NOTICE +9 -0
  4. distill_slm-0.1.0/PKG-INFO +415 -0
  5. distill_slm-0.1.0/README.md +350 -0
  6. distill_slm-0.1.0/demo/README.md +51 -0
  7. distill_slm-0.1.0/distill/__init__.py +16 -0
  8. distill_slm-0.1.0/distill/agents/__init__.py +5 -0
  9. distill_slm-0.1.0/distill/agents/critic.py +283 -0
  10. distill_slm-0.1.0/distill/agents/evaluator.py +341 -0
  11. distill_slm-0.1.0/distill/agents/generator.py +233 -0
  12. distill_slm-0.1.0/distill/agents/improver.py +138 -0
  13. distill_slm-0.1.0/distill/cache.py +90 -0
  14. distill_slm-0.1.0/distill/cli.py +606 -0
  15. distill_slm-0.1.0/distill/config.py +225 -0
  16. distill_slm-0.1.0/distill/costs.py +199 -0
  17. distill_slm-0.1.0/distill/dashboard.py +158 -0
  18. distill_slm-0.1.0/distill/data.py +198 -0
  19. distill_slm-0.1.0/distill/dedup.py +227 -0
  20. distill_slm-0.1.0/distill/errors.py +35 -0
  21. distill_slm-0.1.0/distill/export/__init__.py +20 -0
  22. distill_slm-0.1.0/distill/export/gguf.py +143 -0
  23. distill_slm-0.1.0/distill/export/hub.py +297 -0
  24. distill_slm-0.1.0/distill/export/ollama.py +96 -0
  25. distill_slm-0.1.0/distill/graph.py +638 -0
  26. distill_slm-0.1.0/distill/logging_utils.py +124 -0
  27. distill_slm-0.1.0/distill/metrics.py +149 -0
  28. distill_slm-0.1.0/distill/paths.py +183 -0
  29. distill_slm-0.1.0/distill/prompts.py +64 -0
  30. distill_slm-0.1.0/distill/report/__init__.py +7 -0
  31. distill_slm-0.1.0/distill/report/html_report.py +200 -0
  32. distill_slm-0.1.0/distill/report/template.html.j2 +388 -0
  33. distill_slm-0.1.0/distill/review.py +183 -0
  34. distill_slm-0.1.0/distill/schema.py +204 -0
  35. distill_slm-0.1.0/distill/serving/__init__.py +14 -0
  36. distill_slm-0.1.0/distill/serving/api.py +138 -0
  37. distill_slm-0.1.0/distill/students/__init__.py +24 -0
  38. distill_slm-0.1.0/distill/students/base.py +71 -0
  39. distill_slm-0.1.0/distill/students/hf_runner.py +120 -0
  40. distill_slm-0.1.0/distill/students/ollama_runner.py +78 -0
  41. distill_slm-0.1.0/distill/students/teacher_predictor.py +80 -0
  42. distill_slm-0.1.0/distill/teachers/__init__.py +33 -0
  43. distill_slm-0.1.0/distill/teachers/anthropic_teacher.py +141 -0
  44. distill_slm-0.1.0/distill/teachers/base.py +194 -0
  45. distill_slm-0.1.0/distill/teachers/openai_compatible.py +103 -0
  46. distill_slm-0.1.0/distill/training/__init__.py +18 -0
  47. distill_slm-0.1.0/distill/training/lora_trainer.py +255 -0
  48. distill_slm-0.1.0/distill/training/merge.py +52 -0
  49. distill_slm-0.1.0/examples/email-triage/seeds.jsonl +24 -0
  50. distill_slm-0.1.0/examples/email-triage/task.local.yaml +113 -0
  51. distill_slm-0.1.0/examples/email-triage/task.yaml +133 -0
  52. distill_slm-0.1.0/examples/email-triage/test_set.jsonl +201 -0
  53. distill_slm-0.1.0/pyproject.toml +92 -0
  54. distill_slm-0.1.0/tests/__init__.py +0 -0
  55. distill_slm-0.1.0/tests/conftest.py +274 -0
  56. distill_slm-0.1.0/tests/test_agents.py +285 -0
  57. distill_slm-0.1.0/tests/test_core.py +348 -0
  58. distill_slm-0.1.0/tests/test_onboarding.py +165 -0
  59. distill_slm-0.1.0/tests/test_pipeline.py +494 -0
  60. distill_slm-0.1.0/tests/test_review.py +174 -0
@@ -0,0 +1,20 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ venv/
8
+ .env
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ .coverage
13
+ htmlcov/
14
+ runs/
15
+ models/
16
+ outputs/
17
+ *.gguf
18
+ *.safetensors
19
+ .cache/
20
+ .DS_Store
@@ -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 Abdelilah OURTI
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,9 @@
1
+ Distill
2
+ Copyright 2026 Abdelilah OURTI (AI Engineer) - https://neurautech.com
3
+
4
+ This product includes software developed by Abdelilah OURTI.
5
+
6
+ Les modeles eleves (Qwen 2.5, Llama 3.2) et les modeles professeurs restent
7
+ soumis a leurs licences respectives. Verifiez les conditions d'utilisation de
8
+ votre fournisseur de LLM professeur avant d'entrainer un modele sur ses sorties
9
+ (voir la commande `distill run --check-terms`).
@@ -0,0 +1,415 @@
1
+ Metadata-Version: 2.5
2
+ Name: distill-slm
3
+ Version: 0.1.0
4
+ Summary: Transforme une description de tache et ~20 exemples en un petit modele specialise, evalue et pret pour Ollama, en une seule commande.
5
+ Project-URL: Homepage, https://github.com/Abdelilah04116/distill
6
+ Project-URL: Documentation, https://github.com/Abdelilah04116/distill#readme
7
+ Project-URL: Source, https://github.com/Abdelilah04116/distill
8
+ Project-URL: Article, https://neurautech.com
9
+ Author-email: Abdelilah OURTI <abdelilahourti@gmail.com>
10
+ Maintainer-email: Abdelilah OURTI <abdelilahourti@gmail.com>
11
+ License: Apache-2.0
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Keywords: distillation,fine-tuning,llm,lora,ollama,slm,synthetic-data
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: anthropic>=0.40
24
+ Requires-Dist: httpx>=0.27
25
+ Requires-Dist: jinja2>=3.1
26
+ Requires-Dist: numpy>=1.24
27
+ Requires-Dist: pydantic>=2.7
28
+ Requires-Dist: pyyaml>=6.0
29
+ Requires-Dist: rich>=13.7
30
+ Requires-Dist: typer>=0.12
31
+ Provides-Extra: all
32
+ Requires-Dist: fastapi>=0.111; extra == 'all'
33
+ Requires-Dist: huggingface-hub>=0.24; extra == 'all'
34
+ Requires-Dist: langgraph-checkpoint-sqlite>=1.0.0; extra == 'all'
35
+ Requires-Dist: langgraph>=0.2.28; extra == 'all'
36
+ Requires-Dist: qdrant-client>=1.9; extra == 'all'
37
+ Requires-Dist: sentence-transformers>=3.0; extra == 'all'
38
+ Requires-Dist: uvicorn[standard]>=0.30; extra == 'all'
39
+ Provides-Extra: dedup
40
+ Requires-Dist: qdrant-client>=1.9; extra == 'dedup'
41
+ Requires-Dist: sentence-transformers>=3.0; extra == 'dedup'
42
+ Provides-Extra: dev
43
+ Requires-Dist: mypy>=1.10; extra == 'dev'
44
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
45
+ Requires-Dist: pytest>=8.2; extra == 'dev'
46
+ Requires-Dist: ruff>=0.5; extra == 'dev'
47
+ Requires-Dist: types-pyyaml; extra == 'dev'
48
+ Provides-Extra: graph
49
+ Requires-Dist: langgraph-checkpoint-sqlite>=1.0.0; extra == 'graph'
50
+ Requires-Dist: langgraph>=0.2.28; extra == 'graph'
51
+ Provides-Extra: hub
52
+ Requires-Dist: huggingface-hub>=0.24; extra == 'hub'
53
+ Provides-Extra: serve
54
+ Requires-Dist: fastapi>=0.111; extra == 'serve'
55
+ Requires-Dist: uvicorn[standard]>=0.30; extra == 'serve'
56
+ Provides-Extra: train
57
+ Requires-Dist: accelerate>=0.33; extra == 'train'
58
+ Requires-Dist: bitsandbytes>=0.43; (sys_platform == 'linux') and extra == 'train'
59
+ Requires-Dist: datasets>=2.20; extra == 'train'
60
+ Requires-Dist: peft>=0.12; extra == 'train'
61
+ Requires-Dist: torch>=2.3; extra == 'train'
62
+ Requires-Dist: transformers>=4.44; extra == 'train'
63
+ Requires-Dist: trl>=0.9; extra == 'train'
64
+ Description-Content-Type: text/markdown
65
+
66
+ <div align="center">
67
+
68
+ # Distill
69
+
70
+ **Ton propre modèle, spécialisé, local et 10× moins cher — sans écrire une ligne de code d'entraînement.**
71
+
72
+ [![Licence](https://img.shields.io/badge/licence-Apache%202.0-blue.svg)](https://github.com/Abdelilah04116/distill/blob/main/LICENSE)
73
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
74
+ [![CI](https://img.shields.io/github/actions/workflow/status/Abdelilah04116/distill/ci.yml?branch=main&label=CI)](https://github.com/Abdelilah04116/distill/actions/workflows/ci.yml)
75
+ [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Abdelilah04116/distill/blob/main/notebooks/distill_colab.ipynb)
76
+
77
+ Une description de tâche, une vingtaine d'exemples, une commande.
78
+ En sortie : un SLM de 0,5 à 3 milliards de paramètres, évalué, quantifié, et prêt à tourner en local avec Ollama.
79
+
80
+ </div>
81
+
82
+ ---
83
+
84
+ ## Le problème
85
+
86
+ Les entreprises paient des LLM géants pour des tâches étroites et répétitives : classer des tickets, extraire des champs, router des demandes. C'est cher, c'est lent, et c'est souvent incompatible avec le RGPD dès que les données partent dans le cloud.
87
+
88
+ **Distill utilise le gros LLM une seule fois, comme professeur**, pour former un élève qui fait la même tâche en local, pour une fraction du coût.
89
+
90
+ ```bash
91
+ distill run --task examples/email-triage/task.yaml
92
+ # ... génération, critique, entraînement, évaluation, export ...
93
+ ollama run distill-email-triage
94
+ ```
95
+
96
+ ## Ce que ça fait, étape par étape
97
+
98
+ <div align="center">
99
+ <img src="https://raw.githubusercontent.com/Abdelilah04116/distill/main/docs/architecture-linkedin.png" alt="task.yaml alimente le Générateur, puis le Critique, puis l'Entraînement LoRA, puis l'Évaluateur. Si la cible n'est pas atteinte, l'Améliorateur produit des exemples ciblés et renvoie au Critique, trois fois au maximum. Sinon, le pipeline exporte en GGUF, Ollama et FastAPI." width="880">
100
+ </div>
101
+
102
+ | Agent | Rôle | Fichier |
103
+ |---|---|---|
104
+ | **Générateur** | 2 000 à 5 000 exemples synthétiques, variés par persona, ton, longueur, fautes, cas limites | [generator.py](https://github.com/Abdelilah04116/distill/blob/main/distill/agents/generator.py) |
105
+ | **Critique** | dédup exacte et sémantique, LLM-as-judge (note 1–5), équilibre des classes, isolation du test set | [critic.py](https://github.com/Abdelilah04116/distill/blob/main/distill/agents/critic.py) |
106
+ | **Entraînement** | LoRA / QLoRA sur un seul GPU, courbe de loss en temps réel, reprise après interruption | [lora_trainer.py](https://github.com/Abdelilah04116/distill/blob/main/distill/training/lora_trainer.py) |
107
+ | **Évaluateur** | élève, professeur et baseline sur le même test set, F1 par classe, latence, coût | [evaluator.py](https://github.com/Abdelilah04116/distill/blob/main/distill/agents/evaluator.py) |
108
+ | **Améliorateur** | lit les erreurs réelles, génère des exemples ciblés, relance (3 fois maximum) | [improver.py](https://github.com/Abdelilah04116/distill/blob/main/distill/agents/improver.py) |
109
+ | **Export** | fusion LoRA, GGUF (Q4_K_M, Q8_0), Modelfile Ollama, API FastAPI, rapport HTML | [export/](https://github.com/Abdelilah04116/distill/tree/main/distill/export/) |
110
+
111
+ L'orchestration est un graphe LangGraph avec état persisté ([graph.py](https://github.com/Abdelilah04116/distill/blob/main/distill/graph.py)) : un run interrompu reprend là où il s'est arrêté. Si LangGraph n'est pas installé, le même enchaînement tourne en séquentiel.
112
+
113
+ ## Installation
114
+
115
+ Le paquet n'est pas encore sur PyPI. Pour l'instant, on installe depuis le dépôt :
116
+
117
+ ```bash
118
+ git clone https://github.com/Abdelilah04116/distill && cd distill
119
+ python -m venv .venv && source .venv/bin/activate # .venv\Scriptsctivate sous Windows
120
+
121
+ pip install -e . # noyau : CLI, agents, évaluation, rapport
122
+ pip install -e ".[all]" # + LangGraph, Qdrant, embeddings, FastAPI
123
+ pip install -e ".[train]" # + torch, transformers, peft, trl (GPU)
124
+ ```
125
+
126
+ Pour l'entraînement, Unsloth est optionnel mais recommandé — il est deux fois plus rapide et tient dans moins de VRAM :
127
+
128
+ ```bash
129
+ pip install unsloth
130
+ ```
131
+
132
+ Pour l'export GGUF, il faut llama.cpp compilé :
133
+
134
+ ```bash
135
+ git clone https://github.com/ggerganov/llama.cpp && cd llama.cpp
136
+ cmake -B build && cmake --build build --config Release
137
+ export LLAMA_CPP_DIR=$PWD
138
+ ```
139
+
140
+ ## Démarrage rapide
141
+
142
+ Il faut une clé pour le professeur, ou un modèle local qui en tient lieu.
143
+
144
+ ```bash
145
+ export ANTHROPIC_API_KEY=sk-ant-...
146
+ ```
147
+
148
+ **Sans clé et sans budget**, le dépôt fournit une variante entièrement locale, où le professeur est un modèle open-weight servi par Ollama. Rien ne sort de la machine, rien n'est facturé :
149
+
150
+ ```bash
151
+ ollama pull qwen2.5:7b-instruct
152
+ distill run --task examples/email-triage/task.local.yaml
153
+ ```
154
+
155
+ Le parcours complet sur la tâche de démonstration :
156
+
157
+ ```bash
158
+ # 1. Vérifier la tâche et les exemples avant de dépenser quoi que ce soit
159
+ distill validate --task examples/email-triage/task.yaml
160
+ distill estimate --task examples/email-triage/task.yaml
161
+
162
+ # 2. Lancer le pipeline complet (~4 $ de professeur, plafonné à 6 $)
163
+ distill run --task examples/email-triage/task.yaml
164
+
165
+ # 3. Essayer le modèle
166
+ ollama run distill-email-triage
167
+
168
+ # 4. Le servir en HTTP
169
+ distill serve --task examples/email-triage/task.yaml
170
+ curl -X POST localhost:8000/predict -H 'content-type: application/json' \
171
+ -d '{"input":"Bonjour, je n ai pas recu ma facture de janvier."}'
172
+ ```
173
+
174
+ Autres commandes utiles :
175
+
176
+ ```bash
177
+ distill run --task t.yaml --dry-run # plan + estimation de coût, sans rien lancer
178
+ distill run --task t.yaml --resume # reprend le dernier run
179
+ distill run --task t.yaml --skip-generation # réutilise les exemples déjà produits
180
+ distill watch --task t.yaml # suivi en direct : étapes, coût, courbe de loss
181
+ distill review --task t.yaml # relecture humaine du test set, exemple par exemple
182
+ distill eval --task t.yaml --backend ollama # réévalue le modèle quantifié réellement livré
183
+ distill report --task t.yaml # régénère le rapport HTML
184
+ distill publish --task t.yaml --repo compte/modele --dry-run # carte de modèle Hugging Face
185
+ distill cache --clear # vide le cache des appels au professeur
186
+ ```
187
+
188
+ ## Le fichier `task.yaml`
189
+
190
+ Tout le pipeline est piloté par un seul fichier. Le minimum vital :
191
+
192
+ ```yaml
193
+ name: email-triage
194
+ description: Tu tries les emails recus par le service client d'une PME francaise.
195
+ language: francais
196
+
197
+ output_schema:
198
+ type: object
199
+ additionalProperties: false
200
+ required: [categorie, urgence, resume]
201
+ properties:
202
+ categorie:
203
+ type: string
204
+ enum: [reclamation, facturation, technique, commercial, autre]
205
+ urgence:
206
+ type: string
207
+ enum: [basse, moyenne, haute]
208
+ resume:
209
+ type: string
210
+
211
+ seeds: seeds.jsonl # 10 à 50 exemples entrée → sortie attendue
212
+ test_set: test_set.jsonl # écrit à la main, jamais vu à l'entraînement
213
+
214
+ teacher:
215
+ provider: anthropic
216
+ model: claude-opus-5-5
217
+
218
+ student:
219
+ model: Qwen/Qwen2.5-1.5B-Instruct
220
+
221
+ budget:
222
+ max_examples: 3000
223
+ max_cost_usd: 5.0 # plafond dur : dépassé, le run s'arrête proprement
224
+ max_duration_min: 120
225
+ ```
226
+
227
+ L'exemple complet et commenté : [examples/email-triage/task.yaml](https://github.com/Abdelilah04116/distill/blob/main/examples/email-triage/task.yaml).
228
+
229
+ ### Mode 100 % local (RGPD strict)
230
+
231
+ Aucune donnée ne quitte la machine, ni pendant l'entraînement ni après. Le professeur devient un modèle open-weight servi par vLLM :
232
+
233
+ ```bash
234
+ vllm serve Qwen/Qwen2.5-32B-Instruct --port 8000
235
+ ```
236
+
237
+ ```yaml
238
+ teacher:
239
+ provider: openai_compatible
240
+ base_url: http://localhost:8000/v1
241
+ model: Qwen/Qwen2.5-32B-Instruct
242
+ api_key_env: DISTILL_TEACHER_API_KEY
243
+ temperature: 0.9
244
+ ```
245
+
246
+ `distill estimate` affiche alors explicitement qu'aucun coût API n'est engagé. C'est aussi la réponse au risque juridique : certaines conditions d'utilisation interdisent d'entraîner un modèle sur les sorties du fournisseur — vérifiez les vôtres, ou passez en local.
247
+
248
+ ## Évaluation : le protocole
249
+
250
+ La crédibilité du projet tient à un benchmark honnête. Les règles sont appliquées par le code, pas seulement écrites ici :
251
+
252
+ 1. **Le test set est isolé avant toute génération.** Il n'entre jamais dans l'entraînement.
253
+ 2. **Double garde contre la fuite.** Dédup exacte par empreinte, puis dédup sémantique par embeddings contre le test set — un exemple généré trop proche d'un exemple de test est jeté, pas utilisé.
254
+ 3. **Mêmes entrées, même prompt d'inférence pour tous les modèles.** Le professeur ne bénéficie d'aucun prompt enrichi ([prompts.py](https://github.com/Abdelilah04116/distill/blob/main/distill/prompts.py) est la source unique).
255
+ 4. **Une sortie illisible est une erreur**, pas une ligne à ignorer. Un modèle qui répond n'importe quoi une fois sur dix n'obtient pas 100 % sur les neuf autres.
256
+ 5. **Une baseline est systématiquement mesurée** : le même petit modèle sans fine-tuning. C'est ce qui prouve l'apport de la distillation plutôt que celui du modèle de base.
257
+ 6. **Les échecs sont publiés.** Le rapport HTML contient les erreurs réelles de l'élève, non sélectionnées.
258
+
259
+ ### Comparer les trois tailles d'élève
260
+
261
+ Le protocole demande de montrer le compromis taille / qualité. Chaque taille est un run complet, avec le même `task.yaml` et le même test set :
262
+
263
+ ```bash
264
+ for m in Qwen/Qwen2.5-0.5B-Instruct Qwen/Qwen2.5-1.5B-Instruct Qwen/Qwen2.5-3B-Instruct; do
265
+ distill run --task examples/email-triage/task.yaml --student "$m" --skip-generation
266
+ done
267
+ ```
268
+
269
+ `--skip-generation` à partir du deuxième run réutilise le corpus déjà produit : les trois élèves apprennent sur exactement les mêmes données, et la comparaison porte bien sur la taille du modèle. Les trois rapports sont dans `runs/email-triage/`.
270
+
271
+ ### Tableau de résultats
272
+
273
+ Les chiffres sont produits par votre run, sur votre machine. Le rapport les écrit dans `runs/<tâche>/<run>/report.html` et `metrics.json`.
274
+
275
+ | Modèle | Exactitude | F1 macro | JSON valide | Latence moy. | Coût / 1 000 req. |
276
+ |---|---|---|---|---|---|
277
+ | LLM professeur | à mesurer | à mesurer | à mesurer | à mesurer | à mesurer |
278
+ | Qwen 1.5B brut | à mesurer | à mesurer | à mesurer | à mesurer | à mesurer |
279
+ | **Distill 1.5B** | à mesurer | à mesurer | à mesurer | à mesurer | à mesurer |
280
+
281
+ Objectifs de la v1 : **≥ 90 %** du score du professeur, **≥ 10×** moins cher pour 1 000 requêtes, **≥ 5×** plus rapide, le tout en **moins de 2 h sur un GPU**.
282
+
283
+ > Le coût local n'est pas zéro : il est dérivé du temps GPU réellement occupé, au prix horaire que vous déclarez dans `eval.local_gpu_cost_per_hour`. Comparer un coût API à « gratuit » serait malhonnête.
284
+
285
+ ## Matériel
286
+
287
+ | Élève | VRAM nécessaire (QLoRA 4 bits) | Où |
288
+ |---|---|---|
289
+ | 0.5B | ~4 Go | Colab / Kaggle gratuit |
290
+ | 1.5B | ~8 Go | Colab / Kaggle gratuit, RTX 3060 |
291
+ | 3B | ~14 Go | RTX 4090, L4, A10 |
292
+
293
+ Sans GPU local, le notebook [`notebooks/distill_colab.ipynb`](https://github.com/Abdelilah04116/distill/blob/main/notebooks/distill_colab.ipynb) exécute le pipeline complet sur le T4 gratuit de Colab ou Kaggle, compilation de llama.cpp et export GGUF compris. Sinon, tout le reste fonctionne sur CPU — génération, critique, évaluation d'un modèle Ollama, rapport — avec `--skip-training`.
294
+
295
+ ## Structure du dépôt
296
+
297
+ ```
298
+ distill/
299
+ ├── distill/
300
+ │ ├── cli.py # distill run / eval / export / serve / report
301
+ │ ├── graph.py # graphe LangGraph + état persisté
302
+ │ ├── config.py # task.yaml validé par Pydantic
303
+ │ ├── schema.py # JSON schema → modèle Pydantic
304
+ │ ├── prompts.py # le prompt d'inférence, défini une seule fois
305
+ │ ├── metrics.py # F1, exactitude, percentiles (sans sklearn)
306
+ │ ├── costs.py # tarifs, suivi du budget, coût par 1 000 requêtes
307
+ │ ├── dedup.py # embeddings + Qdrant, avec repli sans dépendance
308
+ │ ├── agents/ # generator · critic · evaluator · improver
309
+ │ ├── training/ # lora_trainer (Unsloth ou TRL) · merge
310
+ │ ├── export/ # gguf · ollama
311
+ │ ├── students/ # runners HF, Ollama, professeur
312
+ │ ├── serving/api.py # FastAPI /predict
313
+ │ ├── review.py # relecture humaine du test set
314
+ │ ├── dashboard.py # distill watch
315
+ │ └── report/ # rapport HTML autonome
316
+ ├── examples/email-triage/ # task.yaml + 24 seeds + 201 exemples de test
317
+ ├── notebooks/ # exécution sur GPU gratuit (Colab / Kaggle)
318
+ ├── demo/ # bande VHS du GIF + plan de tournage
319
+ ├── docs/ # architecture, lancement, article
320
+ ├── docker/ # image de service
321
+ └── tests/
322
+ ```
323
+
324
+ Un run produit un dossier autonome :
325
+
326
+ ```
327
+ runs/email-triage/20261003-141205/
328
+ ├── task.resolved.yaml # la config exacte utilisée
329
+ ├── data/ # generated · train · test · rejected (.jsonl)
330
+ ├── train/ # adaptateur LoRA, checkpoints, loss.jsonl
331
+ ├── eval/ # metrics.json, errors.jsonl
332
+ ├── export/ # GGUF + Modelfile
333
+ ├── logs/events.jsonl # journal structuré de toutes les étapes
334
+ └── report.html
335
+ ```
336
+
337
+ ## Coûts
338
+
339
+ Le budget est plafonné dans `task.yaml` et appliqué pendant le run, pas après :
340
+
341
+ - `distill estimate` affiche une estimation **avant** de dépenser ;
342
+ - chaque appel au professeur est mis en cache sur disque — relancer un run ne repaie pas la génération ;
343
+ - au dépassement du plafond, le run s'arrête proprement, l'état et les données déjà produites sont conservés.
344
+
345
+ ## Limites connues
346
+
347
+ Il vaut mieux les lire avant de lancer un run que de les découvrir après.
348
+
349
+ - **Périmètre v1 : tâches textuelles à sortie structurée.** Classification, extraction de champs, routage. Pas de génération de texte long et libre, pas de multimodal, pas de multi-GPU.
350
+ - **Les champs libres ne sont pas notés par égalité de chaînes.** Un résumé est comparé à titre indicatif ; le score porte sur les champs à valeurs fermées. Évaluer un résumé correctement demande un juge, pas un `==`.
351
+ - **Le test set fourni dans `examples/` a été rédigé pour ce dépôt et doit être relu avant de publier des chiffres.** Le protocole parle d'un test set validé à la main : relisez-le, corrigez-le, c'est votre garantie d'honnêteté, pas la nôtre.
352
+ - **La latence du professeur est mesurée sous concurrence** (4 appels en parallèle par défaut), celle de l'élève requête par requête. Le rapport précise la concurrence utilisée.
353
+ - **Unsloth ne tourne pas partout.** Sans lui, le pipeline bascule sur Transformers + PEFT + TRL, plus lent mais équivalent.
354
+ - **Le suivi est un tableau de bord de terminal, pas une interface web.** `distill watch` lit les fichiers que le run écrit de toute façon ; il n'y a ni serveur, ni base, ni historique multi-runs.
355
+
356
+ ## Relire le test set
357
+
358
+ C'est la seule étape que personne ne peut automatiser à votre place, et celle dont dépendent tous les chiffres. Le pipeline l'outille :
359
+
360
+ ```bash
361
+ distill review --task examples/email-triage/task.yaml --status # où en est la relecture
362
+ distill review --task examples/email-triage/task.yaml # valider, corriger, supprimer
363
+ ```
364
+
365
+ Chaque exemple s'affiche avec sa sortie attendue ; vous validez, corrigez ou supprimez. Les champs à valeurs fermées sont proposés sous forme de choix, donc une relecture ne peut pas introduire une valeur hors schéma — et une correction refusée laisse l'exemple intact. L'avancement est écrit à chaque réponse : arrêtez-vous au vingtième, reprenez demain.
366
+
367
+ **Le test set livré dans `examples/` a été rédigé pour la démonstration, pas validé par un humain.** `distill review` est là pour que vous le fassiez avant de publier le moindre chiffre.
368
+
369
+ ## Suivre un run en cours
370
+
371
+ Un run dure jusqu'à deux heures. Dans un second terminal :
372
+
373
+ ```bash
374
+ distill watch --task examples/email-triage/task.yaml
375
+ ```
376
+
377
+ Étapes en cours et terminées, nombre d'exemples retenus, ratio courant face au professeur, et la courbe de loss en sparkline. Tout vient de `logs/events.jsonl`, `train/loss.jsonl` et `state.json`, donc le suivi fonctionne aussi après coup (`--once`) et sur un run lancé par quelqu'un d'autre.
378
+
379
+ ## Publier le modèle
380
+
381
+ ```bash
382
+ distill publish --task examples/email-triage/task.yaml --repo compte/distill-email-triage --dry-run
383
+ ```
384
+
385
+ `--dry-run` écrit la carte de modèle dans `export/README.md` sans rien envoyer : relisez-la, puis relancez sans le drapeau. La carte est remplie avec les chiffres de votre run — tableau comparatif, limites connues, répartition des erreurs réelles, prompt système exact. Le GGUF f16 n'est pas envoyé dès lors qu'une version quantifiée existe.
386
+
387
+ ## Développement
388
+
389
+ ```bash
390
+ git clone https://github.com/Abdelilah04116/distill && cd distill
391
+ pip install -e ".[dev,serve]"
392
+ pytest # tests unitaires, sans GPU ni réseau
393
+ ruff check distill
394
+ mypy distill
395
+ ```
396
+
397
+ Les tests ne font aucun appel réseau : le professeur est remplacé par un faux déterministe ([tests/conftest.py](https://github.com/Abdelilah04116/distill/blob/main/tests/conftest.py)).
398
+
399
+ ## Aller plus loin
400
+
401
+ - [notebooks/distill_colab.ipynb](https://github.com/Abdelilah04116/distill/blob/main/notebooks/distill_colab.ipynb) — le pipeline complet sur un GPU gratuit, de l'installation au GGUF téléchargeable.
402
+ - [demo/](https://github.com/Abdelilah04116/distill/tree/main/demo/) — la bande VHS qui produit le GIF, et le plan de tournage de la vidéo de 60 à 90 s.
403
+ - [docs/architecture.mmd](https://github.com/Abdelilah04116/distill/blob/main/docs/architecture.mmd) — le même schéma en Mermaid, pour l'éditer ou l'embarquer ailleurs.
404
+ - [docs/LANCEMENT.md](https://github.com/Abdelilah04116/distill/blob/main/docs/LANCEMENT.md) — checklist de publication et textes des posts.
405
+ - [docs/article.md](https://github.com/Abdelilah04116/distill/blob/main/docs/article.md) — brouillon de l'article technique.
406
+
407
+ Dans ces trois derniers, les chiffres sont volontairement laissés entre crochets : ne publiez que ce que vous avez mesuré.
408
+
409
+ ## Licence et crédits
410
+
411
+ Apache 2.0 — voir [LICENSE](https://github.com/Abdelilah04116/distill/blob/main/LICENSE).
412
+
413
+ Les modèles élèves (Qwen 2.5, Llama 3.2) et les modèles professeurs restent soumis à leurs licences respectives.
414
+
415
+ Créé par **Abdelilah OURTI**, AI Engineer.