Distillflow 0.2.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 (39) hide show
  1. distillflow-0.2.0/LICENSE +201 -0
  2. distillflow-0.2.0/PKG-INFO +162 -0
  3. distillflow-0.2.0/README.rst +124 -0
  4. distillflow-0.2.0/pyproject.toml +46 -0
  5. distillflow-0.2.0/src/distillflow/common/__init__.py +10 -0
  6. distillflow-0.2.0/src/distillflow/common/common.py +98 -0
  7. distillflow-0.2.0/src/distillflow/common/logger.py +101 -0
  8. distillflow-0.2.0/src/distillflow/config/__init__.py +6 -0
  9. distillflow-0.2.0/src/distillflow/config/config.py +26 -0
  10. distillflow-0.2.0/src/distillflow/config/validator.py +38 -0
  11. distillflow-0.2.0/src/distillflow/datasets/__init__.py +6 -0
  12. distillflow-0.2.0/src/distillflow/datasets/args.py +99 -0
  13. distillflow-0.2.0/src/distillflow/datasets/loader.py +191 -0
  14. distillflow-0.2.0/src/distillflow/datasets/template/__init__.py +12 -0
  15. distillflow-0.2.0/src/distillflow/datasets/template/alpaca.py +85 -0
  16. distillflow-0.2.0/src/distillflow/datasets/template/args.py +56 -0
  17. distillflow-0.2.0/src/distillflow/datasets/template/role.py +10 -0
  18. distillflow-0.2.0/src/distillflow/datasets/template/sharegpt.py +84 -0
  19. distillflow-0.2.0/src/distillflow/datasets/template/template.py +6 -0
  20. distillflow-0.2.0/src/distillflow/evaluation/__init__.py +0 -0
  21. distillflow-0.2.0/src/distillflow/evaluation/rouge.py +30 -0
  22. distillflow-0.2.0/src/distillflow/model/__init__.py +0 -0
  23. distillflow-0.2.0/src/distillflow/model/adapter.py +257 -0
  24. distillflow-0.2.0/src/distillflow/model/args.py +173 -0
  25. distillflow-0.2.0/src/distillflow/model/checkpoint.py +146 -0
  26. distillflow-0.2.0/src/distillflow/model/finetuning_args.py +132 -0
  27. distillflow-0.2.0/src/distillflow/model/generating_args.py +72 -0
  28. distillflow-0.2.0/src/distillflow/model/liger_kernel.py +46 -0
  29. distillflow-0.2.0/src/distillflow/model/loader.py +286 -0
  30. distillflow-0.2.0/src/distillflow/model/quantization.py +193 -0
  31. distillflow-0.2.0/src/distillflow/model/tokenizer.py +55 -0
  32. distillflow-0.2.0/src/distillflow/model/unsloth.py +92 -0
  33. distillflow-0.2.0/src/distillflow/trainer/AdaptationLayer.py +82 -0
  34. distillflow-0.2.0/src/distillflow/trainer/__init__.py +0 -0
  35. distillflow-0.2.0/src/distillflow/trainer/args.py +56 -0
  36. distillflow-0.2.0/src/distillflow/trainer/attention_distillation.py +113 -0
  37. distillflow-0.2.0/src/distillflow/trainer/fine_tuning.py +51 -0
  38. distillflow-0.2.0/src/distillflow/trainer/layers_distillation.py +106 -0
  39. distillflow-0.2.0/src/distillflow/trainer/logits_distillation.py +96 -0
@@ -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 [yyyy] [name of copyright owner]
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,162 @@
1
+ Metadata-Version: 2.3
2
+ Name: Distillflow
3
+ Version: 0.2.0
4
+ Summary:
5
+ Author: Horus Labs
6
+ Author-email: hello@horusailabs.com
7
+ Requires-Python: >=3.12,<3.14
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: accelerate (>=1.2)
12
+ Requires-Dist: bitsandbytes (>=0.44) ; sys_platform == "linux"
13
+ Requires-Dist: boto3 (>=1.35)
14
+ Requires-Dist: config (>=0.5)
15
+ Requires-Dist: datasets (>=3.0)
16
+ Requires-Dist: deepspeed (>=0.15) ; sys_platform == "linux"
17
+ Requires-Dist: evaluate (>=0.4)
18
+ Requires-Dist: google-cloud-compute (>=1.23)
19
+ Requires-Dist: huggingface-hub (>=0.26)
20
+ Requires-Dist: liger-kernel (>=0.5) ; sys_platform == "linux"
21
+ Requires-Dist: numpy (>=2.0)
22
+ Requires-Dist: pandas (>=2.2)
23
+ Requires-Dist: peft (>=0.14)
24
+ Requires-Dist: pydantic (>=2.7)
25
+ Requires-Dist: pyyaml (>=6.0)
26
+ Requires-Dist: runpod (>=1.7)
27
+ Requires-Dist: safetensors (>=0.4)
28
+ Requires-Dist: setuptools (>=75.0)
29
+ Requires-Dist: tiktoken (>=0.9)
30
+ Requires-Dist: tokenizers (>=0.20)
31
+ Requires-Dist: torch (>=2.5)
32
+ Requires-Dist: tqdm (>=4.66)
33
+ Requires-Dist: transformers (>=4.50)
34
+ Requires-Dist: triton (>=3.0) ; sys_platform == "linux"
35
+ Requires-Dist: trl (>=0.13)
36
+ Requires-Dist: unsloth (>=2024.11) ; sys_platform == "linux"
37
+ Description-Content-Type: text/x-rst
38
+
39
+ .. image:: https://s3.us-west-2.amazonaws.com/www.horusailabs.com/distillflow.png
40
+ :target: https://horusailabs.com/
41
+ :align: center
42
+
43
+ DistillFlow
44
+ ===========
45
+
46
+ Overview
47
+ ========
48
+
49
+ DistillFlow is an open-source toolkit designed to simplify and scale the distillation of large language models (LLMs) into smaller, more efficient models. It provides a flexible pipeline for distillation, fine-tuning, and experimentation across multiple GPUs, with support for dynamic resource allocation and easy integration of custom techniques.
50
+
51
+ **What is distillation?**
52
+
53
+ Distillation is the process of transferring knowledge from large machine learning models to small models. The large model is often called the teacher model while the smaller model is called the student model.
54
+
55
+ DistillFlow is maintained by HorusAILabs_.
56
+
57
+ .. _HorusAILabs: https://www.horusailabs.com/
58
+
59
+ Architecture
60
+ ============
61
+ DistillFlow lets you build a fully configurable pipeline, to help with your Distillation.
62
+ Once the data is available, choose a teacher model, and the student model and your dataset
63
+ and finally run the distillation.
64
+
65
+ .. image:: https://s3.us-west-2.amazonaws.com/www.horusailabs.com/distillflow_arch.png
66
+ :align: center
67
+ :height: 600
68
+
69
+ Key Features
70
+ ============
71
+ - **Multi-Strategy Distillation:** Supports multiple distillation techniques such as logits, attention and layers based distillation.
72
+ - **Dynamic Resource Allocation:** Automatically distributes tasks across GPUs or nodes based on available memory.
73
+ - **Fine-Tuning Support:** Allows for domain-specific and downstream fine-tuning of distilled models.
74
+ - **Model Loading Optimizations:** Supports optimized model loading using Unsloth, Liger Kernel, Flash Attention etc.
75
+ - **Easy Integration:** Compatible with popular libraries like Hugging Face Transformers, PyTorch, and DeepSpeed.
76
+
77
+ Requirements
78
+ ============
79
+
80
+ * Python 3.12+
81
+ * Works on Linux, macOS
82
+
83
+ Install
84
+ =======
85
+
86
+ Clone the repository:
87
+
88
+ .. code-block:: bash
89
+
90
+ git clone git@github.com:horus-ai-labs/DistillFlow.git
91
+ cd DistillFlow
92
+ pip3 install poetry
93
+ poetry install
94
+
95
+ Data
96
+ ======
97
+ We support any HuggingFace dataset in ShareGPT or Alpaca formats.
98
+
99
+ Quick Start
100
+ ===========
101
+ Here's a quick example to get started with DistillFlow:
102
+
103
+ Create a training config, specifying your teacher model, student model,
104
+ huggingface dataset and the distillation type.
105
+
106
+ Use one of the existing test configs in `config` folder. The `local_distill.yaml`
107
+ works for Mac.
108
+
109
+ Here is a quick config to get started:
110
+
111
+ .. code-block:: yaml
112
+
113
+ student_model:
114
+ model_name_or_path: Qwen/Qwen2-1.5B
115
+ teacher_model:
116
+ model_name_or_path: Qwen/Qwen2-7B
117
+ data:
118
+ text_field: "text"
119
+ train_datasets:
120
+ - path: mlabonne/FineTome-100k
121
+ template: sharegpt
122
+ distill:
123
+ type: logits
124
+ max_seq_length: 1024
125
+ sft_config:
126
+ output_dir: './results'
127
+ num_train_epochs: 3
128
+ per_device_train_batch_size: 1
129
+ gradient_accumulation_steps: 8
130
+ eval_strategy: steps
131
+ eval_steps: 100
132
+ save_steps: 2000
133
+ learning_rate: 2.0e-5
134
+ weight_decay: 0.05
135
+ warmup_ratio: 0.1
136
+ lr_scheduler_type: 'cosine'
137
+ max_grad_norm: 1.0
138
+ group_by_length: False
139
+ distillation_args:
140
+ temperature: 2.0
141
+ alpha: 0.5
142
+
143
+ Run the command:
144
+
145
+ .. code-block:: bash
146
+
147
+ accelerate launch src/trainer.py --config <your_config_path>
148
+
149
+ Acknowledgement
150
+ ===============
151
+ The repo structure is inspired by `LLamaFactory <https://github.com/hiyouga/LLaMA-Factory>`_.
152
+ The distillation training techniques are inspired by the works of `DistillKit <https://github.com/arcee-ai/DistillKit>`_.
153
+
154
+
155
+ License
156
+ =======
157
+ Distributed under the Apache-2.0 License. See `LICENSE <https://github.com/horus-ai-labs/DistillFlow/blob/main/LICENSE>`_ for more information.
158
+
159
+ Community and Support
160
+ =====================
161
+ - Join the discussion on our `GitHub Discussions <https://github.com/horus-ai-labs/DistillFlow/discussions>`_.
162
+ - Report issues and request features using our `Issue Tracker <https://github.com/horus-ai-labs/DistillFlow/issues>`_.
@@ -0,0 +1,124 @@
1
+ .. image:: https://s3.us-west-2.amazonaws.com/www.horusailabs.com/distillflow.png
2
+ :target: https://horusailabs.com/
3
+ :align: center
4
+
5
+ DistillFlow
6
+ ===========
7
+
8
+ Overview
9
+ ========
10
+
11
+ DistillFlow is an open-source toolkit designed to simplify and scale the distillation of large language models (LLMs) into smaller, more efficient models. It provides a flexible pipeline for distillation, fine-tuning, and experimentation across multiple GPUs, with support for dynamic resource allocation and easy integration of custom techniques.
12
+
13
+ **What is distillation?**
14
+
15
+ Distillation is the process of transferring knowledge from large machine learning models to small models. The large model is often called the teacher model while the smaller model is called the student model.
16
+
17
+ DistillFlow is maintained by HorusAILabs_.
18
+
19
+ .. _HorusAILabs: https://www.horusailabs.com/
20
+
21
+ Architecture
22
+ ============
23
+ DistillFlow lets you build a fully configurable pipeline, to help with your Distillation.
24
+ Once the data is available, choose a teacher model, and the student model and your dataset
25
+ and finally run the distillation.
26
+
27
+ .. image:: https://s3.us-west-2.amazonaws.com/www.horusailabs.com/distillflow_arch.png
28
+ :align: center
29
+ :height: 600
30
+
31
+ Key Features
32
+ ============
33
+ - **Multi-Strategy Distillation:** Supports multiple distillation techniques such as logits, attention and layers based distillation.
34
+ - **Dynamic Resource Allocation:** Automatically distributes tasks across GPUs or nodes based on available memory.
35
+ - **Fine-Tuning Support:** Allows for domain-specific and downstream fine-tuning of distilled models.
36
+ - **Model Loading Optimizations:** Supports optimized model loading using Unsloth, Liger Kernel, Flash Attention etc.
37
+ - **Easy Integration:** Compatible with popular libraries like Hugging Face Transformers, PyTorch, and DeepSpeed.
38
+
39
+ Requirements
40
+ ============
41
+
42
+ * Python 3.12+
43
+ * Works on Linux, macOS
44
+
45
+ Install
46
+ =======
47
+
48
+ Clone the repository:
49
+
50
+ .. code-block:: bash
51
+
52
+ git clone git@github.com:horus-ai-labs/DistillFlow.git
53
+ cd DistillFlow
54
+ pip3 install poetry
55
+ poetry install
56
+
57
+ Data
58
+ ======
59
+ We support any HuggingFace dataset in ShareGPT or Alpaca formats.
60
+
61
+ Quick Start
62
+ ===========
63
+ Here's a quick example to get started with DistillFlow:
64
+
65
+ Create a training config, specifying your teacher model, student model,
66
+ huggingface dataset and the distillation type.
67
+
68
+ Use one of the existing test configs in `config` folder. The `local_distill.yaml`
69
+ works for Mac.
70
+
71
+ Here is a quick config to get started:
72
+
73
+ .. code-block:: yaml
74
+
75
+ student_model:
76
+ model_name_or_path: Qwen/Qwen2-1.5B
77
+ teacher_model:
78
+ model_name_or_path: Qwen/Qwen2-7B
79
+ data:
80
+ text_field: "text"
81
+ train_datasets:
82
+ - path: mlabonne/FineTome-100k
83
+ template: sharegpt
84
+ distill:
85
+ type: logits
86
+ max_seq_length: 1024
87
+ sft_config:
88
+ output_dir: './results'
89
+ num_train_epochs: 3
90
+ per_device_train_batch_size: 1
91
+ gradient_accumulation_steps: 8
92
+ eval_strategy: steps
93
+ eval_steps: 100
94
+ save_steps: 2000
95
+ learning_rate: 2.0e-5
96
+ weight_decay: 0.05
97
+ warmup_ratio: 0.1
98
+ lr_scheduler_type: 'cosine'
99
+ max_grad_norm: 1.0
100
+ group_by_length: False
101
+ distillation_args:
102
+ temperature: 2.0
103
+ alpha: 0.5
104
+
105
+ Run the command:
106
+
107
+ .. code-block:: bash
108
+
109
+ accelerate launch src/trainer.py --config <your_config_path>
110
+
111
+ Acknowledgement
112
+ ===============
113
+ The repo structure is inspired by `LLamaFactory <https://github.com/hiyouga/LLaMA-Factory>`_.
114
+ The distillation training techniques are inspired by the works of `DistillKit <https://github.com/arcee-ai/DistillKit>`_.
115
+
116
+
117
+ License
118
+ =======
119
+ Distributed under the Apache-2.0 License. See `LICENSE <https://github.com/horus-ai-labs/DistillFlow/blob/main/LICENSE>`_ for more information.
120
+
121
+ Community and Support
122
+ =====================
123
+ - Join the discussion on our `GitHub Discussions <https://github.com/horus-ai-labs/DistillFlow/discussions>`_.
124
+ - Report issues and request features using our `Issue Tracker <https://github.com/horus-ai-labs/DistillFlow/issues>`_.
@@ -0,0 +1,46 @@
1
+ [tool.poetry]
2
+ name = "Distillflow"
3
+ version = "0.2.0"
4
+ description = ""
5
+ authors = ["Horus Labs <hello@horusailabs.com>"]
6
+ readme = "README.rst"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = ">=3.12,<3.14"
10
+ setuptools = ">=75.0"
11
+ accelerate = ">=1.2"
12
+ datasets = ">=3.0"
13
+ evaluate = ">=0.4"
14
+ huggingface-hub = ">=0.26"
15
+ numpy = ">=2.0"
16
+ pandas = ">=2.2"
17
+ pydantic = ">=2.7"
18
+ pyyaml = ">=6.0"
19
+ safetensors = ">=0.4"
20
+ tokenizers = ">=0.20"
21
+ torch = ">=2.5"
22
+ tqdm = ">=4.66"
23
+ transformers = ">=4.50"
24
+ trl = ">=0.13"
25
+ peft = ">=0.14"
26
+ runpod = ">=1.7"
27
+ bitsandbytes = { version = ">=0.44", markers = "sys_platform == 'linux'" }
28
+ unsloth = { version = ">=2024.11", markers = "sys_platform == 'linux'" }
29
+ liger-kernel = { version = ">=0.5", markers = "sys_platform == 'linux'" }
30
+ triton = { version = ">=3.0", markers = "sys_platform == 'linux'" }
31
+ deepspeed = { version = ">=0.15", markers = "sys_platform == 'linux'" }
32
+ boto3 = ">=1.35"
33
+ google-cloud-compute = ">=1.23"
34
+ config = ">=0.5"
35
+ tiktoken = ">=0.9"
36
+
37
+ [tool.poetry.group.dev.dependencies]
38
+ pytest = ">=8.0"
39
+ flake8 = ">=7.1"
40
+
41
+ [build-system]
42
+ requires = ["poetry-core"]
43
+ build-backend = "poetry.core.masonry.api"
44
+
45
+ [virtualenvs]
46
+ in-project = true
@@ -0,0 +1,10 @@
1
+ from .common import get_current_device, count_parameters, find_all_linear_modules, infer_optim_dtype
2
+ from .logger import get_logger
3
+
4
+ __all__ = [
5
+ get_current_device,
6
+ count_parameters,
7
+ find_all_linear_modules,
8
+ get_logger,
9
+ infer_optim_dtype
10
+ ]
@@ -0,0 +1,98 @@
1
+ import os
2
+ from typing import Tuple, List
3
+
4
+ from transformers import is_torch_xpu_available, is_torch_npu_available, PreTrainedModel
5
+ from transformers.utils import is_torch_mps_available, is_torch_cuda_available, is_torch_bf16_gpu_available
6
+ import torch
7
+ from .logger import get_logger
8
+
9
+ logger = get_logger(__name__)
10
+
11
+ def get_current_device() -> torch.device:
12
+ local_rank = os.environ.get("LOCAL_RANK", "0")
13
+ device_map = {
14
+ is_torch_xpu_available: "xpu",
15
+ is_torch_npu_available: "npu",
16
+ is_torch_mps_available: "mps",
17
+ is_torch_cuda_available: "cuda"
18
+ }
19
+
20
+ device = "cpu"
21
+ for b, d in device_map.items():
22
+ if b():
23
+ device = "{}:{}".format(d, local_rank)
24
+
25
+ return torch.device(device)
26
+
27
+ def count_parameters(model: "torch.nn.Module") -> Tuple[int, int]:
28
+ r"""
29
+ Returns the number of trainable parameters and number of all parameters in the model.
30
+ """
31
+ trainable_params, all_param = 0, 0
32
+ for param in model.parameters():
33
+ num_params = param.numel()
34
+ # if using DS Zero 3 and the weights are initialized empty
35
+ if num_params == 0 and hasattr(param, "ds_numel"):
36
+ num_params = param.ds_numel
37
+
38
+ # Due to the design of 4bit linear layers from bitsandbytes, multiply the number of parameters by itemsize
39
+ if param.__class__.__name__ == "Params4bit":
40
+ if hasattr(param, "quant_storage") and hasattr(param.quant_storage, "itemsize"):
41
+ num_bytes = param.quant_storage.itemsize
42
+ elif hasattr(param, "element_size"): # for older pytorch version
43
+ num_bytes = param.element_size()
44
+ else:
45
+ num_bytes = 1
46
+
47
+ num_params = num_params * 2 * num_bytes
48
+
49
+ all_param += num_params
50
+ if param.requires_grad:
51
+ trainable_params += num_params
52
+
53
+ return trainable_params, all_param
54
+
55
+
56
+ def find_all_linear_modules(model: PreTrainedModel) -> List[str]:
57
+ r"""
58
+ Finds all available modules to apply lora or galore.
59
+ """
60
+ model_type = getattr(model.config, "model_type", None)
61
+ forbidden_modules = {"lm_head"}
62
+ if model_type == "chatglm":
63
+ forbidden_modules.add("output_layer")
64
+ elif model_type == "internlm2":
65
+ forbidden_modules.add("output")
66
+ elif model_type in ["llava", "llava_next", "llava_next_video", "paligemma", "video_llava"]:
67
+ forbidden_modules.add("multi_modal_projector")
68
+ elif model_type == "qwen2_vl":
69
+ forbidden_modules.add("merger")
70
+
71
+ module_names = set()
72
+ for name, module in model.named_modules():
73
+ if any(forbidden_module in name for forbidden_module in forbidden_modules):
74
+ continue
75
+
76
+ if "Linear" in module.__class__.__name__ and "Embedding" not in module.__class__.__name__:
77
+ module_names.add(name.split(".")[-1])
78
+
79
+ logger.info("Found linear modules: {}".format(",".join(module_names)))
80
+ return list(module_names)
81
+
82
+ _is_fp16_available = is_torch_npu_available() or is_torch_cuda_available()
83
+ try:
84
+ _is_bf16_available = is_torch_bf16_gpu_available() or (is_torch_npu_available() and torch.npu.is_bf16_supported())
85
+ except Exception:
86
+ _is_bf16_available = False
87
+
88
+
89
+ def infer_optim_dtype(model_dtype: torch.dtype) -> torch.dtype:
90
+ r"""
91
+ Infers the optimal dtype according to the model_dtype and device compatibility.
92
+ """
93
+ if _is_bf16_available and model_dtype == torch.bfloat16:
94
+ return torch.bfloat16
95
+ elif _is_fp16_available:
96
+ return torch.float16
97
+ else:
98
+ return torch.float32